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/Permutation_test
Permutation test
Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n {\displaystyle n} treatment...
#11l
11l
V data = [85, 88, 75, 66, 25, 29, 83, 39, 97, 68, 41, 10, 49, 16, 65, 32, 92, 28, 98]   F pick(at, remain, accu, treat) I remain == 0 R I accu > treat {1} E 0 R pick(at - 1, remain - 1, accu + :data[at - 1], treat) + (I at > remain {pick(at - 1, remain, accu, treat)} E 0)   V treat = 0 V total =...
Give a code snippet in #11l Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n ...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_characters
Special characters
Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact...
#ALGOL_68
ALGOL 68
printf(($"flip:"g"!"l$,flip)); printf(($"flop:"g"!"l$,flop)); printf(($"blank:"g"!"l$,blank)); printf(($"error char:"g"!"l$,error char)); printf(($"null character:"g"!"l$,null character))
Give a code snippet in #ALGOL_68 Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling...
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#SAS
SAS
data _null_; a="Hello,"; b="World!"; c=a !! " " !! b; put c; *Alternative using the catx function; c=catx (" ", a, b); put c; run;
Give a code snippet in #SAS String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string liter...
christopher/rosetta-code
http://rosettacode.org/wiki/Arena_storage_pool
Arena storage pool
Dynamically allocated objects take their memory from a heap. The memory for an object is provided by an allocator which maintains the storage pool used for the heap. Often a call to allocator is denoted as P := new T where   T   is the type of an allocated object,   and   P   is a reference to the object. The stora...
#Delphi
Delphi
  program Arena_storage_pool;   {$APPTYPE CONSOLE}   uses Winapi.Windows, System.SysUtils, system.generics.collections;   type TPool = class private FStorage: TList<Pointer>; public constructor Create; destructor Destroy; override; function Allocate(aSize: Integer): Pointer; function Rel...
