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/Knuth%27s_algorithm_S
Knuth's algorithm S
This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end. This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive sam...
#Phix
Phix
with javascript_semantics enum RID, I, SAMPLE function s_of_n(sequence env, integer item) integer i = env[I] + 1, n = length(env[SAMPLE]) env = deep_copy(env) env[I] = i if i<=n then env[SAMPLE][i] = item elsif n/i>rnd() then env[SAMPLE][rand(n)] = item end if r...
Give a code snippet in #Phix This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end. This means that the equal probability sampling should be maintained for all successive items > n as they become available (although...
christopher/rosetta-code
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#F.23
F#
> let nums = [1 .. 10];; val nums : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] > let summation = List.fold (+) 0 nums;; val summation : int = 55 > let product = List.fold (*) 1 nums;; val product : int = 3628800 > let concatenation = List.foldBack (fun x y -> x + y) (List.map (fun i -> i.ToString()) nums) "";; v...
Give a code snippet in #F.23 Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. ...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#Yorick
Yorick
doors = array(0, 100); for(i = 1; i <= 100; i++) for(j = i; j <= 100; j += i) doors(j) ~= 1; print, where(doors);
Give a code snippet in #Yorick There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ....
christopher/rosetta-code
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#Pike
Pike
#!/usr/bin/env pike   int next(int n) { if (n==1) return 0; if (n%2) return 3*n+1; else return n/2; }   array(int) hailstone(int n) { array seq = ({ n }); while (n=next(n)) seq += ({ n }); return seq; }   void main() { array(int) two = hailstone(27); if (e...
Give a code snippet in #Pike The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#Elixir
Elixir
defmodule GuessingGame do def play(lower, upper) do play(lower, upper, Enum.random(lower .. upper)) end defp play(lower, upper, number) do guess = Integer.parse(IO.gets "Guess a number (#{lower}-#{upper}): ") case guess do {^number, _} -> IO.puts "Well guessed!" {n, _} when n in lo...
Give a code snippet in #Elixir Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: h...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by...
#S-BASIC
S-BASIC
  comment Prime number generator in S-BASIC. Only odd numbers are checked, and only the prime numbers previously found (up to the square root of the number currently under examination) are tested as divisors. Memory is conserved by saving only the first 50 primes as potential divisors, since that is suff...
