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/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...
#SenseTalk
SenseTalk
function CanMakeWord word   put [ ("B", "O"), ("X", "K"), ("D", "Q"), ("C", "P"), ("N", "A"), ("G", "T"), ("R", "E"), ("T", "G"), ("Q", "D"), ("F", "S"), ("J", "W"), ("H", "U"), ("V", "I"), ("A", "N"), ("O", "B"), ("E", "R"), ("F", "S"), ("L", "Y"), ("P", "C"), ("Z", "M") ] int...
Give a code snippet in #SenseTalk 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 alp...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Panda
Panda
file:readme.txt .text
Give a code snippet in #Panda Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incre...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#Befunge
Befunge
p0"2":*8*>::2/\:2/\28*:*:**+>::28*:*:*/\28*:*:*%%#v_\:28*:*:*%v>00p:0`\0\`-1v ++\1-:1`#^_$:28*:*:*/\28*vv_^#<<<!%*:*:*82:-1\-1\<<<\+**:*:*82<+>*:*:**\2-!#+ v"There are "0\g00+1%*:*:<>28*:*:*/\28*:*:*/:0\`28*:*:**+-:!00g^^82!:g01\p01< >:#,_\." ,tneicifed">:#,_\." dna ,tcefrep">:#,_\.55+".srebmun tnadnuba">:#,_@
Give a code snippet in #Befunge These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficie...
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 |...
#Elixir
Elixir
iex(60)> s = "Hello" "Hello" iex(61)> s <> " World!" "Hello World!"
Give a code snippet in #Elixir 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related ...
#Tcl
Tcl
# matrix operation support: package require math::linearalgebra namespace import ::math::linearalgebra::matmul namespace import ::math::linearalgebra::crossproduct namespace import ::math::linearalgebra::dotproduct namespace import ::math::linearalgebra::sub   # returns a cube as a list of faces, # where each face is a...
Give a code snippet in #Tcl Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspect...
christopher/rosetta-code
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#Powershell
Powershell
  #15 Puzzle Game $Script:Neighbours = @{ "1" = @("2","5") "2" = @("1","3","6") "3" = @("2","4","7") "4" = @("3","8") "5" = @("1","6","9") "6" = @("2","5","7","10") "7" = @("3","6","8","11") "8" = @("4","7","12") "9" = @("5","10","13") "10" = @("6","9","11","14") "11" = @("7"...
