task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
response_seed
stringclasses
1 value
instruction_seed
stringlengths
27
14.4k
_source
stringclasses
1 value
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#Logtalk
Logtalk
  :- object(foo).   :- include(bar).   :- end_object.  
Give a code snippet in #Logtalk Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_definition
Singly-linked list/Element definition
singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, Lis...
#Common_Lisp
Common Lisp
(cons 1 (cons 2 (cons 3 nil)) => (1 2 3)
Give a code snippet in #Common_Lisp singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Eleme...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling ...
#Perl
Perl
#! /usr/bin/perl use strict; use XML::Mini::Document;   my @students = ( [ "April", "Bubbly: I'm > Tam and <= Emily" ], [ "Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\"" ], [ "Emily", "Short & shrift" ] );   my $doc = XML::Mini::Document->new(); my $root = $d...
Give a code snippet in #Perl Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> ele...
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#ERRE
ERRE
PROGRAM FORMATTED   PROCEDURE FORMATTED_PRINT(N,LENGTH,DEC_PLACES->FP$)   LOCAL I,C$,NN$   FORMAT$=STRING$(LENGTH,"#")+"."   FOR I=1 TO DEC_PLACES DO FORMAT$=FORMAT$+"#" END FOR   OPEN("O",1,"FORMAT.$$$") WRITE(#1,FORMAT$;N) CLOSE(1)   OPEN("I",1,"FORMAT.$$$") INPUT(LINE...
Give a code snippet in #ERRE Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#CoffeeScript
CoffeeScript
  gcd = (x, y) -> if y == 0 then x else gcd y, x % y  
Give a code snippet in #CoffeeScript Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   g...
christopher/rosetta-code
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1...
#Frink
Frink
  println[binomial[5,3]]  
Give a code snippet in #Frink This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − ...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#Spin
Spin
con _clkmode = xtal1+pll16x _clkfreq = 80_000_000   obj ser : "FullDuplexSerial.spin"   pub init ser.start(31, 30, 0, 115200)   doors   waitcnt(_clkfreq + cnt) ser.stop cogstop(0)   var   byte door[101] ' waste one byte by using only door[1..100]   pri doors | i,j   repeat i from 1 to 100 repeat...
Give a code snippet in #Spin There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ......
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#True_BASIC
True BASIC
  DECLARE SUB hanoi   SUB hanoi(n, desde , hasta, via) IF n > 0 THEN CALL hanoi(n - 1, desde, via, hasta) PRINT "Mover disco"; n; "desde posición"; desde; "hasta posición"; hasta CALL hanoi(n - 1, via, hasta, desde) END IF END SUB   PRINT "Tres discos" PRINT CALL hanoi(3, 1, 2, 3) PRINT PRI...
Give a code snippet in #True_BASIC Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Kotlin
Kotlin
// Version 1.2.31   const val WIDTH = 81 const val HEIGHT = 5   val lines = List(HEIGHT) { CharArray(WIDTH) { '*' } }   fun cantor(start: Int, len: Int, index: Int) { val seg = len / 3 if (seg == 0) return for (i in index until HEIGHT) { for (j in start + seg until start + seg * 2) lines[i][j] = ' '...
Give a code snippet in #Kotlin Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#JavaScript
JavaScript
function shellSort (a) { for (var h = a.length; h > 0; h = parseInt(h / 2)) { for (var i = h; i < a.length; i++) { var k = a[i]; for (var j = i; j >= h && k < a[j - h]; j -= h) a[j] = a[j - h]; a[j] = k; } } return a; }   var a = []; var n ...
Give a code snippet in #JavaScript Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Qui...
christopher/rosetta-code
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a m...
#Axiom
Axiom
(x,xi,y,yi) := (2.0,0.5,4.0,0.25) (z,zi) := (x+y,1/(x+y)) (numbers,invers) := ([x,y,z],[xi,yi,zi]) multiplier(a:Float,b:Float):(Float->Float) == (m +-> a*b*m) [multiplier(number,inver) 0.5 for number in numbers for inver in invers]  
Give a code snippet in #Axiom In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to crea...
christopher/rosetta-code
http://rosettacode.org/wiki/Kronecker_product_based_fractals
Kronecker product based fractals
This task is based on   Kronecker product   of two matrices. If your language has no a built-in function for such product then you need to implement it first. The essence of fractals is self-replication (at least, self-similar replications). So, using   n   times self-product of the matrix   (filled with 0/1)   we ...
#REXX
REXX
/*REXX program calculates the Kronecker product of two arbitrary size matrices. */ parse arg pGlyph . /*obtain optional argument from the CL.*/ if pGlyph=='' | pGlyph=="," then pGlyph= '█' /*Not specified? Then use the default.*/ if length(pGlyph)==2 then pGlyph= x2c(pGlyph) ...
Give a code snippet in #REXX This task is based on   Kronecker product   of two matrices. If your language has no a built-in function for such product then you need to implement it first. The essence of fractals is self-replication (at least, self-similar replications). So, using   n   times self-product of the ma...
christopher/rosetta-code
http://rosettacode.org/wiki/Perlin_noise
Perlin noise
The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random   mapping of   R d ...
#Go
Go
package main   import ( "fmt" "math" )   func main() { fmt.Println(noise(3.14, 42, 7)) }   func noise(x, y, z float64) float64 { X := int(math.Floor(x)) & 255 Y := int(math.Floor(y)) & 255 Z := int(math.Floor(z)) & 255 x -= math.Floor(x) y -= math.Floor(y) z -= math.Floor(z) u :=...
Give a code snippet in #Go The   Perlin noise   is a kind of   gradient noise   invented by   Ken Perlin   around the end of the twentieth century and still currently heavily used in   computer graphics,   most notably to procedurally generate textures or heightmaps. The Perlin noise is basically a   pseudo-random   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#EGL
EGL
  program Matrix_multiplication type BasicProgram {}   function main() a float[][] = [[1,2,3],[4,5,6]]; b float[][] = [[1,2],[3,4],[5,6]]; c float[][] = mult(a, b); end   function mult(a float[][], b float[][]) returns(float[][]) if(a.getSize() == 0) return (new float[0][0]); end if(a[1].getSize() != ...
Give a code snippet in #EGL Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Cut_a_rectangle
Cut a rectangle
A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles...
#zkl
zkl
fcn cut_it(h,w){ if(h.isOdd){ if(w.isOdd) return(0); t,h,w=h,w,t; // swap w,h: a,b=c,d --> a=c; b=d; so need a tmp } if(w==1) return(1);   nxt :=T(T(w+1, 1,0), T(-w-1, -1,0), T(-1, 0,-1), T(1, 0,1)); #[next, dy,dx] blen:=(h + 1)*(w + 1) - 1; grid:=(blen + 1).pump(List(),False); //-->L(Fal...
Give a code snippet in #zkl A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths f...
christopher/rosetta-code
http://rosettacode.org/wiki/One_of_n_lines_in_a_file
One of n lines in a file
A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of the file if possible and m...
#AWK
AWK
#!/usr/bin/gawk -f # # Usage: # gawk -v Seed=$RANDOM -f one_of_n_lines_in_a_file.awk # BEGIN { srand(Seed ? Seed : 1); } { if (NR*rand() < 1 ) { line = $0 } } END { print line; }
Give a code snippet in #AWK A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line ...
christopher/rosetta-code
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar ...
#Factor
Factor
USING: arrays ascii formatting kernel math math.functions math.order sequences ; IN: rosetta-code.vigenere-cipher   : mult-pad ( key input -- x ) [ length ] bi@ 2dup < [ swap ] when / ceiling ;   : lengthen-pad ( key input -- rep-key input ) [ mult-pad ] 2keep [ <repetition> concat ] dip [ length ] keep [ h...
Give a code snippet in #Factor Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of i...
christopher/rosetta-code
http://rosettacode.org/wiki/Dining_philosophers
Dining philosophers
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a rou...
#Wren
Wren
import "random" for Random import "scheduler" for Scheduler import "timer" for Timer   var Rand = Random.new()   var ForkInUse = List.filled(5, false)   class Fork { construct new(name, index) { _name = name _index = index }   index { _index }   pickUp(philosopher) { System.print...
Give a code snippet in #Wren The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eatin...
christopher/rosetta-code
http://rosettacode.org/wiki/Top_rank_per_group
Top rank per group
Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett...
#Forth
Forth
  \ Written in ANS-Forth; tested under VFX. \ Requires the novice package: http://www.forth.org/novice.html \ The following should already be done: \ include novice.4th \ include list.4th   marker TopRank.4th   \ This demonstrates how I typically use lists. A program such as this does not need any explicit iteration, s...
Give a code snippet in #Forth Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#LFE
LFE
  (defun factors (n) (factors n 2 '()))   (defun factors ((1 _ acc) acc) ((n k acc) (when (== 0 (rem n k))) (factors (div n k) k (cons k acc))) ((n k acc) (factors n (+ k 1) acc)))  
Give a code snippet in #LFE The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#Commodore_BASIC
Commodore BASIC
  1 rem rosetta code 2 rem task: animation 10 t$="hello world! ":d=-1 20 print chr$(147);:rem clear screen 30 print "*****************" 35 print "* *" 40 print "* *" 45 print "* *" 50 print "*****************" 60 print "{HOME}{DOWN}{DOWN}{RIGHT}{RIGHT}"t$ 70 get k$ 75 if k$=" "...
Give a code snippet in #Commodore_BASIC Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   Th...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Fur...
#JavaScript
JavaScript
// the constructor function Rational(numerator, denominator) { if (denominator === undefined) denominator = 1; else if (denominator == 0) throw "divide by zero";   this.numer = numerator; if (this.numer == 0) this.denom = 1; else this.denom = denominator;   this.n...
Give a code snippet in #JavaScript Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denomina...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#Run_BASIC
Run BASIC
i = 1024 while i > 0 print i i = int(i / 2) wend end
Give a code snippet in #Run_BASIC Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Dow...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#LLVM
LLVM
  ; const char str[14] = "Hello World!\00" @.str = private unnamed_addr constant [14 x i8] c"Hello, world!\00"   ; declare extern `puts` method declare i32 @puts(i8*) nounwind   define i32 @main() { call i32 @puts( i8* getelementptr ([14 x i8]* @str, i32 0,i32 0)) ret i32 0 }
Give a code snippet in #LLVM Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and th...
#Common_Lisp
Common Lisp
(defconstant +max-score+ 100) (defconstant +n-of-players+ 2)   (let ((scores (make-list +n-of-players+ :initial-element 0)) (current-player 0) (round-score 0)) (loop (format t "Player ~d: (~d, ~d). Rolling? (Y)" current-player (nth current-player scores) round-s...
Give a code snippet in #Common_Lisp The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is adde...
christopher/rosetta-code
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#Fhidwfe
Fhidwfe
  lowers = ['a','z'] uppers = ['A','Z'] function void caesar_encode(message:ptr key:uint) { len = strlen$ message for uint [0u,len) with index { temp = deref_ubyte$ + message index if in temp lowers { temp = + temp key// shift lowercase letters if > temp 'z' { temp = - temp 26ub } ...
Give a code snippet in #Fhidwfe Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z ...
christopher/rosetta-code
http://rosettacode.org/wiki/Odd_word_problem
Odd word problem
Task Write a program that solves the odd word problem with the restrictions given below. Description You are promised an input stream consisting of English letters and punctuations. It is guaranteed that: the words (sequence of consecutive letters) are delimited by one and only one punctuation, the stream will...
#BaCon
BaCon
OPEN "/dev/stdin" FOR DEVICE AS in   FUNCTION get_odd()   LOCAL ch, letter   ch = MEMORY(1) GETBYTE ch FROM in   IF NOT(REGEX(CHR$(PEEK(ch)), "[[:punct:]]")) THEN letter = get_odd() PRINT CHR$(PEEK(ch)); ELSE letter = PEEK(ch) END IF   FREE ch RETURN letter   END ...
Give a code snippet in #BaCon Task Write a program that solves the odd word problem with the restrictions given below. Description You are promised an input stream consisting of English letters and punctuations. It is guaranteed that: the words (sequence of consecutive letters) are delimited by one and only on...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#Forth
Forth
\ csvsum.fs Add a new column named SUM that contain sums from rows of CommaSeparatedValues \ USAGE: \ gforth-fast csvsum.fs -e "stdout stdin csvsum bye" <input.csv >output.csv   CHAR , CONSTANT SEPARATOR 3 CONSTANT DECIMALS 1E1 DECIMALS S>D D>F F** FCONSTANT FSCALE   : colsum ...
Give a code snippet in #Forth CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, chan...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#VBA
VBA
Option Base {0|1}
Give a code snippet in #VBA This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retriev...
christopher/rosetta-code
http://rosettacode.org/wiki/Sexy_primes
Sexy primes
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, sexy primes are prime numbers that differ from each ot...
#Scala
Scala
/* We could reduce the number of functions through a polymorphism since we're trying to retrieve sexy N-tuples (pairs, triplets etc...) but one practical solution would be to use the Shapeless library for this purpose; here we only use built-in Scala packages. */   object SexyPrimes {   /** Check if an input number...
Give a code snippet in #Scala This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, sexy primes are prime n...
christopher/rosetta-code
http://rosettacode.org/wiki/Straddling_checkerboard
Straddling checkerboard
Task Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits. Num...
#Julia
Julia
  function straddlingcheckerboard(board, msg, doencode) lookup = Dict() reverselookup = Dict() row2 = row3 = slash = -1 function encode(x) s = "" for ch in replace(replace(uppercase(x), r"([01-9])", s";=;\1"), r";=;", slash) c = string(ch) if haskey(lookup, c) ...
Give a code snippet in #Julia Task Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#Ring
Ring
  while true see "Spam" end  
Give a code snippet in #Ring Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops...
christopher/rosetta-code
http://rosettacode.org/wiki/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ......
#Quackery
Quackery
[ immovable ]this[ share ]done[ ] is value ( --> x )   [ ]'[ replace ] is to ( x --> )   [ value 1 ] is Q ( --> x ) [ value 0 ] is R ( --> x ) [ value 1 ] is T ( --> x ) [ value 1 ] is K ( --> ...
Give a code snippet in #Quackery Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal s...
christopher/rosetta-code
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#ALGOL_68
ALGOL 68
# PROC to suffix a number with st, nd, rd or th as appropriate # PROC nth = ( INT number )STRING: BEGIN   INT number mod 100 = number MOD 100;   # RESULT # whole( number, 0 ) + IF number mod 100 >= 10 AND number mod 100 <= 20 THEN # numbers in the range 10 .. 20 always have "th" # "th" ...
Give a code snippet in #ALGOL_68 Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to s...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_letter-first_letter
Last letter-first letter
A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the category, they fall out of the ga...
#Common_Lisp
Common Lisp
;;; return all the words that start with an initial letter   (defun filter-with-init (words init) (remove-if-not (lambda (word) (eql init (aref word 0))) words))   ;;; produce a hash table whose key is the initial letter of a word and whose value is ;;; a list of the words that start with that initial letter   (defun...
Give a code snippet in #Common_Lisp A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in ...
christopher/rosetta-code
http://rosettacode.org/wiki/Concurrent_computing
Concurrent computing
Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
#Rust
Rust
extern crate rand; use std::thread; use rand::thread_rng; use rand::distributions::{Range, IndependentSample};   fn main() { let mut rng = thread_rng(); let rng_range = Range::new(0u32, 100); for word in "Enjoy Rosetta Code".split_whitespace() { let snooze_time = rng_range.ind_sample(&mut rng); ...
Give a code snippet in #Rust Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your la...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Elena
Elena
import extensions; import system'routines; import extensions'threading; import system'threading;   static sync = new object();   extension op { sleepSort() { self.forEach:(n) { threadControl.start( { threadControl.sleep(1000 * n);   lock(sy...
Give a code snippet in #Elena Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick so...
christopher/rosetta-code
http://rosettacode.org/wiki/Cramer%27s_rule
Cramer's rule
linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1...
#zkl
zkl
var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) A:=GSL.Matrix(4,4).set(2,-1, 5, 1, 3, 2, 2,-6, 1, 3, 3,-1, 5,-2,-3, 3); b:=GSL.Vector(4).set(-3,-32,-47,49);
Give a code snippet in #zkl linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_duplicate_files
Find duplicate files
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion. Task Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the dire...
#Wren
Wren
import "io" for Directory, File, Stat import "/crypto" for Sha1 import "/sort" for Sort   var findDuplicates = Fn.new { |dir, minSize| if (!Directory.exists(dir)) Fiber.abort("Directory does not exist.") var files = Directory.list(dir).where { |f| Stat.path("%(dir)/%(f)").size >= minSize } var hashMap = {} ...
Give a code snippet in #Wren In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion. Task Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with dup...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#Groovy
Groovy
while (true) { println 'SPAM' }
Give a code snippet in #Groovy Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loo...
christopher/rosetta-code
http://rosettacode.org/wiki/SOAP
SOAP
In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified...
#Tcl
Tcl
package require WS::Client   # Grok the service, and generate stubs ::WS::Client::GetAndParseWsdl http://example.com/soap/wsdl ::WS::Client::CreateStubs ExampleService ;# Assume that's the service name...   # Do the calls set result1 [ExampleService::soapFunc "hello"] set result2 [ExampleService::anotherSoapFunc 3423...
Give a code snippet in #Tcl In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#Liberty_BASIC
Liberty BASIC
input "How much rows would you like? "; n dim a$(n)   for i= 0 to n c = 1 o$ ="" for k =0 to i o$ =o$ ; c; " " c =c *(i-k)/(k+1) next k a$(i)=o$ next i   maxLen = len(a$(n)) for i= 0 to n print space$((maxLen-len(a$(i)))/2);a$(i) next i   end
Give a code snippet in #Liberty_BASIC Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row i...
christopher/rosetta-code
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call
Respond to an unknown method call
Task Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions. Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin...
#Tcl
Tcl
package require TclOO # First create a simple, conventional class and object oo::class create Example { method foo {} { puts "this is foo" } method bar {} { puts "this is bar" } } Example create example   # Modify the object to have a custom ‘unknown method’ interceptor oo::objdefine exa...
Give a code snippet in #Tcl Task Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions. Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of...
christopher/rosetta-code
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#Common_Lisp
Common Lisp
(defvar *probabilities* '((aleph 1/5) (beth 1/6) (gimel 1/7) (daleth 1/8) (he 1/9) (waw 1/10) (zayin 1/11) ...
Give a code snippet in #Common_Lisp Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Becau...
christopher/rosetta-code
http://rosettacode.org/wiki/Speech_synthesis
Speech synthesis
Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
#Nim
Nim
import osproc   discard execCmd("espeak 'Hello world!'")
Give a code snippet in #Nim Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
christopher/rosetta-code
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#Euphoria
Euphoria
function hailstone(atom n) sequence s s = {n} while n != 1 do if remainder(n,2)=0 then n /= 2 else n = 3*n + 1 end if s &= n end while return s end function   function hailstone_count(atom n) integer count count = 1 while n != 1 do ...
Give a code snippet in #Euphoria The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) +...
christopher/rosetta-code
http://rosettacode.org/wiki/The_ISAAC_Cipher
The ISAAC Cipher
ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architectures in nearly all programming...
#C
C
  /* Known to compile and work with tcc in win32 & gcc on Linux (with warnings) ------------------------------------------------------------------------------ readable.c: My random number generator, ISAAC. (c) Bob Jenkins, March 1996, Public Domain You may use this code in any way you wish, and it is free. No warrante...
Give a code snippet in #C ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architecture...
christopher/rosetta-code
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#Python
Python
class empty(object): pass e = empty()
Give a code snippet in #Python Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metap...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#R
R
for(j in 2:10) { r <- sprintf("%d: ", j) for(n in 1:j) { r <- paste(r, format(exp(2i*pi*n/j), digits=4), ifelse(n<j, ",", "")) } print(r) }
Give a code snippet in #R The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
christopher/rosetta-code
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octa...
#Vlang
Vlang
import strings import os import encoding.binary import math   const ( sample_rate = 44100 duration = 8 data_length = sample_rate * duration hdr_size = 44 file_len = data_length + hdr_size - 8 ) fn main() {   // buffers mut buf1 := []byte{len:1} mut buf2 := []byte{len:2} mut b...
Give a code snippet in #Vlang Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi...
christopher/rosetta-code
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform
Burrows–Wheeler transform
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Burrows–Wheeler transform (BWT, also called block-s...
#Raku
Raku
# STX can be any character that doesn't appear in the text. # Using a visible character here for ease of viewing.   constant \STX = '👍';   # Burrows-Wheeler transform sub transform (Str $s is copy) { note "String can't contain STX character." and exit if $s.contains: STX; $s = STX ~ $s; (^$s.chars).map({ ...
Give a code snippet in #Raku This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Burrows–Wheeler trans...
christopher/rosetta-code
http://rosettacode.org/wiki/Formal_power_series
Formal power series
A power series is an infinite sum of the form a 0 + a 1 ⋅ x + a 2 ⋅ x 2 + a 3 ⋅ x 3 + ⋯ {\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots } The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of ...
#J
J
Ai=: (i.@] =/ i.@[ -/ i.@>:@-)&# divide=: [ +/ .*~ [:%.&.x: ] +/ .* Ai diff=: 1 }. ] * i.@# intg=: 0 , ] % 1 + i.@# mult=: +//.@(*/) plus=: +/@,: minus=: -/@,:
Give a code snippet in #J A power series is an infinite sum of the form a 0 + a 1 ⋅ x + a 2 ⋅ x 2 + a 3 ⋅ x 3 + ⋯ {\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots } The ai are called the coefficients of the series. Such sums can be added, multiplied etc., whe...
christopher/rosetta-code
http://rosettacode.org/wiki/Tau_function
Tau function
Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
#Python
Python
def factorize(n): assert(isinstance(n, int)) if n < 0: n = -n if n < 2: return k = 0 while 0 == n%2: k += 1 n //= 2 if 0 < k: yield (2,k) p = 3 while p*p <= n: k = 0 while 0 == n%p: k += 1 n //...
Give a code snippet in #Python Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#Rust
Rust
fn is_palindrome(string: &str) -> bool { let half_len = string.len() / 2; string .chars() .take(half_len) .eq(string.chars().rev().take(half_len)) }   macro_rules! test { ( $( $x:tt ),* ) => { $( println!("'{}': {}", $x, is_palindrome($x)); )* }; }   fn main() { test!( ""...
Give a code snippet in #Rust A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as ...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping
Tokenize a string with escaping
Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for splitting: The fields that were s...
#Swift
Swift
extension String { func tokenize(separator: Character, escape: Character) -> [String] { var token = "" var tokens = [String]() var chars = makeIterator()   while let char = chars.next() { switch char { case separator: tokens.append(token) token = "" case escape: ...
Give a code snippet in #Swift Task[edit] Write a function or program that can split a string at each non-escaped occurrence of a separator character. It should accept three input parameters:   The string   The separator character   The escape character It should output a list of strings. Details Rules for spli...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Bounded
Knapsack problem/Bounded
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature.   So he needs some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th...
#EchoLisp
EchoLisp
  (lib 'struct) (lib 'sql) (lib 'hash)   (define H (make-hash)) (define T (make-table (struct goodies (name poids valeur qty)))) (define IDX (make-vector 0))     ;; convert to 0/1 PB ;; transorm vector [1 2 3 4 (n-max 3) 5 (n-max 2) 6 .. ] ;; into vector of repeated indices : [1 2 3 4 4 4 5 5 6 ... ]   (define (make-01...
Give a code snippet in #EchoLisp A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature.   So he needs some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Ring
Ring
  # Project : Sorting algorithms/Permutation sort   a = [4, 65, 2, 31, 0, 99, 2, 83, 782] result = [] permute(a,1)   for n = 1 to len(result) num = 0 for m = 1 to len(result[n]) - 1 if result[n][m] <= result[n][m+1] num = num + 1 ok next if num = len(result[n]) ...
Give a code snippet in #Ring Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Lambdatalk
Lambdatalk
  {def christian_name Albert} -> christian_name {def name de Jeumont-Schneidre} -> name   {christian_name} {name} -> Albert de Jeumont-Schneidre  
Give a code snippet in #Lambdatalk Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operat...
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Ring
Ring
  see "Degree " + "|" + " Multifactorials 1 to 10" + nl see copy("-", 52) + nl for d = 1 to 5 see "" + d + " " + "| " for n = 1 to 10 see "" + multiFact(n, d) + " " next see nl next   func multiFact n, degree fact = 1 for i = n to 2 step -degree fact = fac...
Give a code snippet in #Ring The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\disp...
christopher/rosetta-code
http://rosettacode.org/wiki/Humble_numbers
Humble numbers
Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above is: humble = 2i × 3j × 5k...
#D
D
import std.conv; import std.stdio;   bool isHumble(int i) { if (i <= 1) return true; if (i % 2 == 0) return isHumble(i / 2); if (i % 3 == 0) return isHumble(i / 3); if (i % 5 == 0) return isHumble(i / 5); if (i % 7 == 0) return isHumble(i / 7); return false; }   void main() { auto limit = sh...
Give a code snippet in #D Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above is:...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#Erlang
Erlang
%% Arithmetic Geometric Mean of 1 and 1 / sqrt(2) %% Author: Abhay Jain   -module(agm_calculator). -export([find_agm/0]). -define(TOLERANCE, 0.0000000001).   find_agm() -> A = 1, B = 1 / (math:pow(2, 0.5)), AGM = agm(A, B), io:format("AGM = ~p", [AGM]).   agm (A, B) when abs(A-B) =< ?TOLERANCE -> A;...
Give a code snippet in #Erlang This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#8086_Assembly
8086 Assembly
;;; Display a Sierpinski triangle on a CGA screen ;;; (order 7 is the maximum that fits in 200 lines) mode: equ 0Fh ; INT 10H call to get current video mode puts: equ 9h ; MS-DOS call to print string cgaseg: equ 0B800h ; Location of CGA video memory cpu 8086 bits 16 org 100h section .text cmp [80h],byte 2 ; Argum...
Give a code snippet in #8086_Assembly Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the vall...
#Go
Go
package raster   func (b *Bitmap) Flood(x, y int, repl Pixel) { targ, _ := b.GetPx(x, y) var ff func(x, y int) ff = func(x, y int) { p, ok := b.GetPx(x, y) if ok && p.R == targ.R && p.G == targ.G && p.B == targ.B { b.SetPx(x, y, repl) ff(x-1, y) ff(x+1, y)...
Give a code snippet in #Go Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards th...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/DOM_serialization
XML/DOM serialization
Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
#Factor
Factor
USING: xml.syntax xml.writer ;   <XML <root><element>Some text here</element></root> XML> pprint-xml
Give a code snippet in #Factor Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#C
C
#include <stdlib.h>   int main() { system("ls"); return 0; }
Give a code snippet in #C Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Nemerle
Nemerle
using System; using System.Console;   module Substrings { Main() : void { string s = "0123456789"; def n = 3; def m = 2; def c = '3'; def z = "345";   WriteLine(s.Substring(n, m)); WriteLine(s.Substring(n, s.Length - n)); WriteLine(s.Substring(0, s...
Give a code snippet in #Nemerle Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#Stata
Stata
mata _gamma_coef = 1.0, 5.772156649015328606065121e-1, -6.558780715202538810770195e-1, -4.200263503409523552900393e-2, 1.665386113822914895017008e-1, -4.219773455554433674820830e-2, -9.621971527876973562114922e-3, 7.218943246663099542395010e-3, -1.165167591859065112113971e-3, -2.152416741149509728157300e-4, 1.28050...
Give a code snippet in #Stata Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/lib...
christopher/rosetta-code
http://rosettacode.org/wiki/SQL-based_authentication
SQL-based authentication
This task has three parts: Connect to a MySQL database (connect_db) Create user/password records in the following table (create_user) Authenticate login requests against the table (authenticate_user) This is the table definition: CREATE TABLE users ( userid INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(...
#Go
Go
package main   import ( "bytes" "crypto/md5" "crypto/rand" "database/sql" "fmt"   _ "github.com/go-sql-driver/mysql" )   func connectDB() (*sql.DB, error) { return sql.Open("mysql", "rosetta:code@/rc") }   func createUser(db *sql.DB, user, pwd string) error { salt := make([]byte, 16) ...
Give a code snippet in #Go This task has three parts: Connect to a MySQL database (connect_db) Create user/password records in the following table (create_user) Authenticate login requests against the table (authenticate_user) This is the table definition: CREATE TABLE users ( userid INT PRIMARY KEY AUTO_INCR...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#Octave
Octave
nchoosek([0:4], 3)
Give a code snippet in #Octave Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Seed7
Seed7
$ include "seed7_05.s7i";   const type: intArray is array integer;   const proc: shuffle (inout intArray: a) is func local var integer: i is 0; var integer: k is 0; var integer: tmp is 0; begin for i range maxIdx(a) downto 2 do k := rand(1, i); tmp := a[i]; a[i] := a[k]; a[k]...
Give a code snippet in #Seed7 The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#PARI.2FGP
PARI/GP
  njd(D) = { my (m, y);   if (D[2] > 2, y = D[1]; m = D[2]+1, y = D[1]-1; m = D[2]+13);   (1461*y)\4 + (306001*m)\10000 + D[3] - 694024 + if (100*(100*D[1]+D[2])+D[3] > 15821004, 2 - y\100 + y\400) }   for (y = 2008, 2121, if (njd([y,12,25]) % 7 == 1, print(y)));  
Give a code snippet in #PARI.2FGP A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years betw...
christopher/rosetta-code
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define ...
#Haskell
Haskell
import Control.Monad (guard) import Text.Printf (printf)   p :: Int -> Int -> Int p l n = calc !! pred n where digitCount = floor $ logBase 10 (fromIntegral l :: Float) log10pwr = logBase 10 2 calc = do raised <- [-1 ..] let firstDigits = floor $ 10 ** (snd (properFract...
Give a code snippet in #Haskell (This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208...
christopher/rosetta-code
http://rosettacode.org/wiki/Yellowstone_sequence
Yellowstone sequence
The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a permutation of the natural n...
#Lua
Lua
function gcd(a, b) if b == 0 then return a end return gcd(b, a % b) end   function printArray(a) io.write('[') for i,v in pairs(a) do if i > 1 then io.write(', ') end io.write(v) end io.write(']') return nil end   function removeAt(a, i) lo...
Give a code snippet in #Lua The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a...
christopher/rosetta-code
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyl...
#VBA
VBA
Private Function kprime(ByVal n As Integer, k As Integer) As Boolean Dim p As Integer, factors As Integer p = 2 factors = 0 Do While factors < k And p * p <= n Do While n Mod p = 0 n = n / p factors = factors + 1 Loop p = p + 1 Loop factors = facto...
Give a code snippet in #VBA A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   wher...
christopher/rosetta-code
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#Haskell
Haskell
fromDegrees :: Floating a => a -> a fromDegrees deg = deg * pi / 180   toDegrees :: Floating a => a -> a toDegrees rad = rad * 180 / pi   main :: IO () main = mapM_ print [ sin (pi / 6) , sin (fromDegrees 30) , cos (pi / 6) , cos (fromDegrees 30) , tan (pi / 6) , tan (fromDegrees 30) ,...
Give a code snippet in #Haskell Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that eva...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#Prolog
Prolog
:- use_module(library(clpfd)).   knapsack :- L = [ item(map, 9, 150), item(compass, 13, 35), item(water, 153, 200), item(sandwich, 50, 160), item(glucose, 15, 60), item(tin, 68, 45), ...
Give a code snippet in #Prolog A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will hav...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#AutoHotkey
AutoHotkey
list = 1,5,17,-2 Loop Parse, list, `, x := x < A_LoopField ? A_LoopField : x MsgBox Max = %x%
Give a code snippet in #AutoHotkey Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls
GUI enabling/disabling of controls
In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI component interaction, write a progr...
#C.2B.2B
C++
file task.h
Give a code snippet in #C.2B.2B In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI com...
christopher/rosetta-code
http://rosettacode.org/wiki/Rhonda_numbers
Rhonda numbers
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors. These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property. 25662 is ...
#Swift
Swift
func digitProduct(base: Int, num: Int) -> Int { var product = 1 var n = num while n != 0 { product *= n % base n /= base } return product }   func primeFactorSum(_ num: Int) -> Int { var sum = 0 var n = num while (n & 1) == 0 { sum += 2 n >>= 1 } v...
Give a code snippet in #Swift A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors. These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
n=5; For[i=1,i<=5,i++, string=""; For[j=1,j<=i,j++,string=string<>"*"]; Print[string] ]
Give a code snippet in #Mathematica.2FWolfram_Language “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterat...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Never
Never
func fizz_buzz() -> int { var i = 1;   for (i = 1; i <= 100; i = i + 1) { /* if (i % 15 == 0) */ if (i % 3 == 0 && i % 5 == 0) { prints("Fizz Buzz\n") } else if (i % 3 == 0) { prints("Fizz\n") } else if (i % 5 == 0) ...
Give a code snippet in #Never Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz...
christopher/rosetta-code
http://rosettacode.org/wiki/Introspection
Introspection
Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop). Extra credit Repor...
#Factor
Factor
: if-older ( n true false -- ) [ build > ] 2dip if ; inline   : when-older ( n true -- ) [ ] if-older ; inline : unless-older ( n false -- ) [ [ ] ] dip if-older ; inline   900 [ "Your version of Factor is too old." print 1 exit ] when-older
Give a code snippet in #Factor Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute ab...
christopher/rosetta-code
http://rosettacode.org/wiki/Hostname
Hostname
Task Find the name of the host on which the routine is running.
#Racket
Racket
  #lang racket/base (require racket/os) (gethostname)  
Give a code snippet in #Racket Task Find the name of the host on which the routine is running.
christopher/rosetta-code
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial ...
#Ruby
Ruby
require 'polynomial'   def x_minus_1_to_the(p) return Polynomial.new(-1,1)**p end   def prime?(p) return false if p < 2 (x_minus_1_to_the(p) - Polynomial.from_string("x**#{p}-1")).coefs.all?{|n| n%p==0} end   8.times do |n| # the default Polynomial#to_s would be OK here; the substitutions just make the # outp...
Give a code snippet in #Ruby The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the c...
christopher/rosetta-code
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\di...
#JavaScript
JavaScript
// Javascript doesn't have built-in support for ranges // Insted we use arrays of two elements to represent ranges var mapRange = function(from, to, s) { return to[0] + (s - from[0]) * (to[1] - to[0]) / (from[1] - from[0]); };   var range = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; for (var i = 0; i < range.length; i++) { ...
Give a code snippet in #JavaScript Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linea...
christopher/rosetta-code
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effect...
#R
R
'%C%' <- function(n, k) choose(n, k) 5 %C% 2 #Outputs 10.
Give a code snippet in #R Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Vlang
Vlang
import rand   fn shuffle_array(mut arr []int) { for i := arr.len - 1; i >= 0; i-- { j := rand.intn(i + 1) arr[i], arr[j] = arr[j], arr[i] } }   fn is_sorted(arr []int) bool { for i := 0; i < arr.len - 1; i++ { if arr[i] > arr[i + 1] { return false } } retu...
Give a code snippet in #Vlang Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick so...
christopher/rosetta-code
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#x86_Assembly
x86 Assembly
# What is the lowest number whose square ends in 269,696?   # At the very end, when we have a result and we need to print it, we shall use for the purpose a program called PRINTF, which forms part of a library of similar utility programs that are provided for us. The codes given here will be needed at that point to tel...
Give a code snippet in #x86_Assembly Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electron...
christopher/rosetta-code
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative...
#ALGOL_68
ALGOL 68
BEGIN # shuffle a string so as many as possible characters are moved # PROC best shuffle = ( STRING orig )STRING: BEGIN STRING res := orig; FOR i FROM LWB orig TO UPB orig DO FOR j FROM LWB orig TO UPB orig DO IF i /= j AND orig[ i ] /= res[ j ] AND orig[ j ] /= res[ ...
Give a code snippet in #ALGOL_68 Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every ti...
christopher/rosetta-code
http://rosettacode.org/wiki/Fivenum
Fivenum
Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the   R   programming language i...
#J
J
midpts=: (1 + #) <:@(] , -:@[ , -) -:@<.@-:@(3 + #) NB. mid points of y quartiles=: -:@(+/)@((<. ,: >.)@midpts { /:~@]) NB. quartiles of y fivenum=: <./ , quartiles , >./ NB. fivenum summary of y
Give a code snippet in #J Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#UnixPipes
UnixPipes
rm -f _sortpass   reset() { test -f _tosort || mv _sortpass _tosort }   bpass() { (read a; read b test -n "$b" -a "$a" && ( test $a -gt $b && (reset; echo $b; (echo $a ; cat) | bpass ) || (echo $a; (echo $b ; cat) | bpass ) ) || echo $a) }   bubblesort() { cat > _tosort while test -f _tosort do ...
Give a code snippet in #UnixPipes Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Harmonic_series
Harmonic series
This page uses content from Wikipedia. The original article was at Harmonic number. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, the n-th harmonic number is the sum of the recipr...
#Julia
Julia
const memoizer = [BigFloat(1.0), BigFloat(1.5)]   """ harmonic(n::Integer)::BigFloat Calculates harmonic numbers. The integer argument `n` should be positive. """ function harmonic(n::Integer)::BigFloat if n < 0 throw(DomainError(n)) elseif n == 0 return BigFloat(0.0) # by convention e...
Give a code snippet in #Julia This page uses content from Wikipedia. The original article was at Harmonic number. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, the n-th harmonic ...
christopher/rosetta-code
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#VBScript
VBScript
' Align columns - RC - VBScript Const nr=16, nc=16 ReDim d(nc),t(nr), wor(nr,nc) i=i+1: t(i) = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" i=i+1: t(i) = "are$delineated$by$a$single$'dollar'$character,$write$a$program" i=i+1: t(i) = "that$aligns$each$column$of$fields$by$ensuring$that$words$in$eac...
Give a code snippet in #VBScript Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix
Sum of elements below main diagonal of matrix
Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
#AutoHotkey
AutoHotkey
matrx :=[[1,3,7,8,10] ,[2,4,16,14,4] ,[3,1,9,18,11] ,[12,14,17,18,20] ,[7,1,3,9,5]] sumA := sumB := sumD := sumAll := 0 for r, obj in matrx for c, val in obj sumAll += val ,sumA += r<c ? val : 0 ,sumB += r>c ? val : 0 ,sumD += r=c ? val : 0   MsgBox % result := "sum above diagonal = " sumA . "`nsum b...
Give a code snippet in #AutoHotkey Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
christopher/rosetta-code
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Forth
Forth
unused . \ memory available for use in dictionary here . \ current dictionary memory pointer : mem, ( addr len -- ) here over allot swap move ; : s, ( str len -- ) here over char+ allot place align ; \ built-in on some forths : ," [char] " parse s, ; variable num create array 60 cells allot create struct 0 , 1...
Give a code snippet in #Forth Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#IDL
IDL
x = [3,1,4,1,5,9] print,mean(x)
Give a code snippet in #IDL Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an establ...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's eval...
#Nim
Nim
import math, sequtils   echo "5^3^2 = ", 5^3^2 echo "(5^3)^2 = ", (5^3)^2 echo "5^(3^2) = ", 5^(3^2) echo "foldl([5, 3, 2], a^b) = ", foldl([5, 3, 2], a^b) echo "foldr([5, 3, 2], a^b) = ", foldr([5, 3, 2], a^b)
Give a code snippet in #Nim This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show th...
christopher/rosetta-code
http://rosettacode.org/wiki/Order_disjoint_list_items
Order disjoint list items
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Kotlin
Kotlin
// version 1.0.6   const val NULL = "\u0000"   fun orderDisjointList(m: String, n: String): String { val nList = n.split(' ') // first replace the first occurrence of items of 'n' in 'm' with the NULL character // which we can safely assume won't occur in 'm' naturally var p = m for (item in nList)...
Give a code snippet in #Kotlin Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#TI-83_BASIC
TI-83 BASIC
Disp [A]*[B]
Give a code snippet in #TI-83_BASIC Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Function_prototype
Function prototype
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions for prototype declarations A p...
#C.23
C#
using System; abstract class Printer { public abstract void Print(); }   class PrinterImpl : Printer { public override void Print() { Console.WriteLine("Hello world!"); } }
Give a code snippet in #C.23 Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions f...
christopher/rosetta-code