Give a code snippet in #S-BASIC Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being ...
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 ...
#Prolog
Prolog
palindrome(Word) :- name(Word,List), reverse(List,List).
Give a code snippet in #Prolog 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 a...
christopher/rosetta-code
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that...
#Erlang
Erlang
-module(egypt).   -import(lists, [reverse/1, seq/2]). -export([frac/2, show/2, rosetta/0]).   rosetta() -> Fractions = [{N, D, second(frac(N, D))} || N <- seq(2,99), D <- seq(N+1, 99)], {Longest, A1, B1} = findmax(fun length/1, Fractions), io:format("~b/~b has ~b terms.~n", [A1, B1, Longest]), {Largest,...
Give a code snippet in #Erlang An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Yabasic
Yabasic
  sub InsertionSort (matriz()) for i = 1 to arraysize(matriz(),1) valor = matriz(i) j = i - 1 while (j >= 0) and (valor < matriz(j)) matriz(j + 1) = matriz(j) j = j - 1 wend matriz(j + 1) = valor next i end sub   //-------------------------- di...
Give a code snippet in #Yabasic 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#LFE
LFE
  > (defun gcd "Get the greatest common divisor." ((a 0) a) ((a b) (gcd b (rem a b))))  
Give a code snippet in #LFE Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest c...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape
Create a file on magnetic tape
The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
#Go
Go
package main   import ( "archive/tar" "compress/gzip" "flag" "io" "log" "os" "time" )   func main() { filename := flag.String("file", "TAPE.FILE", "filename within TAR") data := flag.String("data", "", "data for file") outfile := flag.Strin...
Give a code snippet in #Go The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
christopher/rosetta-code
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#Bracmat
Bracmat
"alphaBETA":?s & out$str$(upp$!s \n low$!s)
Give a code snippet in #Bracmat Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not...
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 ...
#JavaScript
JavaScript
Array.prototype.bubblesort = function() { var done = false; while (!done) { done = true; for (var i = 1; i<this.length; i++) { if (this[i-1] > this[i]) { done = false; [this[i-1], this[i]] = [this[i], this[i-1]] } } } return...
Give a code snippet in #JavaScript Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Qui...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#XPL0
XPL0
code CrLf=9, IntOut=11;   func SumProd(A, L); int A, L; int S, P, I; [S:= 0; P:= 1; for I:= 0 to L-1 do [S:= S+A(I); P:= P*A(I)]; IntOut(0, S); CrLf(0); IntOut(0, P); CrLf(0); ]; \SumSq   SumProd([1,2,3,4,5,6,7,8,9,10], 10)
Give a code snippet in #XPL0 Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#Pascal
Pascal
Program HappyNumbers (output);   uses Math;   function find(n: integer; cache: array of integer): boolean; var i: integer; begin find := false; for i := low(cache) to high(cache) do if cache[i] = n then find := true; end;   function is_happy(n: integer): boolean; var cache: array...
Give a code snippet in #Pascal From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly...
christopher/rosetta-code
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle
Solve a Hidato puzzle
The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always connected. The number “1” is always ...
#Ruby
Ruby
# Solve a Hidato Puzzle # class Hidato Cell = Struct.new(:value, :used, :adj) ADJUST = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]   def initialize(board, pout=true) @board = [] board.each_line do |line| @board << line.split.map{|n| Cell[Integer(n), false] rescue nil} + [n...
Give a code snippet in #Ruby The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always connect...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Go
Go
package main   import ( "fmt" "strings" )   var lean = font{ height: 5, slant: 1, spacing: 2, m: map[rune][]string{ 'G': []string{ ` _/_/_/`, `_/ `, `_/ _/_/`, `_/ _/`, ` _/_/_/`, }, 'o': []string{ ...
Give a code snippet in #Go Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
christopher/rosetta-code
http://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers
Increasing gaps between consecutive Niven numbers
Note:   Niven   numbers are also called   Harshad   numbers.   They are also called    multidigital   numbers. Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisible with no remainder. Task   find the gap (differen...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[NivenQ] $HistoryLength = 0; NivenQ[n_Integer] := Divisible[n, Total[IntegerDigits[n]]] sel = Select[Range[100000000], NivenQ]; i = FoldPairList[{#2 > #1, Max[#1, #2]} &, 0, Differences[sel]]; gapindex = Range[Count[i, True]]; nivenindex = Pick[Range[Length[i]], i]; nivennumber = Pick[Most[sel], i]; gap = sel[[...
Give a code snippet in #Mathematica.2FWolfram_Language Note:   Niven   numbers are also called   Harshad   numbers.   They are also called    multidigital   numbers. Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisib...
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...
#Oberon-2
Oberon-2
MODULE Ascii; IMPORT Out; VAR c: CHAR; d: INTEGER; BEGIN c := CHR(97); d := ORD("a"); Out.Int(d,3);Out.Ln; Out.Char(c);Out.Ln END Ascii.
Give a code snippet in #Oberon-2 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/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#UnixPipes
UnixPipes
echo 1 |tee last fib ; tail -f fib | while read x do cat last | tee -a fib | xargs -n 1 expr $x + |tee last done
Give a code snippet in #UnixPipes The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions...
christopher/rosetta-code
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#Sidef
Sidef
@(1..7)->combinations(3, {|*a| a.sum == 12 || next a.permutations {|*b| b[0].is_even || next say (%w(police fire sanitation) ~Z b -> join(" ")) } })
Give a code snippet in #Sidef There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (di...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#GAP
GAP
Median := function(v) local n, w; w := SortedList(v); n := Length(v); return (w[QuoInt(n + 1, 2)] + w[QuoInt(n, 2) + 1]) / 2; end;   a := [41, 56, 72, 17, 93, 44, 32]; b := [41, 72, 17, 93, 44, 32];   Median(a); # 44 Median(b); # 85/2
Give a code snippet in #GAP Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutation_test
Permutation test
Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n {\displaystyle n} treatment...
#Rust
Rust
  fn main() { let treatment = vec![85, 88, 75, 66, 25, 29, 83, 39, 97]; let control = vec![68, 41, 10, 49, 16, 65, 32, 92, 28, 98];   let mut data_set = control.clone(); data_set.extend_from_slice(&treatment);   let greater = combinations(treatment.iter().sum(), treatment.len() as i64, &data_set) as...
Give a code snippet in #Rust Permutation test You are encouraged to solve this task according to the task description, using any language you may know. A new medical treatment was tested on a population of n + m {\displaystyle n+m} volunteers, with each volunteer randomly assigned either to a group of n ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by...
#EDSAC_order_code
EDSAC order code
  [List of primes by trial division, for Rosetta Code website.] [EDSAC program, Initial Orders 2.] [Division is done implicitly by the use of wheels. One wheel for each possible prime divisor, up to an editable limit.]   T51K [G parameter: print subroutine, 54 locations.] P56F [must be ev...
Give a code snippet in #EDSAC_order_code Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested f...
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...
#Brainf.2A.2A.2A
Brainf***
>>>>>>>>>+>,----------[ READ CHARACTERS UNTIL \N AND >++++++++[<----->-]<++>>>>>>+>,----------] SUBTRACT ASCII 0 FROM EACH <-<<<<<<< GO TO LAST DIGIT [ WHILE THERE ARE DIGITS >>>>>>>>[-<<<<<<<+>>>>>>>]<<<<<<<<...
Give a code snippet in #Brainf.2A.2A.2A 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 th...
christopher/rosetta-code
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#PicoLisp
PicoLisp
(out "file.txt" # Write to "file.txt" (prinl "### This is before the text ###") (here "TEXT-END") (prinl "### This is after the text ###") ) "There must be some way out of here", said the joker to the thief "There's too much confusion, I can't get no relief" TEXT-END   (in "file.txt" (ec...
Give a code snippet in #PicoLisp A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) foll...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
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 ...
#Prolog
Prolog
main:- sort_oid_list(["1.3.6.1.4.1.11.2.17.19.3.4.0.10", "1.3.6.1.4.1.11.2.17.5.2.0.79", "1.3.6.1.4.1.11.2.17.19.3.4.0.4", "1.3.6.1.4.1.11150.3.4.0.1", "1.3.6.1.4.1.11.2.17.19.3.4.0.1", "1.3.6.1.4.1.11150.3.4.0"], Sorted_list), foreach(member(oid(_, Oid), Sorted_list), writeln(Oid)).   sort_...
Give a code snippet in #Prolog 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/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#Raku
Raku
sub is-number-w-ws( Str $term --> Bool ) { # treat Falsey strings as numeric $term.Numeric !~~ Failure; }   sub is-number-wo-ws( Str $term --> Bool ) { # treat Falsey strings as non-numeric ?($term ~~ / \S /) && $term.Numeric !~~ Failure; }   say " Coerce Don't coerce"; say ' String white...
Give a code snippet in #Raku Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Ar...
christopher/rosetta-code
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:...
#Octave
Octave
s = "The quick brown fox jumped over the lazy dog's back"; hash = md5sum(s, true); disp(hash)
Give a code snippet in #Octave Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic
Bitmap/Bézier curves/Cubic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve (definition on Wikipedia).
#Tcl
Tcl
package require Tcl 8.5 package require Tk   proc drawBezier {img colour args} { # ensure the points are increasing along the x-axis set points [lsort -real -index 0 $args]   set xmin [x [lindex $points 0]] set xmax [x [lindex $points end]] set prev [lindex $points 0] set increment 2 for {se...
Give a code snippet in #Tcl Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve (definition on Wikipedia).
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 |...
#Icon_and_Unicon
Icon and Unicon
procedure main(arglist) write("Usage: substring <string> <first position> <second position> <single character> <substring>") s := \arglist[1] | "aardvarks" n := \arglist[2] | 5 m := \arglist[3] | 4 c := \arglist[4] | "d" ss := \arglist[5] | "ard"   write( s[n+:m] ) write( s[n:0] ) ...
Give a code snippet in #Icon_and_Unicon 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 O...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#Yabasic
Yabasic
dim vect1(2) vect1(1) = 5 : vect1(2) = 7 dim vect2(2) vect2(1) = 2 : vect2(2) = 3 dim vect3(arraysize(vect1(),1))   for n = 1 to arraysize(vect1(),1) vect3(n) = vect1(n) + vect2(n) next n print "[", vect1(1), ", ", vect1(2), "] + [", vect2(1), ", ", vect2(2), "] = "; showarray(vect3)   for n = 1 to arraysize(vect1(...
Give a code snippet in #Yabasic Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value ...
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#Arturo
Arturo
print now
Give a code snippet in #Arturo Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Delphi
Delphi
System.Halt;
Give a code snippet in #Delphi Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizer...
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...
#SenseTalk
SenseTalk
  set dog to "Benjamin" set Dog to "Samba" set DOG to "Bernie"   put !"There is just one dog named [[dog]]."  
Give a code snippet in #SenseTalk 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Short-circuit_evaluation
Short-circuit evaluation
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resources without side effects, an...
#Sidef
Sidef
func a(bool) { print 'A'; return bool } func b(bool) { print 'B'; return bool }   # Test-driver func test() { for op in ['&&', '||'] { for x,y in [[1,1],[1,0],[0,1],[0,0]] { "a(%s) %s b(%s): ".printf(x, op, y) eval "a(Bool(x)) #{op} b(Bool(y))" print "\n" } } ...
Give a code snippet in #Sidef Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable res...
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth%27s_algorithm_S
Knuth's algorithm S
This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end. This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive sam...
#C.2B.2B
C++
#include <iostream> #include <functional> #include <vector> #include <cstdlib> #include <ctime>   template <typename T> std::function<std::vector<T>(T)> s_of_n_creator(int n) { std::vector<T> sample; int i = 0; return [=](T item) mutable { i++; if (i <= n) { sample.push_back(item); } else if (st...
Give a code snippet in #C.2B.2B This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end. This means that the equal probability sampling should be maintained for all successive items > n as they become available (altho...
christopher/rosetta-code
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the s...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 PRINT "Number classification sequence" 20 INPUT "Enter a number (0 to end): ";k: IF k>0 THEN GO SUB 2000: PRINT k;" ";s$: GO TO 20 40 STOP 1000 REM sumprop 1010 IF oldk=1 THEN LET newk=0: RETURN 1020 LET sum=1 1030 LET root=SQR oldk 1040 FOR i=2 TO root-0.1 1050 IF oldk/i=INT (oldk/i) THEN LET sum=sum+i+oldk/i 106...
Give a code snippet in #ZX_Spectrum_Basic An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several cla...
christopher/rosetta-code
http://rosettacode.org/wiki/Atomic_updates
Atomic updates
Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the t...
#Ring
Ring
  # Project : Atomic updates   bucket = list(10) f2 = 0 for i = 1 to 10 bucket[i] = floor(random(9)*10) next   a = display("display:") see nl a = flatten(a) see "" + a + nl a = display("flatten:") see nl a = transfer(3,5) see a + nl see "19 from 3 to 5: " a = display(a) see nl   func display(a) displ...
Give a code snippet in #Ring Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of all buc...
christopher/rosetta-code
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Rust
Rust
// 20210212 Rust programming solution   fn nthRoot(n: f64, A: f64) -> f64 {   let p = 1e-9_f64 ; let mut x0 = A / n ;   loop { let mut x1 = ( (n-1.0) * x0 + A / f64::powf(x0, n-1.0) ) / n; if (x1-x0).abs() < (x0*p).abs() { return x1 }; x0 = x1 } }   fn main() { println!("{}"...
Give a code snippet in #Rust Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
christopher/rosetta-code
http://rosettacode.org/wiki/Variable_size/Set
Variable size/Set
Task Demonstrate how to specify the minimum size of a variable or a data type.
#PL.2FI
PL/I
  declare i fixed binary (7), /* occupies 1 byte */ j fixed binary (15), /* occupies 2 bytes */ k fixed binary (31), /* occupies 4 bytes */ l fixed binary (63); /* occupies 8 bytes */   declare d fixed decimal (1), /* occupies 1 byte */ e fixed decimal (3), ...
Give a code snippet in #PL.2FI Task Demonstrate how to specify the minimum size of a variable or a data type.
christopher/rosetta-code
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the s...
#jq
jq
# "until" is available in more recent versions of jq # than jq 1.4 def until(cond; next): def _until: if cond then . else (next|_until) end; _until;   # unordered def proper_divisors: . as $n | if $n > 1 then 1, ( range(2; 1 + (sqrt|floor)) as $i | if ($n % $i) == 0 then $i, (($n /...
Give a code snippet in #jq An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications fo...
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) ...
#Red
Red
Red ["FizzBuzz"]   repeat i 100 [ print case [ i % 15 = 0 ["FizzBuzz"] i % 5 = 0 ["Buzz"] i % 3 = 0 ["Fizz"] true [i] ] ]
Give a code snippet in #Red 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/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also ...
#Swift
Swift
func isPrime(number: Int) -> Bool { if number < 2 { return false } if number % 2 == 0 { return number == 2 } if number % 3 == 0 { return number == 3 } if number % 5 == 0 { return number == 5 } var p = 7 let wheel = [4,2,4,2,4,6,2,6] while true ...
Give a code snippet in #Swift The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hund...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/String
Literals/String
Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Here document Other tasks r...
#F.23
F#
  let n= 'N' let i="Name=\"Nigel Galloway\"\n" let g= @"Name=""Nigel Galloway""\n" let e="Nigel Galloway" let l= """Name="Nigel Galloway"\n""" printfn "%c\n%s\n%s\n%s\n%s" n i g e l  
Give a code snippet in #F.23 Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. Par...
#Python
Python
# Casting out Nines # # Nigel Galloway: June 27th., 2012, # def CastOut(Base=10, Start=1, End=999999): ran = [y for y in range(Base-1) if y%(Base-1) == (y*y)%(Base-1)] x,y = divmod(Start, Base-1) while True: for n in ran: k = (Base-1)*x + n if k < Start: continue if k > End: ...
Give a code snippet in #Python Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or oth...
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Groovy
Groovy
[1,2,3,4].each { println it }
Give a code snippet in #Groovy Task Take a combined set of elements and apply a function to each element.
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 ...
#dc
dc
[*] sm
Give a code snippet in #dc 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/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...
#Eiffel
Eiffel
  class APPLICATION   create make   feature {NONE} -- Initialization   make local number_to_guess: INTEGER do number_to_guess := (create {RANDOMIZER}).random_integer_in_range (1 |..| 10) from print ("Please guess the number!%N") io.read_integer until io.last_integer = number_to_guess l...
Give a code snippet in #Eiffel 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/Bitwise_operations
Bitwise operations
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 |...
#Tailspin
Tailspin
  def a: [x f075 x]; def b: [x 81 x];   ($a and $b) -> '$a; and $b; is $;$#10;' -> !OUT::write ($a or $b) -> '$a; or $b; is $;$#10;' -> !OUT::write ($a xor $b) -> '$a; xor $b; is $;$#10;' -> !OUT::write $a::inverse -> 'not $a; is $;$#10;' -> !OUT::write $a::shift&{left: 3, fill: [x 00 x]} -> '$a; shifted left 3 bits is...
Give a code snippet in #Tailspin 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 Operatio...
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
#KSI
KSI
  `plain 'Hello world!' #echo #  
Give a code snippet in #KSI 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/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#TI-83_BASIC
TI-83 BASIC
rref([[1,2,-1,-4][2,3,-1,-11][-2,0,-3,22]])
Give a code snippet in #TI-83_BASIC Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is con...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associativ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
a1 = <|"name" -> "Rocket Skates", "price" -> 12.75, "color" -> "yellow"|>; a2 = <|"price" -> 15.25, "color" -> "red", "year" -> 1974|>; Merge[{a1, a2}, Last]
Give a code snippet in #Mathematica_.2F_Wolfram_Language Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" ...
christopher/rosetta-code
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point...
#Falcon
Falcon
  // Generate points in [min,max]^2 with constraint function random_point (min, max, constraint) [x, y] = [random(min, max), random(min, max)] return constraint(x, y) ? [x, y] : random_point(min, max, constraint) end   // Generate point list in_circle = { x, y => 10**2 <= x**2 + y**2 and x**2 + y**2 <= 15**2 } poin...
Give a code snippet in #Falcon Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" ci...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy,...
#ALGOL_68
ALGOL 68
MODE ISPRIMEINT = INT; PR READ "prelude/is_prime.a68" PR;   MODE POWMODSTRUCT = INT; PR READ "prelude/pow_mod.a68" PR;   PROC m factor = (INT p)INT:BEGIN INT m factor; INT max k, msb, n, q;   FOR i FROM bits width - 2 BY -1 TO 0 WHILE ( BIN p SHR i AND 2r1 ) = 2r0 DO msb := i OD;   max k := ENTIER sqrt(...
Give a code snippet in #ALGOL_68 A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor befor...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Vedit_macro_language
Vedit macro language
Ins_Text("ha", COUNT, 5)
Give a code snippet in #Vedit_macro_language Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repea...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#OxygenBasic
OxygenBasic
  'CREATE DYNAMIC ARRAY SPACES USING STRINGS   string sa=nuls 5* sizeof float string sb=sa   'MAP ARRAY VARIABLES ONTO STRINGS   float a at *sa float b at *sb   'ASSIGN SOME VALUES   a<=10,20,30,40,50 b<=60,70,80,90,00   'ADD ARRAY B TO A BY STRING CONCATENATION   sa+=sb   'TEST   print a[7] 'result 70  
Give a code snippet in #OxygenBasic Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1 ...
#QB64
QB64
  RANDOMIZE TIMER DIM SHARED cellsPerSide, legalMoves$, startB$, currentB$, targetB$, moveCount   restart DO displayStatus IF currentB$ = targetB$ THEN 'game done! PRINT " Congratulations, done in"; moveCount; " moves." PRINT "": PRINT " Press y for yes, if you want to start over > "; ye...
Give a code snippet in #QB64 The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move...
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to rais...
#Smalltalk
Smalltalk
  Exception subclass: #U0. Exception subclass: #U1.   Object subclass: Foo [   bazCount := 0.   foo [2 timesRepeat: [ "==>" [self bar] "<==" on: U0 do: [:sig | 'Call to bar was aborted by exception U0' printNl. ...
Give a code snippet in #Smalltalk Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   A...
christopher/rosetta-code
http://rosettacode.org/wiki/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in tur...
#C.23
C#
  using System;   namespace nimGame { class Program { static void Main(string[] args) { Console.WriteLine("There are twelve tokens.\n" + "You can take 1, 2, or 3 on your turn.\n" + "Whoever takes the last token wins.\n");   int toke...
Give a code snippet in #C.23 Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes  ...
christopher/rosetta-code
http://rosettacode.org/wiki/I_before_E_except_after_C
I before E except after C
The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually:   "I before E when not pre...
#Raku
Raku
grammar CollectWords { token TOP { [^^ <word> $$ \n?]+ }   token word { [ <with_c> | <no_c> | \N ]+ }   token with_c { c <ie_part> }   token no_c { <ie_part> }   token ie_part { ie | ei | eie # a couple words in the list have "eie" } }   cl...
Give a code snippet in #Raku The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually...
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to rais...
#Quackery
Quackery
[ this ] is U0   [ this ] is U1   [ 0 = iff U0 else U1 message put bail ] is baz ( n --> )   [ baz ] is bar ( n --> )   [ 2 times [ i^ 1 backup bar bailed if [ message share U0 oats iff [ say "Exception U0 raised." cr ...
Give a code snippet in #Quackery Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Ar...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Heapsort
Sorting algorithms/Heapsort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#MATLAB_.2F_Octave
MATLAB / Octave
function list = heapSort(list)   function list = siftDown(list,root,theEnd) while (root * 2) <= theEnd   child = root * 2; if (child + 1 <= theEnd) && (list(child) < list(child+1)) child = child + 1; end   if list(root) < list(child) ...
Give a code snippet in #MATLAB_.2F_Octave 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 sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_letter-first_letter
Last letter-first letter
A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the category, they fall out of the ga...
#zkl
zkl
pokemon:=("audino bagon baltoy banette bidoof braviary " "bronzor carracosta charmeleon cresselia croagunk darmanitan deino " ... "whismur wingull yamask").split();   tree:=pokemon.pump(Dictionary(),'wrap(name){ //--> Hash("aB":("Bc","Bd",,,) ) T( name, pokemon.filter('wrap(nm){ name[-1]==nm[0] }) ) });   ...
Give a code snippet in #zkl A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the cate...
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
#Sidef
Sidef
var keys = %w(a b c) var vals = [1, 2, 3]   var hash = Hash() hash{keys...} = vals... say hash
Give a code snippet in #Sidef 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/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long division is an algorithm for d...
#Perl
Perl
use strict; use List::Util qw(min);   sub poly_long_div { my ($rn, $rd) = @_;   my @n = @$rn; my $gd = scalar(@$rd); if ( scalar(@n) >= $gd ) { my @q = (); while ( scalar(@n) >= $gd ) { my $piv = $n[0]/$rd->[0]; push @q, $piv; $n[$_] -= $rd->[$_] * $piv foreach ( 0 .. min(scalar(@n), $g...
Give a code snippet in #Perl This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long ...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#EDSAC_order_code
EDSAC order code
  [Primes by Wilson's Theoem, for Rosetta Code.] [EDSAC program, Initial Orders 2.] T51K P64F [address for G parameter: low-level subroutines] T47K P130F [M parameter: main routine + high-level subroutine]   [======== M parameter: Main routine + high-level subroutine ============] E...
Give a code snippet in #EDSAC_order_code Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's...
christopher/rosetta-code
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can decid...
#Racket
Racket
#lang racket (require srfi/1)   (define current-samples (make-parameter 10000)) (define *prisoners* 100) (define *max-guesses* 50)   (define (evaluate-strategy instance-solved? strategy (s (current-samples))) (/ (for/sum ((_ s) #:when (instance-solved? strategy)) 1) s))   (define (build-drawers) (list->vector (shuf...
Give a code snippet in #Racket The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start ...
christopher/rosetta-code
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#Cowgol
Cowgol
include "cowgol.coh";   typedef Dpt is int(1, 7);   # print combination if valid sub print_comb(p: Dpt, s: Dpt, f: Dpt) is var out: uint8[] := {'*',' ','*',' ','*','\n',0}; out[0] := p + '0'; out[2] := s + '0'; out[4] := f + '0'; if p != s and p != f and f != s and p+s+f == 12 then print(&ou...
Give a code snippet in #Cowgol There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (d...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the vall...
#PL.2FI
PL/I
fill: procedure (x, y, fill_color) recursive; /* 12 May 2010 */ declare (x, y) fixed binary; declare fill_color bit (24) aligned;   if x <= lbound(image, 2) | x >= hbound(image, 2) then return; if y <= lbound(image, 1) | y >= hbound(image, 1) then return;   pixel_color = image (x,y); /* Obtain the color ...
Give a code snippet in #PL.2FI Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point toward...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_Brain****
Execute Brain****
Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions:...
#PicoLisp
PicoLisp
(off "Program")   (de compile (File) (let Stack NIL (setq "Program" (make (in File (while (char) (case @ (">" (link '(setq Data (or ...
Give a code snippet in #PicoLisp Execute Brain**** is an implementation of Brainf***. Other implementations of Brainf***. RCBF is a set of Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. An implementation need only properly imp...
christopher/rosetta-code
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the s...
#CLU
CLU
% This program uses the 'bigint' cluster from PCLU's 'misc.lib'   % Remove leading and trailing whitespace (bigint$unparse adds a lot) strip = proc (s: string) returns (string) ac = array[char] sc = sequence[char] cs: ac := string$s2ac(s) while ~ac$empty(cs) cand ac$bottom(cs)=' ' do ac$reml(cs) end ...
Give a code snippet in #CLU An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications f...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#11l
11l
V dict = [‘key1’ = 1, ‘key2’ = 2] V value2 = dict[‘key2’]
Give a code snippet in #11l 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, El...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable...
#11l
11l
F is_prime(n) L(x) (2, 3) I n % x == 0 R n == x Int64 d = 5 L d * d <= n L(x) (2, 4) I n % d == 0 R 0B d += x R 1B   Int64 i = 42 V n = 0 L n < 42 I is_prime(i) n++ print(‘n = #2 #16’.format(n, i)) i += i - 1 i++
Give a code snippet in #11l Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which: ...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Ring
Ring
  //this is a single line comment #this also a single line comment!  
Give a code snippet in #Ring Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#MUMPS
MUMPS
for read !,"Enter Y or N to continue: ",input quit:input?1(1"Y",1"y",1"N",1"n")
Give a code snippet in #MUMPS Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Forth
Forth
: hello ( -- c-addr u ) s" Hello" ;   hello 1 /string type \ => ello   hello 1- type \ => hell   hello 1 /string 1- type \ => ell
Give a code snippet in #Forth The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed I...
christopher/rosetta-code
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller prima...
#Liberty_BASIC
Liberty BASIC
  DIM mersenne(11) mersenne(1)=7 mersenne(2)=31 mersenne(3)=127 mersenne(4)=8191 mersenne(5)=131071 mersenne(6)=524287 mersenne(7)=2147483647 mersenne(8)=2305843009213693951 mersenne(9)=618970019642690137449562111 mersenne(10)=162259276829213363391578010288127 mersenne(11)=170141183460469231731687303715884105727     di...
Give a code snippet in #Liberty_BASIC This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rab...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#8th
8th
  \ print the array : .arr \ a -- a ( . space ) a:each ;   : pasc \ a -- \ print the row .arr cr dup \ create two rows from the first, one with a leading the other with a trailing 0 [0] 0 a:insert swap 0 a:push \ add the arrays together to make the new one ' n:+ a:op ;   \ print the first 16 rows: [1...
Give a code snippet in #8th Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#AutoHotkey
AutoHotkey
numbers = 5 4 1 2 3 sort, numbers, N D%A_Space% Msgbox % numbers
Give a code snippet in #AutoHotkey Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Qui...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#Ruby
Ruby
p [1,2,3].permutation.to_a
Give a code snippet in #Ruby Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   gener...
christopher/rosetta-code
http://rosettacode.org/wiki/Leonardo_numbers
Leonardo numbers
Leonardo numbers   are also known as the   Leonardo series. The   Leonardo numbers   are a sequence of numbers defined by: L(0) = 1 [1st equation] L(1) = 1 [2nd equation] L(n) = L(n-1) + L(n-2) + 1 ...
#XPL0
XPL0
int N, L, L0, L1, Add; [Text(0, "Enter L(0), L(1), Add: "); L0:= IntIn(0); L1:= IntIn(0); Add:= IntIn(0); IntOut(0, L0); ChOut(0, ^ ); IntOut(0, L1); ChOut(0, ^ ); for N:= 3 to 25 do [L:= L1 + L0 + Add; IntOut(0, L); ChOut(0, ^ ); L0:= L1; L1:= L; ]; ]
Give a code snippet in #XPL0 Leonardo numbers   are also known as the   Leonardo series. The   Leonardo numbers   are a sequence of numbers defined by: L(0) = 1 [1st equation] L(1) = 1 [2nd equation] L(n) = ...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#jq
jq
def transpose: if (.[0] | length) == 0 then [] else [map(.[0])] + (map(.[1:]) | transpose) end ;
Give a code snippet in #jq Transpose an arbitrarily sized rectangular Matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#Joy
Joy
DEFINE loop == [true []] dip while.   ["SPAM\n" putchars] loop.
Give a code snippet in #Joy Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#Gnuplot
Gnuplot
print strlen("hello") => 5
Give a code snippet in #Gnuplot Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme co...
christopher/rosetta-code
http://rosettacode.org/wiki/Y_combinator
Y combinator
In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's stat...
#Falcon
Falcon
  Y = { f => {x=> {n => f(x(x))(n)}} ({x=> {n => f(x(x))(n)}}) } facStep = { f => {x => x < 1 ? 1 : x*f(x-1) }} fibStep = { f => {x => x == 0 ? 0 : (x == 1 ? 1 : f(x-1) + f(x-2))}}   YFac = Y(facStep) YFib = Y(fibStep)   > "Factorial 10: ", YFac(10) > "Fibonacci 10: ", YFib(10)  
Give a code snippet in #Falcon In strict functional programming and the lambda calculus, functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a v...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#C.23
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.Serialization;   public static class MergeAndAggregateDatasets { public static void Main() { string patientsCsv = @" PATIENT_ID,LASTNAME 1001,Hopper 4004,Wirth 3003,Kemeny 2002,Gosling 500...
Give a code snippet in #C.23 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sleep
Sleep
Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread for the given amount of time. ...
#Raku
Raku
my $sec = prompt("Sleep for how many microfortnights? ") * 1.2096; say "Sleeping..."; sleep $sec; say "Awake!";
Give a code snippet in #Raku Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread ...
christopher/rosetta-code
http://rosettacode.org/wiki/SQL-based_authentication
SQL-based authentication
This task has three parts: Connect to a MySQL database (connect_db) Create user/password records in the following table (create_user) Authenticate login requests against the table (authenticate_user) This is the table definition: CREATE TABLE users ( userid INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(...
#C.23
C#
using System.Security.Cryptography; using System.Text;   namespace rosettaMySQL { class Hasher { private static string _BytesToHex(byte[] input) { var strBuilder = new StringBuilder(); foreach (byte _byte in input) { strBuilder.Append(_byte.ToS...
Give a code snippet in #C.23 This task has three parts: Connect to a MySQL database (connect_db) Create user/password records in the following table (create_user) Authenticate login requests against the table (authenticate_user) This is the table definition: CREATE TABLE users ( userid INT PRIMARY KEY AUTO_IN...
christopher/rosetta-code
http://rosettacode.org/wiki/Magnanimous_numbers
Magnanimous numbers
A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum. E.G. 6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime. 3538 is not a magnanimous numb...
#jq
jq
# To take advantage of gojq's arbitrary-precision integer arithmetic: def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);   def divrem($x; $y): [$x/$y|floor, $x % $y];  
Give a code snippet in #jq A magnanimous number is an integer where there is no place in the number where a + (plus sign) could be added between any two digits to give a non-prime sum. E.G. 6425 is a magnanimous number. 6 + 425 == 431 which is prime; 64 + 25 == 89 which is prime; 642 + 5 == 647 which is prime. 35...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Java
Java
if(problem){ System.exit(integerErrorCode); //conventionally, error code 0 is the code for "OK", // while anything else is an actual problem //optionally: Runtime.getRuntime().exit(integerErrorCode); }
Give a code snippet in #Java Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negat...
#APL
APL
spell←{⎕IO←0 small←'' 'one' 'two' 'three' 'four' 'five' 'six' 'seven' 'eight' small,←'nine' 'ten' 'eleven' 'twelve' 'thirteen' 'fourteen' small,←'fifteen' 'sixteen' 'seventeen' 'eighteen' 'nineteen' teens←'twenty' 'thirty' 'forty' 'fifty' 'sixty' 'seventy' teens,←'eighty' 'ninety' orders←'...
Give a code snippet in #APL Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positi...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Erlang
Erlang
lists:foldl(fun(X, Sum) -> X*X + Sum end, 0, [3,1,4,1,5,9]).
Give a code snippet in #Erlang Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
christopher/rosetta-code
http://rosettacode.org/wiki/Palindromic_gapful_numbers
Palindromic gapful numbers
Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   mea...
#Crystal
Crystal
def palindromesgapful(digit, pow) r1 = (10_u64**pow + 1) * digit r2 = 10_u64**pow * (digit + 1) nn = digit * 11 (r1...r2).select { |i| n = i.to_s; n == n.reverse && i.divisible_by?(nn) } end   def digitscount(digit, count) pow = 2 nums = [] of UInt64 while nums.size < count nums += palindromesgapful(...
Give a code snippet in #Crystal Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful ...
christopher/rosetta-code
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#ABAP
ABAP
  DATA: X1 TYPE F, Y1 TYPE F, X2 TYPE F, Y2 TYPE F, YD TYPE F, PI TYPE F, PI_180 TYPE F, MINUS_1 TYPE F VALUE '-1'.   PI = ACOS( MINUS_1 ). PI_180 = PI / 180.   LATITUDE1 = 36,12 . LONGITUDE1 = -86,67 . LATITUDE2 = 33,94 . LONGITUDE2 = -118,4 .   X1 = LATITUDE1 * PI_180. Y1 = ...
Give a code snippet in #ABAP This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equat...
christopher/rosetta-code
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of...
#Forth
Forth
  variable tab-end   : build ( m n -- ) pad tab-end ! swap >r 1 swap \ dividend on ret stack begin dup r@ <= while 2dup tab-end @ 2! [ 2 cells ] literal tab-end +! swap dup + swap dup + repeat 2drop rdrop ;   : e/mod ( m n -- q r ) over >r build 0 r> \ initial ...
Give a code snippet in #Forth Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, a...
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have download...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols binary   unixdict = 'unixdict.txt' do wmax = Integer.MIN_VALUE dwords = ArrayList() inrdr = BufferedReader(FileReader(File(unixdict))) loop label ln while inrdr.ready dword = Rexx(inrdr.readLine).strip if isOrdered(dword) then d...
Give a code snippet in #NetRexx An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file loca...
christopher/rosetta-code
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area
Shoelace formula for polygonal area
Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the absolute value) Task Write ...
#D
D
import std.stdio;   Point[] pnts = [{3,4}, {5,11}, {12,8}, {9,5}, {5,6}];   void main() { auto ans = shoelace(pnts); writeln(ans); }   struct Point { real x, y; }   real shoelace(Point[] pnts) { real leftSum = 0, rightSum = 0;   for (int i=0; i<pnts.length; ++i) { int j = (i+1) % pnts.length...
Give a code snippet in #D Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the ab...
christopher/rosetta-code
http://rosettacode.org/wiki/Sleep
Sleep
Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread for the given amount of time. ...
#Logtalk
Logtalk
  :- object(sleep).   :- public(how_long/1).   how_long(Seconds) :- write('Sleeping ...'), nl, thread_sleep(Seconds), write('... awake!'), nl.   :- end_object.  
Give a code snippet in #Logtalk Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thre...
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth%27s_power_tree
Knuth's power tree
(Knuth's power tree is used for computing   xn   efficiently.) Task Compute and show the list of Knuth's power tree integers necessary for the computation of:   xn   for any real   x   and any non-negative integer   n. Then, using those integers, calculate and show the exact values of (at least) the integer po...
#Java
Java
import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;   public class PowerTree { private static Map<Integer, Integer> p = new HashMap<>(); private static List<List<Integer>> lvl = new ArrayList<>();   static { p.put(1, 0);   ...
Give a code snippet in #Java (Knuth's power tree is used for computing   xn   efficiently.) Task Compute and show the list of Knuth's power tree integers necessary for the computation of:   xn   for any real   x   and any non-negative integer   n. Then, using those integers, calculate and show the exact value...
christopher/rosetta-code