Give a code snippet in #Powershell Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
christopher/rosetta-code
http://rosettacode.org/wiki/Horizontal_sundial_calculations
Horizontal sundial calculations
Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit...
#Ada
Ada
with Ada.Text_IO; with Ada.Numerics.Elementary_Functions; procedure Sundial is use Ada.Numerics.Elementary_Functions; use Ada.Numerics; package Float_IO is new Ada.Text_IO.Float_IO (Float);   Latitude, Longitude, Meridian : Float; Latitude_Sine  : Float; begin Ada.Text_IO.Put ("Enter la...
Give a code snippet in #Ada Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#C.23
C#
using System; using System.Security.Cryptography;   private static int GetRandomInt() { int result = 0; var rng = new RNGCryptoServiceProvider(); var buffer = new byte[4];   rng.GetBytes(buffer); result = BitConverter.ToInt32(buffer, 0);   return result; }
Give a code snippet in #C.23 Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
christopher/rosetta-code
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, sho...
#AutoHotkey
AutoHotkey
MsgBox, % "72`n" WrapText(Clipboard, 72) "`n`n80`n" WrapText(Clipboard, 80) return   WrapText(Text, LineLength) { StringReplace, Text, Text, `r`n, %A_Space%, All while (p := RegExMatch(Text, "(.{1," LineLength "})(\s|\R+|$)", Match, p ? p + StrLen(Match) : 1)) Result .= Match1 ((Match2 = A_Space || Matc...
Give a code snippet in #AutoHotkey Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#REXX
REXX
/*REXX program loops through a two-dimensional array to search for a '20' (twenty). */ parse arg rows cols targ . /*obtain optional arguments from the CL*/ if rows=='' | rows=="," then rows=60 /*Rows not specified? Then use default*/ if cols=='' | cols=="," then cols=10 ...
Give a code snippet in #REXX Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met...
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.
#Icon_and_Unicon
Icon and Unicon
  t := table() # The table's memory is allocated #... do things with t t := &null # The table's memory can be reclaimed  
Give a code snippet in #Icon_and_Unicon 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/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#.D0.9C.D0.9A-61.2F52
МК-61/52
0 П4 КИП4 ИП4 6 / {x} x=0 02 С/П
Give a code snippet in #.D0.9C.D0.9A-61.2F52 Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-w...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Preserve_screen
Terminal control/Preserve screen
Task Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out. There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be preserved.   If the implement...
#Rust
Rust
use std::io::{stdout, Write}; use std::time::Duration;   fn main() { let mut output = stdout();   print!("\x1b[?1049h\x1b[H"); println!("Alternate screen buffer");   for i in (1..=5).rev() { print!("\rgoing back in {}...", i); output.flush().unwrap(); std::thread::sleep(Duration:...
Give a code snippet in #Rust Task Clear the screen, output something on the display, and then restore the screen to the preserved state that it was in before the task was carried out. There is no requirement to change the font or kerning in this task, however character decorations and attributes are expected to be...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#R
R
> env <- new.env() > env[["x"]] <- 123 > env[["x"]]
Give a code snippet in #R Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compoun...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead 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 ...
#Phix
Phix
with javascript_semantics function beadsort(sequence a) sequence poles = repeat(0,max(a)) for i=1 to length(a) do poles[1..a[i]] = sq_add(poles[1..a[i]],1) end for a[1..$] = 0 for i=1 to length(poles) do a[1..poles[i]] = sq_add(a[1..poles[i]],1) end for return a end function...
Give a code snippet in #Phix 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/Bitmap/B%C3%A9zier_curves/Quadratic
Bitmap/Bézier curves/Quadratic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
pts = {{0, 0}, {1, -1}, {2, 1}}; Graphics[{BSplineCurve[pts], Green, Line[pts], Red, Point[pts]}]
Give a code snippet in #Mathematica_.2F_Wolfram_Language Using the data storage type defined on this page for raster images, and the draw_line function defined in this one, draw a quadratic bezier curve (definition on Wikipedia).
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 ...
#ACL2
ACL2
(defun partition (p xs) (if (endp xs) (mv nil nil) (mv-let (less more) (partition p (rest xs)) (if (< (first xs) p) (mv (cons (first xs) less) more) (mv less (cons (first xs) more))))))   (defun qsort (xs) (if (endp xs) nil (mv-let (...
Give a code snippet in #ACL2 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/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#Ruby
Ruby
def fib(n) raise RangeError, "fib of negative" if n < 0 (fib2 = proc { |m| m < 2 ? m : fib2[m - 1] + fib2[m - 2] })[n] end
Give a code snippet in #Ruby While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwante...
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.
#Python
Python
#!/usr/bin/python def repeat(f,n): for i in range(n): f();   def procedure(): print("Example");   repeat(procedure,3); #prints "Example" (without quotes) three times, separated by newlines.
Give a code snippet in #Python 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/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 ...
#GAP
GAP
FactorsInt(2^67-1); # [ 193707721, 761838257287 ]
Give a code snippet in #GAP 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/Terminal_control/Display_an_extended_character
Terminal control/Display an extended character
Task Display an extended (non ASCII) character onto the terminal. Specifically, display a   £   (GBP currency sign).
#Kotlin
Kotlin
// version 1.1.2   fun main(args:Array<String>) = println("£")
Give a code snippet in #Kotlin Task Display an extended (non ASCII) character onto the terminal. Specifically, display a   £   (GBP currency sign).
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...
#Wren
Wren
var gcd = Fn.new { |x, y| while (y != 0) { var t = y y = x % y x = t } return x.abs }   System.print("gcd(33, 77) = %(gcd.call(33, 77))") System.print("gcd(49865, 69811) = %(gcd.call(49865, 69811))")
Give a code snippet in #Wren 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Checkpoint_synchronization
Checkpoint synchronization
The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before st...
#Haskell
Haskell
import Control.Parallel   data Task a = Idle | Make a type TaskList a = [a] type Results a = [a] type TaskGroups a = [TaskList a] type WorkerList a = [Worker a] type Worker a = [Task a]   -- run tasks in parallel and collect their results -- the function doesn't return until all tasks are done, therefore -- finished th...
Give a code snippet in #Haskell The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part fir...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Tcl
Tcl
rand
Give a code snippet in #Tcl The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm ...
christopher/rosetta-code
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file...
#Liberty_BASIC
Liberty BASIC
'The following code relies on the Windows API Input "Input the text to translate to Morse Code... "; string$ Print PlayMorse$(string$) End   Function PlayMorse$(string$) 'LetterGap = (3 * BaseTime) 'WordGap = (7 * BaseTime) BaseTime = 50 freq = 1250 PlayMorse$ = TranslateToMorse$(string$) morseC...
Give a code snippet in #Liberty_BASIC Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may eithe...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#Harbour
Harbour
arr := { => } arr[ 10 ] := "Val_10" arr[ "foo" ] := "foovalue"
Give a code snippet in #Harbour Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition...
christopher/rosetta-code
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#V
V
[swap [a b : b a] view].   1 2 swap = 2 1 'hello' 'hi' swap
Give a code snippet in #V Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 ...
#Red
Red
  Red []   ;;------------------------------- ;; we have to use function not func here, otherwise we'd have to define all "vars" as local... qsort: function [list][ ;;------------------------------- if 1 >= length? list [ return list ] left: copy [] right: copy [] eq: copy []  ;; "equal" pivot: list/2 ;; s...
Give a code snippet in #Red 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Latin_Squares_in_reduced_form
Latin Squares in reduced form
A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin S...
#C.2B.2B
C++
#include <algorithm> #include <functional> #include <iostream> #include <numeric> #include <vector>   typedef std::vector<std::vector<int>> matrix;   matrix dList(int n, int start) { start--; // use 0 basing   std::vector<int> a(n); std::iota(a.begin(), a.end(), 0); a[start] = a[0]; a[0] = start; ...
Give a code snippet in #C.2B.2B A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element ...
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 ...
#ECL
ECL
//Calculates Fibonacci sequence up to n steps using Binet's closed form solution     FibFunction(UNSIGNED2 n) := FUNCTION REAL Sqrt5 := Sqrt(5); REAL Phi := (1+Sqrt(5))/2; REAL Phi_Inv := 1/Phi; UNSIGNED FibValue := ROUND( ( POWER(Phi,n)-POWER(Phi_Inv,n) ) /Sqrt5); RETURN FibValue; END;   FibSeries(UNSIGNE...
Give a code snippet in #ECL 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/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1} ...
#Ada
Ada
with Ada.Containers.Vectors;   generic type Index_Type is range <>; type Element_Type is private; Zero : Element_Type; with function "+" (Left, Right : Element_Type) return Element_Type is <>; with function "-" (Left, Right : Element_Type) return Element_Type is <>; with function "=" (Left, Right : El...
Give a code snippet in #Ada An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 =...
christopher/rosetta-code
http://rosettacode.org/wiki/Input_loop
Input loop
Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
#Groovy
Groovy
def lineMap = [:] System.in.eachLine { line, i -> lineMap[i] = line } lineMap.each { println it }
Give a code snippet in #Groovy Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
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...
#Smalltalk
Smalltalk
'THE QUICK BROWN FOX' rot:3 -> 'WKH TXLFN EURZQ IRA'
Give a code snippet in #Smalltalk 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#PL.2FI
PL/I
  /* PL/I has immediate facilities for all those operations except for */ /* replace. */ s = t; /* assignment */ s = t || u; /* catenation - append one or more bytes. */ if length(s) = 0 then ... /* test for an empty string. */ if s = t then ... /* compare strin...
Give a code snippet in #PL.2FI Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings acco...
christopher/rosetta-code
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the ...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   namespace Soundex { internal static class Program { private static void Main() { var testWords = new TestWords { {"Soundex", "S532"}, ...
Give a code snippet in #C.23 Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is...
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...
#Liberty_BASIC
Liberty BASIC
For i = 0 To 10 Print "f(";i;") maps to ";mapToRange(i, 0, 10, -1, 0) Next i End   Function mapToRange(value, inputMin, inputMax, outputMin, outputMax) mapToRange = (((value - inputMin) * (outputMax - outputMin)) / (inputMax - inputMin)) + outputMin End Function  
Give a code snippet in #Liberty_BASIC 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 li...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#C
C
foo *foos = malloc(n * sizeof(*foos)); for (int i = 0; i < n; i++) init_foo(&foos[i]);
Give a code snippet in #C Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered u...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. 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: Def...
#zkl
zkl
class Node{ fcn init(_value,_prev=Void,_next=Void) { var value=_value, prev=_prev, next=_next; } fcn toString{ value.toString() } fcn append(value){ b,c := Node(value,self,next),next; next=b; if(c) c.prev=b; b } }
Give a code snippet in #zkl Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Rem...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion
Singly-linked list/Element insertion
Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Trav...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program insertList.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ READ, 3 .equ WRITE, 4   .equ NBELEMENTS, 100 @ list size     /**********************...
Give a code snippet in #ARM_Assembly Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element de...
christopher/rosetta-code
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#PARI.2FGP
PARI/GP
Strchr(Vecsmall(apply(k->if(k>96&&k<123,(k-84)%26+97,if(k>64&&k<91,(k-52)%26+65,k)),Vec(Vecsmall(s)))))
Give a code snippet in #PARI.2FGP This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Da...
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...
#Vedit_macro_language
Vedit macro language
RS(10, "$") // Field separator #11 = 1 // Align: 1 = left, 2 = center, 3 = right   // Reset column widths. Max 50 columns for (#1=40; #1<90; #1++) { #@1 = 0 }   // Find max width of each column BOF Repeat(ALL) { for (#1=40; #1<90; #1++) { Match(@10, ADVANCE) // skip field separator if any #2 = Cur_Pos...
Give a code snippet in #Vedit_macro_language 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 t...
christopher/rosetta-code
http://rosettacode.org/wiki/Reflection/List_methods
Reflection/List methods
Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
#Nanoquery
Nanoquery
// create a class with methods that will be listed class Methods def static method1() return "this is a static method. it will not be printed" end def method2() return "this is not a static method" end   def operator=(other) // operator methods are listed by both their defined name and // by their internal...
Give a code snippet in #Nanoquery Task The goal is to get the methods of an object, as names, values or both. Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
christopher/rosetta-code
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#C.23
C#
using System; using System.IO; using System.Linq; using System.Text;   class Program { static char Rot13(char c) { if ('a' <= c && c <= 'm' || 'A' <= c && c <= 'M') { return (char)(c + 13); } if ('n' <= c && c <= 'z' || 'N' <= c && c <= 'Z') { retu...
Give a code snippet in #C.23 Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 ...
christopher/rosetta-code
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha...
#Ring
Ring
  mobStr = " . "   for i = 1 to 200 if mobius(i) >= 0 mobStr + = " " ok temp = string(mobius(i)) if left(temp,2) = "-0" temp = right(temp,len(temp)-1) ok mobStr += temp + " " if i % 10 = 9 see mobStr + nl mobStr = " " ok next   func mobius(n) ...
Give a code snippet in #Ring The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum o...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
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 ...
#Delphi
Delphi
program SortWithCustomComparator;   {$APPTYPE CONSOLE}   uses SysUtils, Types, Generics.Collections, Generics.Defaults;   var lArray: TStringDynArray; begin lArray := TStringDynArray.Create('Here', 'are', 'some', 'sample', 'strings', 'to', 'be', 'sorted');   TArray.Sort<string>(lArray , TDelegatedComparer<string>...
Give a code snippet in #Delphi 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/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Avail
Avail
BEGIN { # Do not put quotes round the numeric values, or the tests will fail a = 1 # True b = 0 # False   # Boolean evaluations if (a) { print "first test a is true" } # This should print if (b) { print "second test b is true" } # This should not print if (!a) { print "third test...
Give a code snippet in #Avail Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file
Create a file
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT - create file ERROR/STOP CREATE ("output.txt",FDF-o,-std-) - create directory ERROR/STOP CREATE ("docs",project,-std-)  
Give a code snippet in #TUSCRIPT In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty 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/Sort_an_integer_array
Sort an integer array
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 ...
#PowerBASIC
PowerBASIC
ARRAY SORT x()
Give a code snippet in #PowerBASIC 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/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#PHP
PHP
<?php $words = explode("\n", file_get_contents('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt')); foreach ($words as $word) { $chars = str_split($word); sort($chars); $anagram[implode($chars)][] = $word; }   $best = max(array_map('count', $anagram)); foreach ($anagram as $ana) if (count($ana) == $...
Give a code snippet in #PHP When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in the...
christopher/rosetta-code
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#Liberty_BASIC
Liberty BASIC
nomainwin   UpperLeftX = 50 UpperLeftY = 50 WindowWidth =900 WindowHeight =930   statictext #w.st, "", 10, 850, 870, 40   open "Spiral matrix" for graphics_nsb_nf as #w   #w "trapclose [quit]" #w "backcolor darkblue; color cyan; fill darkblue"   for N =2 to 50   #w.st "!font courier_new "; int( 60 /N); " bold...
Give a code snippet in #Liberty_BASIC Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle
Solve a Hidato puzzle
The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always connected. The number “1” is always ...
#Tailspin
Tailspin
  def input: '__ 33 35 __ __ . . . __ __ 24 22 __ . . . __ __ __ 21 __ __ . . __ 26 __ 13 40 11 . . 27 __ __ __ 9 __ 1 . . . __ __ 18 __ __ . . . . . __ 7 __ __ . . . . . . 5 __';   templates hidato composer setup data givenInput <[<={}|{row: <row>, col: <col>}>*]> local @: ...
Give a code snippet in #Tailspin The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always con...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#PowerShell
PowerShell
$a = 1,2,3 $b = 4,5,6   $c = $a + $b Write-Host $c
Give a code snippet in #PowerShell Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
0^0
Give a code snippet in #Mathematica.2FWolfram_Language Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language obje...
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 ...
#Octave
Octave
r = factor(120202039393)
Give a code snippet in #Octave 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I befo...
#Nim
Nim
let fruit = ["apple", "orange"] echo "The length of the fruit array is ", len(fruit)
Give a code snippet in #Nim Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequen...
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. 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 Generate and show a maze, using the simple Depth...
#F.23
F#
let rnd : int -> int = let gen = new System.Random() fun max -> gen.Next(max)   // randomly choose an element of a list let choose (xs:_ list) = xs.[rnd xs.Length]   type Maze(width, height) = // (x,y) -> have we been here before? let visited = Array2D.create width height false // (x,y) -> is there a wall bet...
Give a code snippet in #F.23 This page uses content from Wikipedia. The original article was at Maze generation algorithm. 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 Generate and show ...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at uni...
#PARI.2FGP
PARI/GP
dict=readstr("unixdict.txt"); len=apply(s->#s, dict); getLen(L)=my(v=List()); for(i=1,#dict, if(len[i]==L, listput(v, dict[i]))); Vec(v); letters(s)=vecsort(Vec(s)); getAnagrams(v)=my(u=List(),L=apply(letters,v),t,w); for(i=1,#v-1, w=List(); t=L[i]; for(j=i+1,#v, if(L[j]==t, listput(w, v[j]))); if(#w, listput(u, concat...
Give a code snippet in #PARI.2FGP Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: ...
#Sidef
Sidef
func runge_kutta(yp) { func (t, y, δt) { var a = (δt * yp(t, y)); var b = (δt * yp(t + δt/2, y + a/2)); var c = (δt * yp(t + δt/2, y + b/2)); var d = (δt * yp(t + δt, y + c)); (a + 2*(b + c) + d) / 6; } }   define δt = 0.1; var δy = runge_kutta(func(t, y) { t * y.sqrt });...
Give a code snippet in #Sidef Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This eq...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/lexical_analyzer
Compiler/lexical analyzer
Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is als...
#C
C
#include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <ctype.h> #include <string.h> #include <errno.h> #include <stdbool.h> #include <limits.h>   #define NELEMS(arr) (sizeof(arr) / sizeof(arr[0]))   #define da_dim(name, type) type *name = NULL; \ int _qy_ ## name ## _...
Give a code snippet in #C Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scann...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#Groovy
Groovy
class DigitalRoot { static int[] calcDigitalRoot(String number, int base) { BigInteger bi = new BigInteger(number, base) int additivePersistence = 0 if (bi.signum() < 0) { bi = bi.negate() } BigInteger biBase = BigInteger.valueOf(base) while (bi >= biBase)...
Give a code snippet in #Groovy The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} ,...
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#Run_BASIC
Run BASIC
v1$ = "1, 3, -5" v2$ = "4, -2, -1"   print "DotProduct of ";v1$;" and "; v2$;" is ";dotProduct(v1$,v2$) end   function dotProduct(a$, b$) while word$(a$,i + 1,",") <> "" i = i + 1 v1$=word$(a$,i,",") v2$=word$(b$,i,",") dotProduct = dotProduct + val(v1$) * val(v2$) wend end function
Give a code snippet in #Run_BASIC Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2...
christopher/rosetta-code
http://rosettacode.org/wiki/Pseudo-random_numbers/Middle-square_method
Pseudo-random numbers/Middle-square method
Middle-square_method Generator The Method To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number i...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Main is type long is range 0 .. 2**64; Seed : long := 675_248; function random return long is begin Seed := Seed * Seed / 1_000 rem 1_000_000; return Seed; end random; begin for I in 1 .. 5 loop Put (long'Image (random)); end loop; ...
Give a code snippet in #Ada Middle-square_method Generator The Method To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the resu...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the...
#Nim
Nim
proc strcmp(a, b: cstring): cint {.importc: "strcmp", nodecl.} echo strcmp("abc", "def") echo strcmp("hello", "hello")   proc printf(formatstr: cstring) {.header: "<stdio.h>", varargs.}   var x = "foo" printf("Hello %d %s!\n", 12, x)
Give a code snippet in #Nim Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be...
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...
#ooRexx
ooRexx
  sequence = hailstone(27) say "Hailstone sequence for 27 has" sequence~items "elements and is ["sequence~toString('l', ", ")"]"   highestNumber = 1 highestCount = 1   loop i = 2 to 100000 sequence = hailstone(i) count = sequence~items if count > highestCount then do highestNumber = i highes...
Give a code snippet in #ooRexx 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. 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 loop b...
#SPL
SPL
> n, 1..10,2 #.output(n) <
Give a code snippet in #SPL Task Demonstrate a   for-loop   where the step-value is greater than one. 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/Incre...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion 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 ...
#Common_Lisp
Common Lisp
(defun span (predicate list) (let ((tail (member-if-not predicate list))) (values (ldiff list tail) tail)))   (defun less-than (x) (lambda (y) (< y x)))   (defun insert (list elt) (multiple-value-bind (left right) (span (less-than elt) list) (append left (list elt) right)))   (defun insertion-sort (list) ...
Give a code snippet in #Common_Lisp 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 | Qu...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related ...
#Scala
Scala
import java.awt.event.ActionEvent import java.awt._   import javax.swing.{JFrame, JPanel, Timer}   import scala.math.{Pi, atan, cos, sin, sqrt}   object RotatingCube extends App {   class RotatingCube extends JPanel { private val vertices: Vector[Array[Double]] = Vector(Array(-1, -1, -1), Array(-1, -1, 1), ...
Give a code snippet in #Scala Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspe...
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 ...
#ColdFusion
ColdFusion
<cfif fileExists(expandPath("input.txt"))> <cffile action="read" file="#expandPath('input.txt')#" variable="inputContents"> <cffile action="write" file="#expandPath('output.txt')#" output="#inputContents#"> </cfif>
Give a code snippet in #ColdFusion 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 f...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
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 ...
#Phix
Phix
sequence s = {{"grass","green"},{"snow","white"},{"sky","blue"},{"cherry","red"},{0,1.2},{3.4,-1}} ?sort(s) function compare_col2(sequence a, b) return compare(a[2],b[2]) end function ?custom_sort(compare_col2,s) ?sort_columns(s,{2}) -- 0.8.0+, same result as above w/o needing an explicit comparison routine
Give a code snippet in #Phix 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/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#XQuery
XQuery
  let $json := ' { "Astring" : "string-value", "Anumber" : 5.7, "Anull"  : null, "Aarray"  : ["One","Two", 3], "Aobject" : { "key1": "value1", "key2": "value2" }, "Atrue"  : true, "Afalse"  : false } ' let $xml := json-to-xml($local:json) return ( "XPath fn:js...
Give a code snippet in #XQuery Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
christopher/rosetta-code
http://rosettacode.org/wiki/Shell_one-liner
Shell one-liner
Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different comman...
#NetLogo
NetLogo
let x 15 ask turtles [ set xcor x set x x + 1 ]
Give a code snippet in #NetLogo Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementa...
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.
#Fortran
Fortran
program test_maxval   integer,dimension(5),parameter :: x = [10,100,7,1,2] real,dimension(5),parameter :: y = [5.0,60.0,1.0,678.0,0.0]   write(*,'(I5)') maxval(x) write(*,'(F5.1)') maxval(y)   end program test_maxval
Give a code snippet in #Fortran 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/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language...
#Groovy
Groovy
def dog = "Benjamin", Dog = "Samba", DOG = "Bernie" println (dog == DOG ? "There is one dog named ${dog}" : "There are three dogs named ${dog}, ${Dog} and ${DOG}.")
Give a code snippet in #Groovy Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, S...
christopher/rosetta-code
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#ALGOL-M
ALGOL-M
  BEGIN   COMMENT FIND PRIMES UP TO THE SPECIFIED LIMIT (HERE 1,000) USING CLASSIC SIEVE OF ERATOSTHENES;   % CALCULATE INTEGER SQUARE ROOT % INTEGER FUNCTION ISQRT(N); INTEGER N; BEGIN INTEGER R1, R2; R1 := N; R2 := 1; WHILE R1 > R2 DO BEGIN R1 := (R1+R2) / 2; R2 :=...
Give a code snippet in #ALGOL-M This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Wee_Basic
Wee Basic
print 1 at 10,12 "Hello world!" end
Give a code snippet in #Wee_Basic Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#Gambas
Gambas
Public Sub Form_Open() Dim sData As String = File.Load("data.txt") Dim iCount, iSpaces, iLetters, iOther As Integer Dim bPunctuation As Boolean   For iCount = 1 To Len(sData) If InStr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", UCase(Mid(sData, iCount, 1))) Then Inc iLetters bPunctuation = True End If If Mid(sData, i...
Give a code snippet in #Gambas Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (as...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. 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 loop b...
#Raven
Raven
[ 2 4 6 8 ] each "%d, " print "who do we appreciate?\n" print
Give a code snippet in #Raven Task Demonstrate a   for-loop   where the step-value is greater than one. 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/Inc...
christopher/rosetta-code
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
#ChucK
ChucK
Machine.add(me.dir() + "/MyOwnClassesDefinitions.ck");
Give a code snippet in #ChucK 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/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point...
#Icon_and_Unicon
Icon and Unicon
link graphics   procedure main(A) # points, inside r, outside r in pixels - default to task values   if \A[1] == "help" then stop("Usage: plot #points inside-radius outside-radius") points := \A[1] | 100 outside := \A[2] | 15 inside := \A[3] | 10 if inside > outside then inside :=: outside   wsize := integer(2.2*o...
Give a code snippet in #Icon_and_Unicon Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "...
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
#zkl
zkl
var re=RegExp(".*string$"); re.matches("I am a string") //-->True var s="I am a string thing" re=RegExp("(string)") // () means group, ie if you see it, save it re.search(s,True) //-->True, .search(x,True) means search for a match, ie don't need .* p,n:=re.matched[0] //.matched-->L(L(7,6),"string") String(s[0,p],"FOO"...
Give a code snippet in #zkl Task   match a string against a regular expression   substitute part of a string using a regular expression
christopher/rosetta-code
http://rosettacode.org/wiki/Resistor_mesh
Resistor mesh
Task Given   10×10   grid nodes   (as shown in the image)   interconnected by   1Ω   resistors as shown, find the resistance between points   A   and   B. See also   (humor, nerd sniping)   xkcd.com cartoon
#11l
11l
-V DIFF_THRESHOLD = 1e-40   T.enum Fixed FREE A B   T Node Float voltage Fixed fixed F (v = 0.0, f = Fixed.FREE) .voltage = v .fixed = f   F set_boundary(&m) m[1][1] = Node( 1.0, Fixed.A) m[6][7] = Node(-1.0, Fixed.B)   F calc_difference(m, &d) V h = m.len V w = m[0].len V t...
Give a code snippet in #11l Task Given   10×10   grid nodes   (as shown in the image)   interconnected by   1Ω   resistors as shown, find the resistance between points   A   and   B. See also   (humor, nerd sniping)   xkcd.com cartoon
christopher/rosetta-code
http://rosettacode.org/wiki/Distributed_programming
Distributed programming
Write two programs (or one program with two modes) which run on networked computers, and send some messages between them. The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example ...
#Python
Python
#!/usr/bin/env python # -*- coding: utf-8 -*-   import SimpleXMLRPCServer   class MyHandlerInstance: def echo(self, data): '''Method for returning data got from client''' return 'Server responded: %s' % data   def div(self, num1, num2): '''Method for divide 2 numbers''' return nu...
Give a code snippet in #Python Write two programs (or one program with two modes) which run on networked computers, and send some messages between them. The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed ...
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...
#R
R
choose(5,3)
Give a code snippet in #R 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 ) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Wart
Wart
def (s * n) :case (string? s) with outstring repeat n pr s   ("ha" * 5) => "hahahahaha"
Give a code snippet in #Wart Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) =...
christopher/rosetta-code
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string....
#Clojure
Clojure
(def c 100) ;number of children in each generation (def p 0.05) ;mutation probability   (def target "METHINKS IT IS LIKE A WEASEL") (def tsize (count target))   (def alphabet " ABCDEFGHIJLKLMNOPQRSTUVWXYZ")
Give a code snippet in #Clojure Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of i...
christopher/rosetta-code
http://rosettacode.org/wiki/Pig_the_dice_game/Player
Pig the dice game/Player
Pig the dice game/Player You are encouraged to solve this task according to the task description, using any language you may know. Task Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy. State here the play strategies involved. Show play dur...
#Go
Go
package pig   import ( "fmt" "math/rand" "time" )   type ( PlayerID int MessageID int StrategyID int   PigGameData struct { player PlayerID turnCount int turnRollCount int turnScore int lastRoll int scores [2]int verbose bool } )   const ( // Status messages g...
Give a code snippet in #Go Pig the dice game/Player You are encouraged to solve this task according to the task description, using any language you may know. Task Create a dice simulator and scorer of Pig the dice game and add to it the ability to play the game to at least one strategy. State here the play strateg...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Nim
Nim
import sequtils   let values = toSeq(0..9)   # Filtering by returning a new sequence. # - using an explicit filtering procedure. echo "Even values: ", values.filter(proc(x: int): bool = x mod 2 == 0) # - using a predicate. echo "Odd values: ", values.filterIt(it mod 2 == 1)   # Filtering by modifying the sequence. # - ...
Give a code snippet in #Nim Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
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...
#Stata
Stata
di c(current_date) di c(current_time)
Give a code snippet in #Stata 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/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...
#C.23
C#
  using System; using System.IO;   namespace Pig {   class Roll { public int TotalScore{get;set;} public int RollScore{get;set;} public bool Continue{get;set;} }   class Player { public String Name{get;set;} public int Score {get;set;} Random rand;   public Player() { Score = 0; rand = new Random...
Give a code snippet in #C.23 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 th...
christopher/rosetta-code
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioin...
#PureBasic
PureBasic
If OpenConsole("Show_Ascii_table: rosettacode.org") Define r.i, c.i For r=0 To 15 For c=32+r To 112+r Step 16 Print(RSet(Str(c),3)+" : ") Select c Case 32 Print("Spc") Case 127 Print("Del") Default Print(LSet(Chr(c),3)) EndSelect Prin...
Give a code snippet in #PureBasic Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stone...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ...
#Vlang
Vlang
import math   fn mean_angle(deg []f64) f64 { mut ss, mut sc := f64(0), f64(0) for x in deg { s, c := math.sincos(x * math.pi / 180) ss += s sc += c } return math.atan2(ss, sc) * 180 / math.pi }   fn main() { for angles in [ [f64(350), 10], [f64(90), 180, 270, 360], [f64(10), 20, 30], ] { println("Th...
Give a code snippet in #Vlang When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first read...
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,...
#LabVIEW
LabVIEW
  // Create a new array with length 0 {def myArray1 {A.new}} -> []   // Create an array with 2 members (length is 2) {def myArray2 {A.new Item1 Item2}} -> [Item1,Item2]   // Edit a value in an array {def myArray3 {A.new 1 2 3}} {A.set! 1 hello {myArray3}} -> [1,hello,3]   // Add a value at the head of an array {def my...
Give a code snippet in #LabVIEW 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 ret...
christopher/rosetta-code
http://rosettacode.org/wiki/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#FunL
FunL
def lcm( _, 0 ) = 0 lcm( 0, _ ) = 0 lcm( x, y ) = abs( (x\gcd(x, y)) y )
Give a code snippet in #FunL Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has ...
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×...
#Scala
Scala
import spire.math.SafeLong import spire.implicits._   import scala.collection.parallel.immutable.ParVector   object Primorial { def main(args: Array[String]): Unit = { println( s"""|First 10 Primorials: |${LazyList.range(0, 10).map(n => f"$n: ${primorial(n).toBigInt}%,d").mkString("\n")} ...
Give a code snippet in #Scala 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/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.
#NetRexx
NetRexx
/* NetRexx */   options replace format comments java crossref savelog symbols binary   import java.text.MessageFormat   sevenPointOneTwoFive = double 7.125   -- using NetRexx Built-In Functions (BIFs) say Rexx(sevenPointOneTwoFive).format(5, 3).changestr(' ', '0')   -- using Java library constructs System.out.printf('%...
Give a code snippet in #NetRexx 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/Play_recorded_sounds
Play recorded sounds
Load at least two prerecorded sounds, and demonstrate as many of these features as you can: playing them individually and simultaneously stopping before the end of the sound looping (preferably glitch-free) setting the volume of each sound stereo or 3D positional mixing performing other actions when marked times...
#R
R
  #Setup # Warning: The example files are Windows specific. library(sound) media_dir <- file.path(Sys.getenv("SYSTEMROOT"), "Media") chimes <- loadSample(file.path(media_dir, "chimes.wav")) chord <- loadSample(file.path(media_dir, "chord.wav"))   # Play sequentially play(appendSample(chimes, chord))   # Play simultaneo...
Give a code snippet in #R Load at least two prerecorded sounds, and demonstrate as many of these features as you can: playing them individually and simultaneously stopping before the end of the sound looping (preferably glitch-free) setting the volume of each sound stereo or 3D positional mixing performing othe...
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.
#REXX
REXX
/*REXX program emulates immutable variables (as a post-computational check). */ call immutable '$=1' /* ◄─── assigns an immutable variable. */ call immutable ' pi = 3.14159' /* ◄─── " " " " */ call immutable 'radius= 2*pi/4 ' ...
Give a code snippet in #REXX 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/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#C
C
bool? value = null
Give a code snippet in #C Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Iterated_digits_squaring
Iterated digits squaring
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lambda x: x if x in [1, 89] else i...
#Common_Lisp
Common Lisp
  (defun square (number) (expt number 2))   (defun list-digits (number) "Return the `number' as a list of its digits." (loop :for (rest digit) := (multiple-value-list (truncate number 10)) :then (multiple-value-list (truncate rest 10)) :collect digit :until (zerop rest)))   (defu...
Give a code snippet in #Common_Lisp If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate...
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 ...
#Swift
Swift
func polynomialCoeffs(n: Int) -> [Int] { var result = [Int](count : n+1, repeatedValue : 0)   result[0]=1 for i in 1 ..< n/2+1 { //Progress up, until reaching the middle value result[i] = result[i-1] * (n-i+1)/i; } for i in n/2+1 ..< n+1 { //Copy the inverse of the first part result[...
Give a code snippet in #Swift 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 ...
christopher/rosetta-code