Give a code snippet in #Delphi Dynamically allocated objects take their memory from a heap. The memory for an object is provided by an allocator which maintains the storage pool used for the heap. Often a call to allocator is denoted as P := new T where   T   is the type of an allocated object,   and   P   is a ref...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#HicEst
HicEst
DLG(Edit=A, DNum, MIn=-1000, MAx=1000, E=B, DN, MI=-1000, MA=1000) WRITE(Messagebox, Name) A, B, "Sum = ", A+B
Give a code snippet in #HicEst A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separat...
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)(...
#F.23
F#
let rec mfact d = function | n when n <= d -> n | n -> n * mfact d (n-d)   [<EntryPoint>] let main argv = let (|UInt|_|) = System.UInt32.TryParse >> function | true, v -> Some v | false, _ -> None let (maxDegree, maxN) = match argv with | [| UInt d; UInt n |] -> (int d, int n) ...
Give a code snippet in #F.23 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/Host_introspection
Host introspection
Print the word size and endianness of the host machine. See also: Variable size/Get
#Slate
Slate
inform: 'Endianness: ' ; Platform current endianness. inform: 'Word Size: ' ; (Platform current bytesPerWord * 8) printString.
Give a code snippet in #Slate Print the word size and endianness of the host machine. See also: Variable size/Get
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#ALGOL_W
ALGOL W
begin  % returns a string representing the number in s incremented  %  % As strings are fixed length, the significant length of s must %  % be specified in length  %  % s must contain an unsigned integer  %  % If the string is invalid or ...
Give a code snippet in #ALGOL_W Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#Bracmat
Bracmat
1000000000:?MOD; tbl$(state,55); 0:?si:?sj;   (subrand-seed= i,j,p2 . 1:?p2 & mod$(!arg,!MOD):?(0$?state) & 1:?i & 21:?j & whl ' ( !i:<55 & (!j:~<55&!j+-55:?j|) & !p2:?(!j$?state) & (  !arg+-1*!p2:?p2:<0 & !p2+!MOD:?p2 | ) & !(!j$state):?arg & !...
Give a code snippet in #Bracmat A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod...
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...
#Vala
Vala
  double arithmetic(double[] list){ double mean; double sum = 0;   if (list.length == 0) return 0.0; foreach(double number in list){ sum += number; } // foreach   mean = sum / list.length;   return mean; } // end arithmetic mean   public static void main(){ double[] test = {1.0, 2.0, 5.0, -5.0, 9.5, 3.14159...
Give a code snippet in #Vala 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 estab...
christopher/rosetta-code
http://rosettacode.org/wiki/Jewels_and_stones
Jewels and stones
Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case ...
#VBA
VBA
Function count_jewels(stones As String, jewels As String) As Integer Dim res As Integer: res = 0 For i = 1 To Len(stones) res = res - (InStr(1, jewels, Mid(stones, i, 1), vbBinaryCompare) <> 0) Next i count_jewels = res End Function Public Sub main() Debug.Print count_jewels("aAAbbbb", "aA")...
Give a code snippet in #VBA Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case l...
christopher/rosetta-code
http://rosettacode.org/wiki/Plasma_effect
Plasma effect
The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid. Task Create a plasma effect. See also Computer Graphics Tutorial (lod...
#Gosu
Gosu
  uses javax.swing.* uses java.awt.* uses java.awt.image.* uses java.awt.event.ActionEvent uses java.awt.image.BufferedImage#* uses java.lang.Math#*   var size = 400 EventQueue.invokeLater(\ -> showPlasma())   function showPlasma() { var frame = new JFrame("Plasma") {:Resizable = false, :DefaultCloseOperation = JFram...
Give a code snippet in #Gosu The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid. Task Create a plasma effect. See also C...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Eiffel
Eiffel
class APPLICATION   create make   feature {NONE} -- Initialization   make do move (4, "A", "B", "C") end   feature -- Towers of Hanoi   move (n: INTEGER; frm, to, via: STRING) require n > 0 do if n = 1 then print ("Move disk from pole " + frm + " to pole " + to + "%N") else m...
Give a code snippet in #Eiffel Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e...
#Visual_Basic_.NET
Visual Basic .NET
Module MagicSquares   Function MagicSquareDoublyEven(n As Integer) As Integer(,) If n < 4 OrElse n Mod 4 <> 0 Then Throw New ArgumentException("base must be a positive multiple of 4") End If   'pattern of count-up vs count-down zones Dim bits = Convert.ToInt32("1001011001...
Give a code snippet in #Visual_Basic_.NET A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order...
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...
#FUZE_BASIC
FUZE BASIC
READ x,y,z PRINT "Open doors: ";x;" "; CYCLE z=x+y PRINT z;" "; x=z y=y+2 REPEAT UNTIL z>=100 DATA 1,3,0 END
Give a code snippet in #FUZE_BASIC 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, #...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#Wren
Wren
var csv = "Character,Speech\n" + "The multitude,The messiah! Show us the messiah!\n" + "Brians mother,<angry>Now you listen here! He's not the messiah; " + "he's a very naughty boy! Now go away!</angry>\n" + "The multitude,Who are you?\n" + "Brians mother,I'm his mother; that's who!\n" + "Th...
Give a code snippet in #Wren Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Cre...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_proper_divisor_of_n
Largest proper divisor of n
Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
#Draco
Draco
proc nonrec lpd(word n) word: word d; if n=1 then 1 else d := n-1; while n % d /= 0 do d := d-1 od; d fi corp   proc nonrec main() void: word n; for n from 1 upto 100 do write(lpd(n):3); if n%10 = 0 then writeln() fi od corp
Give a code snippet in #Draco Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
christopher/rosetta-code
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#PicoLisp
PicoLisp
(let File "test.file" (and (info File) (prinl (stamp (cadr @) (cddr @))) ) # Print date and time in UTC (call 'touch File) ) # Set modification time to "now"
Give a code snippet in #PicoLisp Task Get and set the modification time of a file.
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
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 |...
#Crystal
Crystal
a = gets.not_nil!.to_i64 b = gets.not_nil!.to_i64   puts "Sum: #{a + b}" puts "Difference: #{a - b}" puts "Product: #{a * b}" puts "Quotient (float division): #{a / b}" # / always returns a float. puts "Quotient (floor division): #{a // b}" puts "Remainder: #{a % b}" # Sign of remainder matches that of the second oper...
Give a code snippet in #Crystal 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/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#Bracmat
Bracmat
  ( 0:?max & :?seq & -1 -2 3 5 6 -2 -1 4 -4 2 -1  :  ? [%( ( = s sum . ( sum = A .  !arg:%?A ?arg&!A+sum$!arg | 0 ) & ( sum$!sjt:>!max:?max ...
Give a code snippet in #Bracmat Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements ar...
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) ...
#PL.2FM
PL/M
100H:   /* DECLARE OUTPUT IN TERMS OF CP/M - PL/M DOES NOT COME WITH ANY STANDARD LIBRARY */ BDOS: PROCEDURE(FUNC, ARG); DECLARE FUNC BYTE, ARG ADDRESS; GO TO 5; END BDOS;   PUT$STRING: PROCEDURE(STR); DECLARE STR ADDRESS; CALL BDOS(9, STR); CALL BDOS(9, .(13,10,'$')); END PUT$STRING;   /* PRINT...
Give a code snippet in #PL.2FM 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   FizzBuz...
christopher/rosetta-code
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#Elixir
Elixir
defmodule God do def g(n,g) when g == 1 or n < g, do: 1 def g(n,g) do Enum.reduce(2..g, 1, fn q,res -> res + (if q > n-g, do: 0, else: g(n-g,q)) end) end end   Enum.each(1..25, fn n -> IO.puts Enum.map(1..n, fn g -> "#{God.g(n,g)} " end) end)
Give a code snippet in #Elixir This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 ha...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the...
#PARI.2FGP
PARI/GP
estack = [];   epush(x) = { estack = vector(#estack + 1, i, if(i <= #estack, estack[i], x)); return(#estack); };   epop() = { local(val = estack[#estack]); estack = vector(#estack - 1, i, estack[i]); return(val); };   registerRPNToken(t) = { local(o1, o2);   if(type(t) == "t_STR", if...
Give a code snippet in #PARI.2FGP Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with th...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_easy
Abbreviations, easy
This task is an easier (to code) variant of the Rosetta Code task:   Abbreviations, simple. For this task, the following   command table   will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find ...
#REXX
REXX
/*REXX program validates a user "word" against a "command table" with abbreviations.*/ parse arg uw /*obtain optional arguments from the CL*/ if uw='' then uw= 'riG rePEAT copies put mo rest types fup. 6 poweRin' say 'user words: ' uw   @= 'Add ALTer BAckup...
Give a code snippet in #REXX This task is an easier (to code) variant of the Rosetta Code task:   Abbreviations, simple. For this task, the following   command table   will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlic...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typica...
#Fortran
Fortran
program cdemo complex :: a = (5,3), b = (0.5, 6.0) ! complex initializer complex :: absum, abprod, aneg, ainv   absum = a + b abprod = a * b aneg = -a ainv = 1.0 / a end program cdemo
Give a code snippet in #Fortran A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\display...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Joy
Joy
DEFINE fib == [small] [] [pred dup pred] [+] binrec.
Give a code snippet in #Joy The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are g...
christopher/rosetta-code
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#Burlesque
Burlesque
  blsq ) 6 -.^^0\/r@\/'0\/.*'1+]\/{\/{rt}\/E!XX}x/+]m[sp 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1  
Give a code snippet in #Burlesque Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0...
christopher/rosetta-code
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#UNIX_Shell
UNIX Shell
echo alphaBETA | tr '[a-z]' '[A-Z]' # => ALPHABETA echo alphaBETA | tr '[A-Z]' '[a-z]' # => alphabeta
Give a code snippet in #UNIX_Shell Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sleep
Sleep
Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread for the given amount of time. ...
#J
J
sleep =: 6!:3   sleeping=: monad define smoutput 'Sleeping...' sleep y smoutput 'Awake!' )
Give a code snippet in #J Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread for...
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) ...
#Monte
Monte
def fizzBuzz(top): var t := 1 while (t < top): if ((t % 3 == 0) || (t % 5 == 0)): if (t % 15 == 0): traceln(`$t FizzBuzz`) else if (t % 3 == 0): traceln(`$t Fizz`) else: traceln(`$t Buzz`) t += 1   fizzBuzz(10...
Give a code snippet in #Monte 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/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given f...
#Draco
Draco
/* 8080 machine code in an array */ [6] byte add_mc = ( 0xC1, /* POP B - get return address */ 0xD1, /* POP D - get second argument */ 0xE1, /* POP H - get first argument */ 0x19, /* DAD D - add arguments */ 0xC5, /* PUSH B - push return address back...
Give a code snippet in #Draco The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assem...
christopher/rosetta-code
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#zig
zig
const std = @import("std"); const fs = std.fs;   pub fn main() !void { const here = fs.cwd(); try here.deleteFile("input.txt"); try here.deleteDir("docs");   const root = try fs.openDirAbsolute("/", .{}); try root.deleteFile("input.txt"); try root.deleteDir("docs"); }
Give a code snippet in #zig Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers...
#PicoLisp
PicoLisp
(de mem (N) (nth (quote 15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0 ) (inc N) ) )   (for (IP (mem 0) IP) (let (A (pop 'IP) B (pop 'IP) C (pop 'IP)) (cond ((lt0 A) (set (mem B) (char))) ((lt0 B) (prin (...
Give a code snippet in #PicoLisp Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of...
christopher/rosetta-code
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#Euler_Math_Toolbox
Euler Math Toolbox
  >function horner (x,v) ... $ n=cols(v); res=v{n}; $ loop 1 to n-1; res=res*x+v{n-#}; end; $ return res $endfunction >v=[-19,7,-4,6] [ -19 7 -4 6 ] >horner(2,v) // test Horner 27 >evalpoly(2,v) // built-in Horner 27 >horner(I,v) // complex values -15+1i >horner(1±0.05,v) // interval values ~-10.9,-9.11~ >fu...
Give a code snippet in #Euler_Math_Toolbox A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + (...
christopher/rosetta-code
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. 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 haversine formula is an equation important in navigation, g...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Math   Module Module1   Const deg2rad As Double = PI / 180   Structure AP_Loc Public IATA_Code As String, Lat As Double, Lon As Double   Public Sub New(ByVal iata_code As String, ByVal lat As Double, ByVal lon As Double) Me.IATA_Code = iata_code : Me.Lat = lat * deg2rad : Me.Lon = lon *...
Give a code snippet in #Visual_Basic_.NET This page uses content from Wikipedia. The original article was at Haversine formula. 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 haversine formul...
christopher/rosetta-code
http://rosettacode.org/wiki/Enforced_immutability
Enforced immutability
Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
#PHP
PHP
define("PI", 3.14159265358); define("MSG", "Hello World");
Give a code snippet in #PHP Task Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created.
christopher/rosetta-code
http://rosettacode.org/wiki/Stream_merge
Stream merge
2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was. N-strea...
#D
D
import std.range.primitives; import std.stdio;   // An output range for writing the elements of the example ranges struct OutputWriter { void put(E)(E e) if (!isInputRange!E) { stdout.write(e); } }   void main() { import std.range : only; merge2(OutputWriter(), only(1,3,5,7), only(2,4,6,8)); ...
Give a code snippet in #D 2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#MATLAB_.2F_Octave
MATLAB / Octave
% Demonstrate how to assign an empty string to a variable. str = ''; % Demonstrate how to check that a string is empty. isempty(str) (length(str)==0) % Demonstrate how to check that a string is not empty. ~isempty(str) (length(str)>0)
Give a code snippet in #MATLAB_.2F_Octave Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not e...
christopher/rosetta-code
http://rosettacode.org/wiki/Interactive_programming_(repl)
Interactive programming (repl)
Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. Task Show how to start this...
#BQN
BQN
Join ← {a 𝕊 b‿c: b∾a∾a∾c} (function block) ":" Join "Rosetta"‿"Code" "Rosetta::Code"
Give a code snippet in #BQN Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Topic_variable
Topic variable
Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate h...
#J
J
example=: *:, %: NB. *: is square, %: is square root example 3 9 1.73205
Give a code snippet in #J Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic variable within the language a...
christopher/rosetta-code
http://rosettacode.org/wiki/ISBN13_check_digit
ISBN13 check digit
Task Validate the check digit of an ISBN-13 code:   Multiply every other digit by  3.   Add these numbers and the other digits.   Take the remainder of this number after division by  10.   If it is  0,   the ISBN-13 check digit is correct. Use the following codes for testing:   978-1734314502       (good)   ...
#Kotlin
Kotlin
  fun isValidISBN13(text: String): Boolean { val isbn = text.replace(Regex("[- ]"), "") return isbn.length == 13 && isbn.map { it - '0' } .mapIndexed { index, value -> when (index % 2) { 0 -> value else -> 3 * value } } .sum() % 10 == 0 }  
Give a code snippet in #Kotlin Task Validate the check digit of an ISBN-13 code:   Multiply every other digit by  3.   Add these numbers and the other digits.   Take the remainder of this number after division by  10.   If it is  0,   the ISBN-13 check digit is correct. Use the following codes for testing:  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Long_literals,_with_continuations
Long literals, with continuations
This task is about writing a computer program that has long literals   (character literals that may require specifying the words/tokens on more than one (source) line,   either with continuations or some other method, such as abutments or concatenations   (or some other mechanisms). The literal is to be in the form ...
#Phix
Phix
constant last_updated = "March 24th, 2020", elements_text = ` hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon potassium calc...
Give a code snippet in #Phix This task is about writing a computer program that has long literals   (character literals that may require specifying the words/tokens on more than one (source) line,   either with continuations or some other method, such as abutments or concatenations   (or some other mechanisms). The...
christopher/rosetta-code
http://rosettacode.org/wiki/Determinant_and_permanent
Determinant and permanent
For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the permanent is given by ...
#EchoLisp
EchoLisp
  (lib 'list) (lib 'matrix)   ;; adapted from Racket (define (permanent M) (let (( n (matrix-row-num M))) (for/sum ([σ (in-permutations n)]) (for/product ([i n] [σi σ]) (array-ref M i σi)))))   ;; output (define A (list->array '(1 2 3 4) 2 2)) (array-print A) 1 2 3 4 (determinant A) → ...
Give a code snippet in #EchoLisp For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} whil...
christopher/rosetta-code
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#Swift
Swift
import Foundation   typealias SodukuPuzzle = [[Int]]   class Soduku { let mBoardSize:Int! let mBoxSize:Int! var mBoard:SodukuPuzzle! var mRowSubset:[[Bool]]! var mColSubset:[[Bool]]! var mBoxSubset:[[Bool]]!   init(board:SodukuPuzzle) { mBoard = board mBoardSize = board.count...
Give a code snippet in #Swift Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
christopher/rosetta-code
http://rosettacode.org/wiki/Spinning_rod_animation/Text
Spinning rod animation/Text
Task An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the previous frame being cleared be...
#Wren
Wren
import "io" for Stdout import "timer" for Timer   var ESC = "\u001b"   var a = "|/-\\" System.write("%(ESC)[?25l") // hide the cursor var start = System.clock var asleep = 0 while (true) { for (i in 0..3) { System.write("%(ESC)[2J") // clear terminal System.write("%(ESC)[0;0H") // place...
Give a code snippet in #Wren Task An animation with the following frames in the following order (if certain characters aren't available or can't be used correctly in the programming language, alternate characters can replace any of these frames) must animate with a delay of 0.25 seconds between each frame, with the p...
christopher/rosetta-code
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation langu...
#Rust
Rust
pub struct CumulativeStandardDeviation { n: f64, sum: f64, sum_sq: f64 }   impl CumulativeStandardDeviation { pub fn new() -> Self { CumulativeStandardDeviation { n: 0., sum: 0., sum_sq: 0. } }   fn push(&mut self, x: f64) -> f64 { self...
Give a code snippet in #Rust Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the functi...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#Euphoria
Euphoria
  function s( atom x ) return 1 / power( x, 2 ) end function   function sum( atom low, atom high ) atom ret = 0.0 for i = low to high do ret = ret + s( i ) end for return ret end function   printf( 1, "%.15f\n", sum( 1, 1000 ) )
Give a code snippet in #Euphoria Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k ...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#Python
Python
import numpy as np   height = [1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83] weight = [52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46]   X = np.mat(height**np.arange(3)[:, None]) y = np.mat(weight)   print(y * X...
Give a code snippet in #Python Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . ...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Babel
Babel
strrev: { str2ar ar2ls reverse ls2lf ar2str }
Give a code snippet in #Babel Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty...
christopher/rosetta-code
http://rosettacode.org/wiki/Sleep
Sleep
Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread for the given amount of time. ...
#Lasso
Lasso
stdoutnl('Sleeping...') sleep(5000) // Sleep 5 seconds stdoutnl('Awake!')
Give a code snippet in #Lasso Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread...
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...
#Fortran
Fortran
  program almost_prime use iso_fortran_env, only: output_unit implicit none   integer :: i, c, k   do k = 1, 5 write(output_unit,'(A3,x,I0,x,A1,x)', advance="no") "k =", k, ":" i = 2 c = 0 do if (c >= 10) exit   if (kprime(i, k)) then ...
Give a code snippet in #Fortran 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,   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#Ada
Ada
with Ada.Text_IO;   procedure Van_Eck_Sequence is   Sequence : array (Natural range 1 .. 1_000) of Natural;   procedure Calculate_Sequence is begin Sequence (Sequence'First) := 0; for Index in Sequence'First .. Sequence'Last - 1 loop Sequence (Index + 1) := 0; for I in reverse Seq...
Give a code snippet in #Ada The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured p...
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#HicEst
HicEst
value = XEQ( " temp = 1 + 2 + 3 ") ! value is assigned 6 ! temp is undefined outside XEQ, if it was not defined before.   XEQ(" WRITE(Messagebox) 'Hello World !' ")   OPEN(FIle="my_file.txt") READ(FIle="my_file.txt", Row=6) string XEQ( string ) ! executes row 6 of my_file.txt
Give a code snippet in #HicEst Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applic...
christopher/rosetta-code
http://rosettacode.org/wiki/Sleep
Sleep
Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread for the given amount of time. ...
#Haskell
Haskell
import Control.Concurrent   main = do seconds <- readLn putStrLn "Sleeping..." threadDelay $ round $ seconds * 1000000 putStrLn "Awake!"
Give a code snippet in #Haskell Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thre...
christopher/rosetta-code
http://rosettacode.org/wiki/Barnsley_fern
Barnsley fern
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ƒ2   (chosen 85% of the time) ...
#Applesoft_BASIC
Applesoft BASIC
100 LET YY(1) = .16 110 XX(2) = .85:XY(2) = .04 120 YX(2) = - .04:YY(2) = .85 130 LET Y(2) = 1.6 140 XX(3) = .20:XY(3) = - .26 150 YX(3) = .23:YY(3) = .22 160 LET Y(3) = 1.6 170 XX(4) = - .15:XY(4) = .28 180 YX(4) = .26:YY(4) = .24 190 LET Y(4) = .44 200 HGR :I = PEEK (49234) 210 HC...
Give a code snippet in #Applesoft_BASIC A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 =...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an ov...
#Ruby
Ruby
class Numeric def pow(m) raise TypeError, "exponent must be an integer: #{m}" unless m.is_a? Integer puts "pow!!" Array.new(m, self).reduce(1, :*) end end   p 5.pow(3) p 5.5.pow(3) p 5.pow(3.1)
Give a code snippet in #Ruby Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or proc...
christopher/rosetta-code
http://rosettacode.org/wiki/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×...
#Sidef
Sidef
say ( 'First ten primorials: ', {|i| pn_primorial(i) }.map(^10).join(', ') )   { |i| say ("primorial(10^#{i}) has " + pn_primorial(10**i).len + ' digits') } << 1..6
Give a code snippet in #Sidef Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primo...
christopher/rosetta-code
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th...
#Bc
Bc
define coconuts(sailors, monkeys) { print "coconuts(", sailors, ", ", monkeys, ") = " if (sailors < 2 || monkeys < 1 || sailors <= monkeys) { return 0 } blue_cocos = sailors-1 pow_bc = blue_cocos^sailors x_cocos = pow_bc while ((x_cocos-blue_cocos)%sailors || (x_cocos-blue_cocos)/sailors < 1) { x_cocos += po...
Give a code snippet in #Bc Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he ...
christopher/rosetta-code
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas
The Twelve Days of Christmas
Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations: Metrics Array length Stri...
#Snobol
Snobol
DAYS = ARRAY('12') DAYS<1> = 'first' DAYS<2> = 'second' DAYS<3> = 'third' DAYS<4> = 'fourth' DAYS<5> = 'fifth' DAYS<6> = 'sixth' DAYS<7> = 'seventh' DAYS<8> = 'eighth' DAYS<9> = 'ninth' DAYS<10> = 'tenth' DAYS<11> = 'eleventh' DAYS<12> = 'twelfth'   GIFTS = ARRAY('12') GIFTS<1> = 'A partridge in a pear t...
Give a code snippet in #Snobol Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat...
#Kitten
Kitten
define y<S..., T...> (S..., (S..., (S... -> T...) -> T...) -> T...): -> f; { f y } f call   define fac (Int32, (Int32 -> Int32) -> Int32): -> x, rec; if (x <= 1) { 1 } else { (x - 1) rec call * x }   define fib (Int32, (Int32 -> Int32) -> Int32): -> x, rec; if (x <= 2): 1 else: (x - 1) rec call -> a...
Give a code snippet in #Kitten In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a v...
christopher/rosetta-code
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#REBOL
REBOL
rebol [ Title: "Regular Expression Matching" URL: http://rosettacode.org/wiki/Regular_expression_matching ]   string: "This is a string."   ; REBOL doesn't use a conventional Perl-compatible regular expression ; syntax. Instead, it uses a variant Parsing Expression Grammar with ; the 'parse' function. It's also not l...
Give a code snippet in #REBOL Task   match a string against a regular expression   substitute part of a string using a regular expression
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
res = {#, DivisorSigma[0, #]} & /@ Range[100000]; highest = 0; filter = {}; Do[ If[r[[2]] == highest + 1, AppendTo[filter, r[[1]]]; highest = r[[2]] ] , {r, res} ] Take[filter, 15]
Give a code snippet in #Mathematica_.2F_Wolfram_Language Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequenc...
christopher/rosetta-code
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a met...
#ALGOL_68
ALGOL 68
# sieve of Eratosthene: sets s[i] to TRUE if i is prime, FALSE otherwise # PROC sieve = ( REF[]BOOL s )VOID: BEGIN # start with everything flagged as prime # FOR i TO UPB s DO s[ i ] := TRUE OD; # sieve out the non-primes ...
Give a code snippet in #ALGOL_68 A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to in...
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]]
#AWK
AWK
  # syntax: GAWK -f SUM_OF_ELEMENTS_BELOW_MAIN_DIAGONAL_OF_MATRIX.AWK BEGIN { arr1[++n] = "1,3,7,8,10" arr1[++n] = "2,4,16,14,4" arr1[++n] = "3,1,9,18,11" arr1[++n] = "12,14,17,18,20" arr1[++n] = "7,1,3,9,5" for (i=1; i<=n; i++) { x = split(arr1[i],arr2,",") if (x != n) { pri...
Give a code snippet in #AWK 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/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting 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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
countingSort[list_] := Module[{minElem, maxElem, count, z, number}, minElem = Min[list]; maxElem = Max[list]; count = ConstantArray[0, (maxElem - minElem + 1)]; For[number = 1, number < Length[list], number++, count[[number - minElem + 1]] = count[[number - minElem + 1]] + 1;] ; z = 1; For[i = minElem, i ...
Give a code snippet in #Mathematica.2FWolfram_Language 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 |...
christopher/rosetta-code
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#PicoLisp
PicoLisp
(let V (in "input.txt" (till)) (out "output.txt" (prin V)) )
Give a code snippet in #PicoLisp File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a fil...
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 ...
#Ruby
Ruby
require 'rexml/document' include REXML   remarks = { %q(April) => %q(Bubbly: I'm > Tam and <= Emily),  %q(Tam O'Shanter) => %q(Burns: "When chapman billies leave the street ..."), %q(Emily) => %q(Short & shrift), }   doc = Document.new root = doc.add_element("CharacterRemarks")   remarks.each do |n...
Give a code snippet in #Ruby 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/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...
#Action.21
Action!
DEFINE LINES_COUNT="10" DEFINE COLUMNS_COUNT="20" DEFINE WORDS_COUNT="100" DEFINE BUFFER_SIZE="2000" DEFINE LINE_WIDTH="40" DEFINE PTR="CARD"   PTR ARRAY lines(LINES_COUNT) BYTE ARRAY wordStart(WORDS_COUNT) BYTE ARRAY wordLen(WORDS_COUNT) BYTE ARRAY firstWordInLine(LINES_COUNT) BYTE ARRAY wordsInLine(LINES_COUNT) BYTE ...
Give a code snippet in #Action.21 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/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#Factor
Factor
  :: my-named-params ( a b -- c ) a b * ;  
Give a code snippet in #Factor Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on ...
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#Excel
Excel
=NOW()
Give a code snippet in #Excel Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_comparison
String comparison
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 |...
#Perl
Perl
use v5.16; # ...for fc(), which does proper Unicode casefolding. # With older Perl versions you can use lc() as a poor-man's substitute.   sub compare { my ($a, $b) = @_; my $A = "'$a'"; my $B = "'$b'";   print "$A and $B are lexically equal.\n" if $a eq $b; print "$A and $B are not...
Give a code snippet in #Perl 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 C...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_triangle
Prime triangle
You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangem...
#ALGOL_68
ALGOL 68
BEGIN # find solutions to the "Prime Triangle" - a triangle of numbers that sum to primes # INT max number = 18; # largest number we will consider # # construct a primesieve and from that a table of pairs of numbers whose sum is prime # [ 0 : 2 * max number ]BOOL prime; prime[ 0 ] := prime[ 1 ] := FALSE...
Give a code snippet in #ALGOL_68 You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 pri...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Gambas
Gambas
  Public Sub Main()   RepeatIt("RepeatableOne", 2)   RepeatIt("RepeatableTwo", 3)   End   'Cannot pass procedure pointer in Gambas; must pass procedure name and use Object.Call() Public Sub RepeatIt(sDelegateName As String, iCount As Integer)   For iCounter As Integer = 1 To iCount Object.Call(Me, s...
Give a code snippet in #Gambas Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
christopher/rosetta-code
http://rosettacode.org/wiki/Count_the_coins
Count the coins
There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pennies   A nickel and 10 pen...
#Mercury
Mercury
:- module coins. :- interface. :- import_module int, io. :- type coin ---> quarter; dime; nickel; penny. :- type purse ---> purse(int, int, int, int).   :- pred sum_to(int::in, purse::out) is nondet.   :- pred main(io::di, io::uo) is det. :- implementation. :- import_module solutions, list, string.   :- func value(coin...
Give a code snippet in #Mercury There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Heapsort
Sorting algorithms/Heapsort
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 ...
#Groovy
Groovy
def makeSwap = { a, i, j = i+1 -> print "."; a[[j,i]] = a[[i,j]] }   def checkSwap = { list, i, j = i+1 -> [(list[i] > list[j])].find{ it }.each { makeSwap(list, i, j) } }   def siftDown = { a, start, end -> def p = start while (p*2 < end) { def c = p*2 + ((p*2 + 1 < end && a[p*2 + 2] > a[p*2 + 1]) ? ...
Give a code snippet in #Groovy 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/Long_year
Long year
Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
#Scheme
Scheme
(define (dec31wd year) (remainder (apply + (map (lambda (d) (quotient year d)) '(1 4 -100 400))) 7))   (define (long? year) (or (= 4 (dec31wd year)) (= 3 (dec31wd (- year 1)))))   (display "Long years between 1800 and 2100:") (newline) (display (filter long? (iota 300 1800)))
Give a code snippet in #Scheme Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
christopher/rosetta-code
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 ...
#Lambdatalk
Lambdatalk
  1) just define function as usual: {def add {lambda {:a :b :c} {+ :a :b :c}}} -> add   2) and use it: {add 1 2 3} -> 6 {{add 1} 2 3} -> 6 {{add 1 2} 3} -> 6 {{{add 1} 2} 3} -> 6   3) application: {def fs {lambda {:f} map :f}} {def f1 {lambda {:x} {* :x 2}}} {def f2 {lambda {:x} {pow :x 2}}} {def fs...
Give a code snippet in #Lambdatalk Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original fu...
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#Objective-C
Objective-C
NSLog(@"%@", [NSDate date]);
Give a code snippet in #Objective-C Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related tas...
christopher/rosetta-code
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed positi...
#Nim
Nim
const N = 64   template pow2(x: uint): uint = 1u shl x   proc evolve(state: uint; rule: Positive) = var state = state for _ in 1..10: var b = 0u for q in countdown(7, 0): let st = state b = b or (st and 1) shl q state = 0 for i in 0u..<N: let t = (st shr (i - 1) or st shl (N ...
Give a code snippet in #Nim Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting succ...
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_lines_from_a_file
Remove lines from a file
Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th...
#AWK
AWK
  # syntax: GAWK -f REMOVE_LINES_FROM_A_FILE.AWK # show files after lines are removed: # GAWK "FNR==1{print(FILENAME)};{print(FNR,$0)}" TEST1 TEST2 TEST3 BEGIN { build_test_data() remove_lines("TEST0",1,1) remove_lines("TEST1",3,4) remove_lines("TEST2",9,3) remove_lines("TEST3",11,1) exit(erro...
Give a code snippet in #AWK Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remov...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Smalltalk
Smalltalk
'asdf' reverse
Give a code snippet in #Smalltalk Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string E...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#zkl
zkl
fcn{self.fcn()}()
Give a code snippet in #zkl Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#AutoHotkey
AutoHotkey
isWordPossible(blocks, word){ o := {} loop, parse, blocks, `n, `r o.Insert(A_LoopField) loop, parse, word if !(r := isWordPossible_contains(o, A_LoopField, word)) return 0 return 1 } isWordPossible_contains(byref o, letter, word){ loop 2 { for k,v in o if Instr(v,letter) { StringReplace, op, v,%...
Give a code snippet in #AutoHotkey ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete al...
christopher/rosetta-code
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#CoffeeScript
CoffeeScript
  # Unlike traditional N-Queens solutions that use recursion, this # program attempts to more closely model the "human" algorithm. # # In this algorithm, the function keeps placing queens on the board # until there is no longer a safe square. If the 8th queen has been # placed, the solution is noted. If fewer than 8...
Give a code snippet in #CoffeeScript Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Kni...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_the_coins
Count the coins
There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pennies   A nickel and 10 pen...
#Go
Go
package main   import "fmt"   func main() { amount := 100 fmt.Println("amount, ways to make change:", amount, countChange(amount)) }   func countChange(amount int) int64 { return cc(amount, 4) }   func cc(amount, kindsOfCoins int) int64 { switch { case amount == 0: return 1 case amount <...
Give a code snippet in #Go There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pe...
christopher/rosetta-code
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#C.23
C#
public static (bool lexicallyEqual, bool strictlyAscending) CompareAListOfStrings(List<string> strings) => strings.Count < 2 ? (true, true) : ( strings.Distinct().Count() < 2, Enumerable.Range(1, strings.Count - 1).All(i => string.Compare(strings[i-1], strings[i]) < 0) );
Give a code snippet in #C.23 Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false v...
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#PureBasic
PureBasic
;use last bit method isOdd = i & 1 ;isOdd is non-zero if i is odd isEven = i & 1 ! 1 ;isEven is non-zero if i is even   ;use modular method isOdd = i % 2 ;isOdd is non-zero if i is odd isEven = i % 2 ! 1 ;isEven is non-zero if i is even
Give a code snippet in #PureBasic Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#Julia
Julia
function recaman() a = Vector{Int}([0]) used = Dict{Int, Bool}(0 => true) used1000 = Set(0) founddup = false termcount = 1 while length(used1000) <= 1000 nextterm = a[termcount] - termcount if nextterm < 1 || haskey(used, nextterm) nextterm += termcount + termcount ...
Give a code snippet in #Julia The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Ta...
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. ...
#XLISP
XLISP
(DO ((I 1 (+ I 1))) ((> I 5)) (DO ((J 0 (+ J 1))) ((= J I)) (DISPLAY "*")) (NEWLINE))
Give a code snippet in #XLISP “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 structu...
christopher/rosetta-code
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribut...
#Go
Go
package main   import ( "fmt" "math" )   type ifctn func(float64) float64   func simpson38(f ifctn, a, b float64, n int) float64 { h := (b - a) / float64(n) h1 := h / 3 sum := f(a) + f(b) for j := 3*n - 1; j > 0; j-- { if j%3 == 0 { sum += 2 * f(a+h1*float64(j)) } els...
Give a code snippet in #Go Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean t...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func begin writeln(STD_ERR, "Goodbye, World!"); end func;
Give a code snippet in #Seed7 Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out"...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Modula-3
Modula-3
MODULE StringInt EXPORTS Main;   IMPORT IO, Fmt, Scan;   VAR string: TEXT := "1234"; num: INTEGER := 0;   BEGIN num := Scan.Int(string); IO.Put(string & " + 1 = " & Fmt.Int(num + 1) & "\n"); END StringInt.
Give a code snippet in #Modula-3 Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Print "Goodbye, World!"; '' the trailing semi-colon suppresses the new line Sleep
Give a code snippet in #FreeBASIC Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/S...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
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 |...
#C
C
#include <stdio.h>   int main() { int a, b; scanf("%d %d", &a, &b);   if (a < b) printf("%d is less than %d\n", a, b);   if (a == b) printf("%d is equal to %d\n", a, b);   if (a > b) printf("%d is greater than %d\n", a, b);   return 0; }
Give a code snippet in #C 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 Conc...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#CLU
CLU
factorial = proc (n: int) returns (int) signals (negative) if n<0 then signal negative elseif n=0 then return(1) else return(n * factorial(n-1)) end end factorial   start_up = proc () po: stream := stream$primary_output()   for i: int in int$from_to(0, 10) do fac: int := factorial(i) ...
Give a code snippet in #CLU Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a num...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Prolog
Prolog
mortal(X) :- man(X). man(socrates).
Give a code snippet in #Prolog Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#ACL2
ACL2
(defun recursion-limit (x) (if (zp x) 0 (prog2$ (cw "~x0~%" x) (1+ (recursion-limit (1+ x))))))
Give a code snippet in #ACL2 Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   Th...
#Swift
Swift
struct FuscSeq: Sequence, IteratorProtocol { private var arr = [0, 1] private var i = 0   mutating func next() -> Int? { defer { i += 1 }   guard i > 1 else { return arr[i] }   switch i & 1 { case 0: arr.append(arr[i / 2]) case 1: arr.append(arr[(i - 1) / 2] + a...
Give a code snippet in #Swift Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition st...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#MIPS_Assembly
MIPS Assembly
  # First, it gets the length of the original string # Then, it allocates memory from the copy # Then it copies the pointer to the original string, and adds the strlen # subtract 1, then that new pointer is at the last char. # while(strlen) # copy char # decrement strlen # decrement source pointer # ...
Give a code snippet in #MIPS_Assembly Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a strin...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming langu...
#XPL0
XPL0
include c:\cxpl\codes; int N; [N:= 2; repeat HexOut(0, N); Text(0, " "); IntOut(0, N); CrLf(0); N:= N*N; until N=0; ]
Give a code snippet in #XPL0 Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard rout...
christopher/rosetta-code