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/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...
#XLISP
XLISP
(define starlings (make-table))
Give a code snippet in #XLISP 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/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 ...
#R
R
library(combinat) perm <- function(A) { stopifnot(is.matrix(A)) n <- nrow(A) if(n != ncol(A)) stop("Matrix is not square.") if(n < 1) stop("Matrix has a dimension of size 0.") sum(sapply(combinat::permn(n), function(sigma) prod(sapply(1:n, function(i) A[i, sigma[i]])))) }   #We copy our test cases from the Py...
Give a code snippet in #R 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 p...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score...
#Elixir
Elixir
defmodule Game do def guess(a..b) do x = Enum.random(a..b) guess(x, a..b, div(a+b, 2)) end   defp guess(x, a.._b, guess) when x < guess do IO.puts "Is it #{guess}? Too High." guess(x, a..guess-1, div(a+guess, 2)) end defp guess(x, _a..b, guess) when x > guess do IO.puts "Is it #{guess}? To...
Give a code snippet in #Elixir Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The...
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 ...
#Kotlin
Kotlin
// version 1.0.5-2   fun meanAngle(angles: DoubleArray): Double { val sinSum = angles.sumByDouble { Math.sin(it * Math.PI / 180.0) } val cosSum = angles.sumByDouble { Math.cos(it * Math.PI / 180.0) } return Math.atan2(sinSum / angles.size, cosSum / angles.size) * 180.0 / Math.PI }   fun main(args: Array<S...
Give a code snippet in #Kotlin 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 rea...
christopher/rosetta-code
http://rosettacode.org/wiki/Ascending_primes
Ascending primes
Generate and show all primes with strictly ascending decimal digits. Aside: Try solving without peeking at existing solutions. I had a weird idea for generating a prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial but generating them quickly is at least mildly interesting. T...
#Go
Go
package main   import ( "fmt" "rcu" "sort" )   var ascPrimesSet = make(map[int]bool) // avoids duplicates   func generate(first, cand, digits int) { if digits == 0 { if rcu.IsPrime(cand) { ascPrimesSet[cand] = true } return } for i := first; i < 10; i++ { ...
Give a code snippet in #Go Generate and show all primes with strictly ascending decimal digits. Aside: Try solving without peeking at existing solutions. I had a weird idea for generating a prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial but generating them quickly is at...
christopher/rosetta-code
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120....
#BCPL
BCPL
get "libhdr" manifest $( MAXIMUM = 120 $)   let sieve(prime, max) be $( for i=0 to max do i!prime := i>=2 for i=2 to max>>1 if i!prime $( let j = i<<1 while j <= max do $( j!prime := false j := j+i $) $) $)   let factors(n, prime, max) = valof $( let count = 0 fo...
Give a code snippet in #BCPL A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Sh...
christopher/rosetta-code
http://rosettacode.org/wiki/Mayan_calendar
Mayan calendar
The ancient Maya people had two somewhat distinct calendar systems. In somewhat simplified terms, one is a cyclical calendar known as The Calendar Round, that meshes several sacred and civil cycles; the other is an offset calendar known as The Long Count, similar in many ways to the Gregorian calendar. The Calendar R...
#Go
Go
package main   import ( "fmt" "strconv" "strings" "time" )   var sacred = strings.Fields("Imix’ Ik’ Ak’bal K’an Chikchan Kimi Manik’ Lamat Muluk Ok Chuwen Eb Ben Hix Men K’ib’ Kaban Etz’nab’ Kawak Ajaw")   var civil = strings.Fields("Pop Wo’ Sip Sotz’ Sek Xul Yaxk’in Mol Ch’en Yax Sak’ Keh Mak K’ank’in ...
Give a code snippet in #Go The ancient Maya people had two somewhat distinct calendar systems. In somewhat simplified terms, one is a cyclical calendar known as The Calendar Round, that meshes several sacred and civil cycles; the other is an offset calendar known as The Long Count, similar in many ways to the Gregori...
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 ...
#Octave
Octave
  in = fopen("input.txt", "r", "native"); out = fopen("output.txt", "w","native"); if (in == -1) disp("Error opening input.txt for reading."); else if (out == -1) disp("Error opening output.txt for writing."); else while (1) [val,count]=fread(in,1,"uchar",0,"native"); if (count > 0) count=fwrite(out,val,"uc...
Give a code snippet in #Octave 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#Yabasic
Yabasic
  sub ordinal$ (n) NMod10 = mod(n, 10) NMod100 = mod(n, 100) if (NMod10 = 1) and (NMod100 <> 11) then return "st" else if (NMod10 = 2) and (NMod100 <> 12) then return "nd" else if (NMod10 = 3) and (NMod100 <> 13) then return "rd" else ...
Give a code snippet in #Yabasic Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to sh...
christopher/rosetta-code
http://rosettacode.org/wiki/Parse_an_IP_Address
Parse an IP Address
The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address [::1]:80 The "localhost" IPv6...
#Julia
Julia
  const testdata = ["127.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", "::ffff:192.168.173.22", "[::ffff:192.168.173.22]:80", "1::", "[1::]:80", "::", "[::]:80"]   maybev4(ip) = search(ip, '.') > 0 && length(...
Give a code snippet in #Julia The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6. Taking the following as inputs: 127.0.0.1 The "localhost" IPv4 address 127.0.0.1:80 The "localhost" IPv4 address, with a specified port (80) ::1 The "localhost" IPv6 address ...
christopher/rosetta-code
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. 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) Benford's law, also called the first-digit law, refers to the freque...
#Raku
Raku
sub benford(@a) { bag +« @a».substr(0,1) }   sub show(%distribution) { printf "%9s %9s  %s\n", <Actual Expected Deviation>; for 1 .. 9 -> $digit { my $actual = %distribution{$digit} * 100 / [+] %distribution.values; my $expected = (1 + 1 / $digit).log(10) * 100; printf "%d: %5.2f%% | %5....
Give a code snippet in #Raku This page uses content from Wikipedia. The original article was at Benford's_law. 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) Benford's law, also called the first-d...
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#ALGOL_68
ALGOL 68
main:( printf(($gl$, ABS "a")); # for ASCII this prints "+97" EBCDIC prints "+129" # printf(($gl$, REPR 97)) # for ASCII this prints "a"; EBCDIC prints "/" # )
Give a code snippet in #ALGOL_68 Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). C...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Maple
Maple
printf("String:"); string_value := readline(); printf("Integer: "); int_value := parse(readline());
Give a code snippet in #Maple User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#Befunge
Befunge
v_$0:8p>:#v_:18p08g1-08p >:08g`!v ~->p5p ^ 0v1p80-1g80vj!-g5g80g5_0'ev :a^80+1:g8<>8g1+:18pv>0"eslaF">:#,_@ [[relet]]-2010------>003-x -^"Tru"<
Give a code snippet in #Befunge A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail 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 ...
#Icon_and_Unicon
Icon and Unicon
procedure main() #: demonstrate various ways to sort a list and string demosort(cocktailsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty") end   procedure cocktailsort(X,op) #: return sorted list local i,swapped   op := sortop(op,X) # select how and what we sort   swapped :...
Give a code snippet in #Icon_and_Unicon 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/et...
#Wren
Wren
import "/dynamic" for Tuple   var Element = Tuple.create("Element", ["record", "index"])   var findFirst = Fn.new { |seq, pred| var i = 0 for (e in seq) { if (pred.call(e)) return Element.new(e, i) i = i + 1 } return Element.new(null, -1) }   var City = Tuple.create("City", ["name", "pop...
Give a code snippet in #Wren Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[ed...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#uBasic.2F4tH
uBasic/4tH
PRINT "Bubble sort:" n = FUNC (_InitArray) PROC _ShowArray (n) PROC _Bubblesort (n) PROC _ShowArray (n) PRINT   END   _Bubblesort PARAM(1) ' Bubble sort LOCAL (2)   DO b@ = 0 FOR c@ = 1 TO a@-1 IF @(c@-1) > @(c@) THEN PROC _Swap (c@, c@-1) : b@ = c@ NEXT a@ = b@ U...
Give a code snippet in #uBasic.2F4tH 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 | Q...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_block_comments
Strip block comments
A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at least handle simple, non-ne...
#Prolog
Prolog
    :- system:set_prolog_flag(double_quotes,codes) .   strip_block_comments(INPUTz) :- strip_block_comments(INPUTz,OUTPUTz) , system:format("```~n",[OUTPUTz]) , system:format("~s~n",[OUTPUTz]) , system:format("```~n",[OUTPUTz]) .   strip_block_comments(INPUTz,OUTPUTz) :- prolog:phrase(block(OUTPUTz),INPUTz) .   block([...
Give a code snippet in #Prolog A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos shoul...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Haskell
Haskell
import Data.Map   makeMap ks vs = fromList $ zip ks vs mymap = makeMap ['a','b','c'] [1,2,3]
Give a code snippet in #Haskell Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
christopher/rosetta-code
http://rosettacode.org/wiki/Super-d_numbers
Super-d numbers
A super-d number is a positive, decimal (base ten) integer   n   such that   d × nd   has at least   d   consecutive digits   d   where 2 ≤ d ≤ 9 For instance, 753 is a super-3 number because 3 × 7533 = 1280873331. Super-d   numbers are also shown on   MathWorld™   as   super-d   or   super-d. Task Write a...
#R
R
library(Rmpfr) options(scipen = 999)   find_super_d_number <- function(d, N = 10){   super_number <- c(NA) n = 0 n_found = 0   while(length(super_number) < N){   n = n + 1 test = d * mpfr(n, precBits = 200) ** d #Here I augment precision test_formatted = .mpfr2str(test)$str #and I extract the...
Give a code snippet in #R A super-d number is a positive, decimal (base ten) integer   n   such that   d × nd   has at least   d   consecutive digits   d   where 2 ≤ d ≤ 9 For instance, 753 is a super-3 number because 3 × 7533 = 1280873331. Super-d   numbers are also shown on   MathWorld™   as   super-d   or  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#Prolog
Prolog
consolidate_ranges(Ranges, Consolidated):- normalize(Ranges, Normalized), sort(Normalized, Sorted), merge(Sorted, Consolidated).   normalize([], []):-!. normalize([r(X, Y)|Ranges], [r(Min, Max)|Normalized]):- (X > Y -> Min = Y, Max = X; Min = X, Max = Y), normalize(Ranges, Normalized).   merge([], [...
Give a code snippet in #Prolog Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one rang...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#SVG
SVG
  class Sphere: UIView{   override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() let locations: [CGFloat] = [0.0, 1.0]   let colors = [UIColor.whiteColor().CGColor, UIColor.blueColor().CGColor]   let colorspace = CGColorSpaceCreateDeviceRGB()   let gradient = CG...
Give a code snippet in #SVG Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deat...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#CLU
CLU
% generate the size-M combinations from 0 to n-1 combinations = iter (m, n: int) yields (sequence[int]) if m<=n then state: array[int] := array[int]$predict(1, m) for i: int in int$from_to(0, m-1) do array[int]$addh(state, i) end   i: int := m while i>0 do ...
Give a code snippet in #CLU Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl...
#Elixir
Elixir
defmodule Catalan do def numbers(num) do {result,_} = Enum.reduce(1..num, {[],{0,1}}, fn i,{list,t0} -> t1 = numbers(i, t0) t2 = numbers(i+1, Tuple.insert_at(t1, i+1, elem(t1, i))) {[elem(t2, i+1) - elem(t2, i) | list], t2} end) Enum.reverse(result) end   defp numbers(0, t), do: t ...
Give a code snippet in #Elixir Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that gen...
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. ...
#OCaml
OCaml
for i = 1 to 5 do for j = 1 to i do print_string "*" done; print_newline () done
Give a code snippet in #OCaml “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/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...
#ALGOL_68
ALGOL 68
BEGIN # Magic squares of doubly even order # PROC doubly even magic square = ( INT n )[,]INT: IF n MOD 4 /= 0 THEN # not a doubly even number # [ 1 : 0, 1 : 0 ]INT empty square; empty square ELSE # ok to create the square # [ 1 : 4, 1 : 4...
Give a code snippet in #ALGOL_68 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 si...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#R
R
# For reproducibility, set the seed: set.seed(12345L)   result <- rnorm(1000, mean = 1, sd = 0.5)
Give a code snippet in #R Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related tas...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#FreeBASIC
FreeBASIC
' version 20-06-2015 ' compile with: fbc -s console "filename".bas   #Ifndef TRUE ' define true and false for older freebasic versions #Define FALSE 0 #Define TRUE Not FALSE #EndIf   Function reverse(norm As String) As Integer   Dim As String rev Dim As Integer i, l = Len(norm) -1   rev = nor...
Give a code snippet in #FreeBASIC A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibl...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#LOLCODE
LOLCODE
HAI 1.3   VISIBLE "SEED ME, FEMUR! "! I HAS A seed, GIMMEH seed   HOW IZ I randomizin seed R MOD OF SUM OF 1 AN PRODUKT OF 69069 AN seed AN 10 IF U SAY SO   I IZ randomizin MKAY I HAS A answer ITZ SUM OF seed AN 1 I HAS A guess   IM IN YR guesser VISIBLE "WUTS MY NUMBR? "! GIMMEH guess, guess IS NOW A NUMBR...
Give a code snippet in #LOLCODE Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a...
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) ...
#Gleam
Gleam
import gleam/int import gleam/io import gleam/iterator   pub fn main() { iterator.range(1, 101) |> iterator.map(to_fizzbuzz) |> iterator.map(io.println) |> iterator.run }   fn to_fizzbuzz(n: Int) -> String { case n % 3, n % 5 { 0, 0 -> "FizzBuzz" 0, _ -> "Fizz" _, 0 -> "Buzz" _, _ -> int.to_st...
Give a code snippet in #Gleam 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/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/sha.h>   int main() { int i; unsigned char result[SHA_DIGEST_LENGTH]; const char *string = "Rosetta Code";   SHA1(string, strlen(string), result);   for(i = 0; i < SHA_DIGEST_LENGTH; i++) printf("%02x%c", result[i], i < (SHA_DIGE...
Give a code snippet in #C SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identif...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#Tcl
Tcl
package require Tcl 8.5 package require Tk   proc drawCircle {image colour point radius} { lassign $point x0 y0   setPixel $image $colour [list $x0 [expr {$y0 + $radius}]] setPixel $image $colour [list $x0 [expr {$y0 - $radius}]] setPixel $image $colour [list [expr {$x0 + $radius}] $y0] setPixel $im...
Give a code snippet in #Tcl Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#VBScript
VBScript
Function Luhn_Test(cc) cc = RevString(cc) s1 = 0 s2 = 0 For i = 1 To Len(cc) If i Mod 2 > 0 Then s1 = s1 + CInt(Mid(cc,i,1)) Else tmp = CInt(Mid(cc,i,1))*2 If tmp < 10 Then s2 = s2 + tmp Else s2 = s2 + CInt(Right(CStr(tmp),1)) + 1 End If End If Next If Right(CStr(s1 + s2),1) = "0" T...
Give a code snippet in #VBScript The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order...
christopher/rosetta-code
http://rosettacode.org/wiki/Teacup_rim_text
Teacup rim text
On a set of coasters we have, there's a picture of a teacup.   On the rim of the teacup the word   TEA   appears a number of times separated by bullet characters   (•). It occurred to me that if the bullet were removed and the words run together,   you could start at any letter and still end up with a meaningful three...
#Java
Java
import java.io.*; import java.util.*;   public class Teacup { public static void main(String[] args) { if (args.length != 1) { System.err.println("usage: java Teacup dictionary"); System.exit(1); } try { findTeacupWords(loadDictionary(args[0])); } ...
Give a code snippet in #Java On a set of coasters we have, there's a picture of a teacup.   On the rim of the teacup the word   TEA   appears a number of times separated by bullet characters   (•). It occurred to me that if the bullet were removed and the words run together,   you could start at any letter and still ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fivenum
Fivenum
Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the   R   programming language i...
#Raku
Raku
sub fourths ( Int $end ) { my $end_22 = $end div 2 / 2;   return 0, $end_22, $end/2, $end - $end_22, $end; } sub fivenum ( @nums ) { my @x = @nums.sort(+*) or die 'Input must have at least one element';   my @d = fourths(@x.end);   return ( @x[@d».floor] Z+ @x[@d».ceiling] ) »/» 2; }   say ....
Give a code snippet in #Raku Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, th...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequ...
#NewLISP
NewLISP
; file: ocount.lsp ; url: http://rosettacode.org/wiki/Count_in_octal ; author: oofoe 2012-01-29   ; Although NewLISP itself uses a 64-bit integer representation, the ; format function relies on underlying C library's printf function, ; which can only handle a 32-bit octal number on this implementation.   (for (i 0...
Give a code snippet in #NewLISP Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached....
christopher/rosetta-code
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#TXR
TXR
(defun power-set (s) (mappend* (op comb s) (range 0 (length s))))
Give a code snippet in #TXR A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a...
christopher/rosetta-code
http://rosettacode.org/wiki/Parametric_polymorphism
Parametric polymorphism
Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, ...
#J
J
public class Tree<T>{ private T value; private Tree<T> left; private Tree<T> right;   public void replaceAll(T value){ this.value = value; if (left != null) left.replaceAll(value); if (right != null) right.replaceAll(value); } }
Give a code snippet in #J Parametric Polymorphism type variables Task Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some functio...
christopher/rosetta-code
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#Factor
Factor
USING: formatting kernel locals make sequences ;   : to-front ( elt seq -- seq' ) over [ remove ] dip prefix ;   : encode ( symbols msg -- indices ) [ [ swap 2dup index , to-front ] each ] { } make nip ;   : decode ( symbols indices -- msg ) [ [ swap [ nth ] keep over , to-front ] each ] "" make nip ;   :: roun...
Give a code snippet in #Factor Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is usefu...
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
#Haskell
Haskell
import Text.Regex   str = "I am a string"   case matchRegex (mkRegex ".*string$") str of Just _ -> putStrLn $ "ends with 'string'" Nothing -> return ()
Give a code snippet in #Haskell Task   match a string against a regular expression   substitute part of a string using a regular expression
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...
#Frink
Frink
array = new array[[10,10], {|x,y| random[1,20]}]   println["array is:\n" + formatTable[array, "right"] + "\n"]   [rows,cols] = array.dimensions[]   ROW: for r = 0 to rows-1 for c = 0 to cols-1 { print[array@r@c + " " ] if array@r@c == 20 break ROW }
Give a code snippet in #Frink 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 me...
christopher/rosetta-code
http://rosettacode.org/wiki/Merge_and_aggregate_datasets
Merge and aggregate datasets
Merge and aggregate datasets Task Merge and aggregate two datasets as provided in   .csv   files into a new resulting dataset. Use the appropriate methods and data structures depending on the programming language. Use the most common libraries only when built-in functionality is not sufficient. Note Either lo...
#R
R
# load data from csv files # setwd("C:\Temp\csv\") # df_patient <- read.csv(file="patients.csv", header = TRUE, sep = ",") # df_visits <- read.csv(file="visits.csv", header = TRUE, sep = ",", dec = ".", colClasses=c("character","character","numeric"))   # load data hard coded, create data frames df_patient <- read.tabl...
Give a code snippet in #R Merge and aggregate datasets Task Merge and aggregate two datasets as provided in   .csv   files into a new resulting dataset. Use the appropriate methods and data structures depending on the programming language. Use the most common libraries only when built-in functionality is not suf...
christopher/rosetta-code
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#ALGOL_W
ALGOL W
begin % compute values of the Mertens function  % integer array M ( 1 :: 1000 ); integer k, zero, cross;  % Generate Mertens numbers  % M( 1 ) := 1; for n := 2 until 1000 do begin M( n ) := 1; for k := 2 until n do M( n ) ...
Give a code snippet in #ALGOL_W The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möb...
christopher/rosetta-code
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#AppleScript
AppleScript
-- This handler just returns the standardised real value. It's up to external processes to format it for display.   on standardisePrice(input) set integerPart to input div 1.0 set fractionalPart to input mod 1.0   if (fractionalPart is 0.0) then return input as real else if (fractionalPart < 0.0...
Give a code snippet in #AppleScript A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#J
J
9!:1 random seed (incomplete specification of state -- see 9!:45) 9!:3 default display for non-nouns 9!:7 box drawing characters 9!:9 error messages 9!:11 print precision 9!:17 centering (or not) when box contents are smaller than boxes 9!:19 comparison tolerance 9!:21 memory limit 9!:25 security level 9!:27 text of i...
Give a code snippet in #J Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-transitive_dice
Non-transitive dice
Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 defined sides is defined by the numb...
#MiniZinc
MiniZinc
  %Non transitive dice. Nigel Galloway, September 14th., 2020 int: die; int: faces; set of int: values; predicate pN(array[1..faces] of var values: n, array[1..faces] of var values: g) = sum(i in 1..faces,j in 1..faces)(if n[i]<g[j] then 1 elseif n[i]>g[j] then -1 else 0 endif)>0; predicate pG(array[1..faces] of var va...
Give a code snippet in #MiniZinc Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 de...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Wren
Wren
System.print("Hello world!")
Give a code snippet in #Wren Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print str...
#360_Assembly
360 Assembly
* Strip a set of characters from a string 07/07/2016 STRIPCH CSECT USING STRIPCH,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " <- ST R15,...
Give a code snippet in #360_Assembly Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characte...
christopher/rosetta-code
http://rosettacode.org/wiki/JortSort
JortSort
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 JortSort;   {$APPTYPE CONSOLE} {$R *.res}   uses System.SysUtils, System.Generics.Collections, System.Generics.Defaults;   type TArrayHelper = class helper for TArray public class function JortSort<T>(const original: TArray<T>): Boolean; static; end;   { TArrayHelper }   class function TArrayH...
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/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...
#8086_Assembly
8086 Assembly
cpu 8086 bits 16 org 100h section .text jmp demo ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Subroutine "blocks": see if the $-terminated string in DS:BX ;;; can be written with the blocks. ;;; Returns: carry flag set if word is accepted. ;;; Uses registers: AL, BX, CX, SI, DI ...
Give a code snippet in #8086_Assembly 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#Racket
Racket
#lang racket   ;;; Generate the headings and boxes (define (i->heading/box i) (values (let ((heading (* i #e11.25))) (case (modulo i 3) ((1) (+ heading #e5.62)) ((2) (- heading #e5.62)) (else heading))) (add1 (modulo i 32)))) (define-values (headings-list box-list...
Give a code snippet in #Racket There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and d...
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...
#Pascal
Pascal
# These variables are all different $dog='Benjamin'; $Dog='Samba'; $DOG='Bernie'; print "The three dogs are named $dog, $Dog, and $DOG \n"
Give a code snippet in #Pascal 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/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome 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 ...
#jq
jq
# As soon as "condition" is true, then emit . and stop: def do_until(condition; next): def u: if condition then . else (next|u) end; u;   # input: an array def gnomeSort: def swap(i;j): .[i] as $x | .[i]=.[j] | .[j]=$x;   length as $length # state: [i, j, ary] | [1, 2, .] | do_until( .[0] >= $length; ...
Give a code snippet in #jq 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/Terminal_control/Positional_read
Terminal control/Positional read
Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display records to achieve this task, r...
#Phix
Phix
-- -- demo\rosetta\Positional_read.exw -- ================================ -- without js -- (position, get_screen_char) position(6,1) -- line 6 column 1 (1-based) puts(1,"abcdef") integer {ch,attr} = get_screen_char(6,3) printf(1,"\n\n=>%c",ch) {} = wait_key()
Give a code snippet in #Phix Determine the character displayed on the screen at column 3, row 6 and store that character in a variable. Note that it is permissible to utilize system or language provided methods or system provided facilities, system maintained records or available buffers or system maintained display r...
christopher/rosetta-code
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#Kotlin
Kotlin
// version 1.1.0   import java.awt.* import javax.swing.*   class ArchimedeanSpiral : JPanel() { init { preferredSize = Dimension(640, 640) background = Color.white }   private fun drawGrid(g: Graphics2D) { g.color = Color(0xEEEEEE) g.stroke = BasicStroke(2f) val angl...
Give a code snippet in #Kotlin The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
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...
#M2000_Interpreter
M2000 Interpreter
  A$={{ Module "Fibonacci" : Read X  :If X<0 then {Error {X<0}} Else Fib=Lambda (x)->if(x>1->fib(x-1)+fib(x-2), x) : =fib(x)}} Try Ok { Print Function(A$, -12) } If Error or Not Ok Then Print Error$ Print Function(A$, 12)=144 ' true  
Give a code snippet in #M2000_Interpreter 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), ca...
christopher/rosetta-code
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#Swift
Swift
({print($0+$0.debugDescription+")")})("({print($0+$0.debugDescription+\")\")})(")
Give a code snippet in #Swift A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program  ...
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 |...
#Component_Pascal
Component Pascal
  MODULE Arithmetic; IMPORT CPmain,Console,RTS;   VAR x,y : INTEGER; arg : ARRAY 128 OF CHAR; status : BOOLEAN;     PROCEDURE Error(IN str : ARRAY OF CHAR); BEGIN Console.WriteString(str);Console.WriteLn; HALT(1) END Error;     BEGIN IF CPmain.ArgNumber() < 2 THEN Error("Give me two integers!") EN...
Give a code snippet in #Component_Pascal 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Curzon_numbers
Curzon numbers
A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1. Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1. Base here does not imply the radix of the counting sys...
#Pascal
Pascal
  program CurzonNumbers; uses SysUtils; const MAX_CURZON_MEG = 100; RC_LINE_LENGTH = 66;   procedure ListCurzonNumbers( base : integer); var k, n, m, x, testBit, maxCurzon : uint64; nrHits : integer; lineOut : string; begin maxCurzon := 1000000*MAX_CURZON_MEG; k := uint64( base); nrHits := 0; n := 0; ...
Give a code snippet in #Pascal A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1. Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1. Base here does not imp...
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
#Blade
Blade
print('Goodbye, World!')
Give a code snippet in #Blade 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/Stand...
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.
#Visual_Basic
Visual Basic
  Debug.Print Format$(7.125, "00000.000")  
Give a code snippet in #Visual_Basic 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/Variable_declaration_reset
Variable declaration reset
A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may ...
#AWK
AWK
  # syntax: GAWK -f VARIABLE_DECLARATION_RESET.AWK BEGIN { n = split("1,2,2,3,4,4,5",arr,",") for (i=1; i<=n; i++) { curr = arr[i] if (i > 1 && prev == curr) { printf("%s\n",i) } prev = curr } exit(0) }  
Give a code snippet in #AWK A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}....
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 ...
#Phix
Phix
with javascript_semantics sequence s = repeat("x",6) ?s s[$] = 5 ?s s[1] &= 'y' ?s -- s[2] = s  ?s s[2] = deep_copy(s) ?s
Give a code snippet in #Phix 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 considere...
christopher/rosetta-code
http://rosettacode.org/wiki/File_extension_is_in_extensions_list
File extension is in extensions list
File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of extensions, tell whether the filename...
#C
C
/* * File extension is in extensions list (dots allowed). * * This problem is trivial because the so-called extension is simply the end * part of the name. */   #define _CRT_SECURE_NO_WARNINGS   #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <locale.h> #include <string.h>   #ifdef _Bool #includ...
Give a code snippet in #C File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of extensions...
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 ...
#C.2B.2B
C++
#include <vector> #include <memory> // for auto_ptr #include <cmath> // for the ceil and log10 and floor functions #include <iostream> #include <iomanip> // for the setw function   using namespace std;   typedef vector< int > IntRow; typedef vector< IntRow > IntTable;   auto_ptr< IntTable > getSpiralArray( int dimensio...
Give a code snippet in #C.2B.2B 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Raku
Raku
multi is-Brazilian (Int $n where $n %% 2 && $n > 6) { True }   multi is-Brazilian (Int $n) { LOOP: loop (my int $base = 2; $base < $n - 1; ++$base) { my $digit; for $n.polymod( $base xx * ) { $digit //= $_; next LOOP if $digit != $_; } return True } Fa...
Give a code snippet in #Raku Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you ...
#Python
Python
  import doctest import random     def flatten(lst): """ >>> flatten([[3,2],[1,2]]) [3, 2, 1, 2] """ return [i for sublst in lst for i in sublst]   def magic_shuffle(deck): """ >>> magic_shuffle([1,2,3,4]) [1, 3, 2, 4] """ half = len(deck) // 2 return flatten(zip(deck[:half]...
Give a code snippet in #Python A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Quackery
Quackery
[ stack ] is rings ( --> [ )   [ rings share depth share - 8 * times sp emit sp emit sp say 'move' cr ] is echomove ( c c --> )   [ dup rings put depth put char a char b char c [ swap decurse rot 2dup echomove decurse swap rot ...
Give a code snippet in #Quackery Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. ...
#Ruby
Ruby
def getDifference(b1, b2) r = (b2 - b1) % 360.0 # Ruby modulus has same sign as divisor, which is positive here, # so no need to consider negative case if r >= 180.0 r -= 360.0 end return r end   if __FILE__ == $PROGRAM_NAME puts "Input in -180 to +180 range" puts getDifference(20.0, 45.0) puts getDifference...
Give a code snippet in #Ruby Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#UNIX_Shell
UNIX Shell
  #!/bin/bash   DELAY=0 # increase this if printing of matrices should be slower   echo "This script takes two matrices, henceforth called A and B, and returns their product, AB.   For the time being, matrices can have integer components only.   "   read -p "Number of rows of matrix A: " arows read -p "Number of co...
Give a code snippet in #UNIX_Shell Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature
Numerical integration/Gauss-Legendre Quadrature
In a general Gaussian quadrature rule, an definite integral of f ( x ) {\displaystyle f(x)} is first approximated over the interval [ − 1 , 1 ] {\displaystyle [-1,1]} by a polynomial approximable function g ( x ) {\displaystyle g(x)} and a known weighting function W ( x ) {\displaystyle ...
#Raku
Raku
multi legendre-pair( 1 , $x) { $x, 1 } multi legendre-pair(Int $n, $x) { my ($m1, $m2) = legendre-pair($n - 1, $x); my \u = 1 - 1 / $n; (1 + u) * $x * $m1 - u * $m2, $m1; }   multi legendre( 0 , $ ) { 1 } multi legendre(Int $n, $x) { legendre-pair($n, $x)[0] }   multi legendre-prime( 0 , $ ) { 0 } ...
Give a code snippet in #Raku In a general Gaussian quadrature rule, an definite integral of f ( x ) {\displaystyle f(x)} is first approximated over the interval [ − 1 , 1 ] {\displaystyle [-1,1]} by a polynomial approximable function g ( x ) {\displaystyle g(x)} and a known weighting function...
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.
#jq
jq
(1,2,3,4,5,6,7,8,9) | select(. % 2 == 0)
Give a code snippet in #jq 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/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#Smalltalk
Smalltalk
  (SHA256 new hashStream: 'Rosetta code' readStream) hex.  
Give a code snippet in #Smalltalk SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa54271396...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Ada
Ada
with Ada.Command_Line, Ada.Text_IO;   procedure Command_Name is begin Ada.Text_IO.Put_Line(Ada.Command_Line.Command_Name); end Command_Name;
Give a code snippet in #Ada The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script na...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring
Substring
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Gambas
Gambas
Public Sub Main() Dim sString As String = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"   Print Mid(sString, 11, 5) 'Starting from n characters in and of m length Print Mid(sString, 17) 'Starting from n characters in, up to the end of the string Print Left(sString, -1) ...
Give a code snippet in #Gambas 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/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#OCaml
OCaml
let is_prime n = if n = 2 then true else if n < 2 || n mod 2 = 0 then false else let rec loop k = if k * k > n then true else if n mod k = 0 then false else loop (k+2) in loop 3
Give a code snippet in #OCaml Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops...
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,...
#LIL
LIL
# (not) Arrays, in LIL set a [list abc def ghi] set b [list 4 5 6] print [index $a 0] print [index $b 1] print [count $a] append b [list 7 8 9] print [count $b] print $b
Give a code snippet in #LIL This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retriev...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Common_Lisp
Common Lisp
;;; Play nice with shebangs (set-dispatch-macro-character #\# #\! (lambda (stream character n) (declare (ignore character n)) (read-line stream nil nil t) nil))
Give a code snippet in #Common_Lisp The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the s...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Fur...
#C
C
#include <stdio.h> #include <stdlib.h> #define FMT "%lld" typedef long long int fr_int_t; typedef struct { fr_int_t num, den; } frac;   fr_int_t gcd(fr_int_t m, fr_int_t n) { fr_int_t t; while (n) { t = n; n = m % n; m = t; } return m; }   frac frac_new(fr_int_t num, fr_int_t den) { frac a; if (!den) { printf("d...
Give a code snippet in #C Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as p...
christopher/rosetta-code
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#Racket
Racket
#lang racket (define default-symtab "abcdefghijklmnopqrstuvwxyz")   (define (move-to-front:encode in (symtab default-symtab)) (define inner-encode (match-lambda** [((? string? (app string->list in)) st acc) ; make input all listy (inner-encode in st acc)] [(in (? string? (app string->list st)) acc...
Give a code snippet in #Racket Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is usefu...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print str...
#PL.2FI
PL/I
strip_chars: procedure (text, chars) returns (character (100) varying); declare text character (*) varying, chars character (*) varying; declare out_text character (100); declare ch character (1); declare (i, j) fixed binary;   j = 0; do i = 1 to length(text); ch = substr(text, i, 1); if i...
Give a code snippet in #PL.2FI Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in ...
christopher/rosetta-code
http://rosettacode.org/wiki/Totient_function
Totient function
The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the integers up to a given positiv...
#zkl
zkl
fcn totient(n){ [1..n].reduce('wrap(p,k){ p + (n.gcd(k)==1) }) } fcn isPrime(n){ totient(n)==(n - 1) }
Give a code snippet in #zkl The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the i...
christopher/rosetta-code
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#M2000_Interpreter
M2000 Interpreter
  Module UseBlink { Def boolean direction=True rotating$ =lambda$ a$="Hello World! " (direction as boolean)->{ =a$ a$=if$(direction->right$(a$,1)+mid$(a$,1, len(a$)-1), mid$(a$,2)+left$(a$,1)) } Declare MyForm Form Declare MyButton Button Form MyForm With My...
Give a code snippet in #M2000_Interpreter Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   ...
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...
#OCaml
OCaml
let fib n = let rec real = function 0 -> 1 | 1 -> 1 | n -> real (n-1) + real (n-2) in if n < 0 then None else Some (real n)
Give a code snippet in #OCaml 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 unwant...
christopher/rosetta-code
http://rosettacode.org/wiki/Linear_congruential_generator
Linear congruential generator
The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaystyle r_{0}} is a seed. r 1 ...
#Batch
Batch
  @echo off & setlocal enabledelayedexpansion   echo BSD Rand set /a a=0,cnt=1 :b set /a "a=1103515245 *a+12345,a&=0x7fffffff, cnt+=1" call:prettyprint !cnt! !a! if !cnt! leq 10 goto :b   echo. echo Microsoft Rand set /a a=0,cnt=1 :c set /a "a=214013 *a+2531011,a&=0x7fffffff, b=a>>16,cnt+=1" call:prettyprint !cnt! !b! ...
Give a code snippet in #Batch The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaystyle r...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl...
#Groovy
Groovy
  class Catalan { public static void main(String[] args) { BigInteger N = 15; BigInteger k,n,num,den; BigInteger catalan; print(1); for(n=2;n<=N;n++) { num = 1; den = 1; for(k=2;k<=n;k++) { num = num*(n+k);...
Give a code snippet in #Groovy Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that gen...
christopher/rosetta-code
http://rosettacode.org/wiki/Inheritance/Single
Inheritance/Single
This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent types. Usually inherited properties...
#zkl
zkl
class Animal{} class Dog(Animal){} class Cat(Animal){} class Lab(Dog){} class Collie(Dog){} Collie.linearizeParents
Give a code snippet in #zkl This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent types. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. 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) Benford's law, also called the first-digit law, refers to the freque...
#Ada
Ada
with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions;   procedure Benford is   subtype Nonzero_Digit is Natural range 1 .. 9; function First_Digit(S: String) return Nonzero_Digit is (if S(S'First) in '1' .. '9' then Nonzero_Digit'Value(S(S'First .. S'First)) else First_Digit(S(S'F...
Give a code snippet in #Ada This page uses content from Wikipedia. The original article was at Benford's_law. 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) Benford's law, also called the first-di...
christopher/rosetta-code
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an ob...
#Phix
Phix
type nullableString(object o) return string(o) or o=NULL end type nullableString s s = "hello" s = NULL --s = 1 -- error --s = {1,2,3} -- error type nullableSequence(object o) return sequence(o) or o=NULL end type nullableSequence q q = {1,2,3} q = "string" -- fine (strings are a subset of sequences) q = N...
Give a code snippet in #Phix Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your langua...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#Go
Go
func multiply(a, b float64) float64 { return a * b }
Give a code snippet in #Go A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract fro...
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 ⋮ ⋮ ⋮ ⋱ ...
#VBScript
VBScript
  build_matrix(7)   Sub build_matrix(n) Dim matrix() ReDim matrix(n-1,n-1) i = 0 'populate the matrix For row = 0 To n-1 For col = 0 To n-1 If col = i Then matrix(row,col) = 1 Else matrix(row,col) = 0 End If Next i = i + 1 Next 'display the matrix For row = 0 To n-1 For col = 0 To n-1 ...
Give a code snippet in #VBScript 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/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game where one player prompts another...
#D
D
import std.stdio, std.regex, std.algorithm, std.string, std.array;   void main() { writeln("Enter a story template, terminated by an empty line:"); string story; while (true) { auto line = stdin.readln().strip(); if (line.empty) break; story ~= line ~ "\n"; }   auto re = rege...
Give a code snippet in #D This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game where...
christopher/rosetta-code
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#Erlang
Erlang
-module(mutrec). -export([mutrec/0, f/1, m/1]).   f(0) -> 1; f(N) -> N - m(f(N-1)).   m(0) -> 0; m(N) -> N - f(m(N-1)).   mutrec() -> lists:map(fun(X) -> io:format("~w ", [f(X)]) end, lists:seq(0,19)), io:format("~n", []), lists:map(fun(X) -> io:format("~w ", [m(X)]) end, lists:seq(0,19)), io:format("~n"...
Give a code snippet in #Erlang Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n...
christopher/rosetta-code
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Elixir
Elixir
iex(1)> ls = fn dir -> File.ls!(dir) |> Enum.each(&IO.puts &1) end #Function<6.54118792/1 in :erl_eval.expr/5> iex(2)> ls.("foo") bar :ok iex(3)> ls.("foo/bar") 1 2 a b :ok
Give a code snippet in #Elixir Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Examp...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * ...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   numeric digits 1000 runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) public static BLACK_UPPOINTING_TRIANGLE = '\u25b2' parse arg ordr filr . if ordr = '' | ...
Give a code snippet in #NetRexx Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * ...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definitio...
#Swift
Swift
typealias NodePtr<T> = UnsafeMutablePointer<Node<T>>   class Node<T> { var value: T fileprivate var prev: NodePtr<T>? fileprivate var next: NodePtr<T>?   init(value: T, prev: NodePtr<T>? = nil, next: NodePtr<T>? = nil) { self.value = value self.prev = prev self.next = next } }   struct DoublyLinke...
Give a code snippet in #Swift Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type...
christopher/rosetta-code
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#Prolog
Prolog
turing(Config, Rules, TapeIn, TapeOut) :- call(Config, IS, _, _, _, _), perform(Config, Rules, IS, {[], TapeIn}, {Ls, Rs}), reverse(Ls, Ls1), append(Ls1, Rs, TapeOut).   perform(Config, Rules, State, TapeIn, TapeOut) :- call(Config, _, FS, RS, B, Symbols), ( memberchk(State, FS) -> TapeO...
Give a code snippet in #Prolog One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machin...
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use
Text processing/Max licenses in use
A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a checkout event when a copy of the ...
#Euphoria
Euphoria
function split(sequence s, integer c) sequence out integer first, delim out = {} first = 1 while first <= length(s) do delim = find_from(c, s, first) if delim = 0 then delim = length(s) + 1 end if out = append(out, s[first..delim-1]) first = delim ...
Give a code snippet in #Euphoria A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#PHP
PHP
  <?php   session_start();   if(isset($_SESSION['number'])) { $number = $_SESSION['number']; } else { $_SESSION['number'] = rand(1,10); }     if(isset($_POST["guess"])){ if($_POST["guess"]){ $guess = htmlspecialchars($_POST['guess']);   echo $guess . "<br />"; if ($guess != $number) { ec...
Give a code snippet in #PHP Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#UNIX_Shell
UNIX Shell
#!/bin/sh   if [ -z $1 ]; then exit 1; fi   # weed out multiple erros due to bad year ncal 1 $1 > /dev/null && \ for m in 01 02 03 04 05 06 07 08 09 10 11 12; do echo $1-$m-`ncal $m $1 | grep Fr | sed 's/.* \([0-9]\)/\1/'` done
Give a code snippet in #UNIX_Shell Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24...
christopher/rosetta-code