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/EKG_sequence_convergence
EKG sequence convergence
The sequence is from the natural numbers and is defined by: a(1) = 1; a(2) = Start = 2; for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used. The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed)....
#Raku
Raku
sub infix:<shares-divisors-with> { ($^a gcd $^b) > 1 }   sub next-EKG ( *@s ) { return first { @s ∌ $_ and @s.tail shares-divisors-with $_ }, 2..*; }   sub EKG ( Int $start ) { 1, $start, &next-EKG … * }   sub converge-at ( @ints ) { my @ekgs = @ints.map: &EKG;   return (2 .. *).first: -> $i...
Give a code snippet in #Raku The sequence is from the natural numbers and is defined by: a(1) = 1; a(2) = Start = 2; for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used. The sequence is called the EKG sequence (after its visual similarity to an el...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Common_Lisp
Common Lisp
(defun gap-insertion-sort (array predicate gap) (let ((length (length array))) (if (< length 2) array (do ((i 1 (1+ i))) ((eql i length) array) (do ((x (aref array i)) (j i (- j gap))) ((or (< (- j gap) 0) (not (funcall predicate x (aref array (1- j))))) ...
Give a code snippet in #Common_Lisp Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Qu...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversa...
#Ada
Ada
  with Ada.Text_Io; use Ada.Text_Io; with Ada.Integer_Text_Io; use Ada.Integer_Text_Io; with Ada.Numerics.Discrete_Random;   procedure NumberReverse is   subtype RandRange is Integer range 1..9; type NumArrayType is array (Integer range 1..9) of Integer;   package RandNumbers is new Ada.Numerics.Discrete_Rando...
Give a code snippet in #Ada Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The scor...
christopher/rosetta-code
http://rosettacode.org/wiki/Curzon_numbers
Curzon numbers
A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1. Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1. Base here does not imply the radix of the counting sys...
#Sidef
Sidef
func is_curzon(n, k) { powmod(k, n, k*n + 1).is_congruent(-1, k*n + 1) && (n > 0) }   for k in (2 .. 10 `by` 2) { say "\nFirst 50 Curzon numbers using a base of #{k}:" say 50.by {|n| is_curzon(n, k) }.join(' ') say ("1000th term: ", 1000.th {|n| is_curzon(n,k) }) }
Give a code snippet in #Sidef A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1. Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1. Base here does not impl...
christopher/rosetta-code
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120....
#jq
jq
  def count(s): reduce s as $x (null; .+1);   def is_attractive: count(prime_factors) | is_prime;   def printattractive($m; $n): "The attractive numbers from \($m) to \($n) are:\n", [range($m; $n+1) | select(is_attractive)];   printattractive(1; 120)
Give a code snippet in #jq A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show...
christopher/rosetta-code
http://rosettacode.org/wiki/Introspection
Introspection
Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop). Extra credit Repor...
#PureBasic
PureBasic
CompilerIf #PB_Compiler_Version<441 CompilerError "You failed the version check!" CompilerEndIf   CompilerIf Defined(bloop,#PB_Variable) CompilerIf Defined(Abs(),#PB_Function) Abs(bloop) CompilerEndIf CompilerEndIf
Give a code snippet in #PureBasic Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#zkl
zkl
d:=Dictionary(); do{ d[(1).random(10)]=True }while(d.len()<4); abcd:=d.keys.shuffle(); while(1){ guess:=ask("4 digits: ")-" ,"; if(guess.len()!=4 or guess.unique().len()!=4) continue; bulls:=abcd.zipWith('==,guess).sum(0); cows:=guess.split("").enumerate() .reduce('wrap(s,[(n,c)]){ s + (d.find(c,False...
Give a code snippet in #zkl Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the gu...
christopher/rosetta-code
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/et...
#Haskell
Haskell
import Data.List (findIndex, find)   data City = City { name :: String , population :: Float } deriving (Read, Show)   -- CITY PROPERTIES ------------------------------------------------------------ cityName :: City -> String cityName (City x _) = x   cityPop :: City -> Float cityPop (City _ x) = x   mbCityName :...
Give a code snippet in #Haskell Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#OCaml
OCaml
# String.create 10 ;; - : string = "\000\023\000\000\001\000\000\000\000\000"
Give a code snippet in #OCaml Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings accor...
christopher/rosetta-code
http://rosettacode.org/wiki/Fork
Fork
Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
#HicEst
HicEst
SYSTEM( RUN )   WRITE(Messagebox='?Y', IOStat=ios) "Another Fork?" IF(ios == 2) ALARM(999) ! quit immediately   ! assume this script is stored as 'Fork.hic' SYSTEM(SHell='Fork.hic')   BEEP("c e g 'c") WRITE(Messagebox="!") "Waiting ..." ALARM(999) ! quit immediately
Give a code snippet in #HicEst Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
christopher/rosetta-code
http://rosettacode.org/wiki/Display_an_outline_as_a_nested_table
Display an outline as a nested table
Display an outline as a nested table. Parse the outline to a tree, count the leaves descending from each node, and write out a table with 'colspan' values measuring the indent of each line, translating the indentation to a nested structure, and padding the tree to even depth. defining the width of a ...
#Haskell
Haskell
{-# LANGUAGE TupleSections #-}   module OutlineTree where   import Data.Bifunctor (first) import Data.Bool (bool) import Data.Char (isSpace) import Data.List (find, intercalate) import Data.Tree (Tree (..), foldTree, levels)   ---------------- NESTED TABLES FROM OUTLINE --------------   wikiTablesFromOutline :: [String...
Give a code snippet in #Haskell Display an outline as a nested table. Parse the outline to a tree, count the leaves descending from each node, and write out a table with 'colspan' values measuring the indent of each line, translating the indentation to a nested structure, and padding the tree to even ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_word/fractal
Fibonacci word/fractal
The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is odd next n and iterate until e...
#Wren
Wren
import "graphics" for Canvas, Color import "dome" for Window   class FibonacciWordFractal { construct new(width, height, n) { Window.title = "Fibonacci Word Fractal" Window.resize(width, height) Canvas.resize(width, height) _fore = Color.green _wordFractal = wordFractal(n) ...
Give a code snippet in #Wren The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is ...
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.
#Java
Java
public static double nthroot(int n, double A) { return nthroot(n, A, .001); } public static double nthroot(int n, double A, double p) { if(A < 0) { System.err.println("A < 0");// we handle only real positive numbers return -1; } else if(A == 0) { return 0; } double x_prev = A; double x = A / n; // starting...
Give a code snippet in #Java 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/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...
#Pascal
Pascal
if true then begin halt end
Give a code snippet in #Pascal 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/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Rust
Rust
fn gnome_sort<T: PartialOrd>(a: &mut [T]) { let len = a.len(); let mut i: usize = 1; let mut j: usize = 2; while i < len { if a[i - 1] <= a[i] { // for descending sort, use >= for comparison i = j; j += 1; } else { a.swap(i - 1, i); ...
Give a code snippet in #Rust Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/String_matching
String matching
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 |...
#Delphi
Delphi
program CharacterMatching;   {$APPTYPE CONSOLE}   uses StrUtils;   begin WriteLn(AnsiStartsText('ab', 'abcd')); // True WriteLn(AnsiEndsText('zn', 'abcd')); // False WriteLn(AnsiContainsText('abcd', 'bb')); // False Writeln(AnsiContainsText('abcd', 'ab')); // True WriteLn(Pos('ab', 'abcd')); // 1 end.
Give a code snippet in #Delphi Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbe...
#Rust
Rust
#![feature(iterator_step_by)]   extern crate primal;   fn is_prime(n: u64) -> bool { if n == 2 || n == 3 || n == 5 || n == 7 || n == 11 || n == 13 { return true; } if n % 2 == 0 || n % 3 == 0 || n % 5 == 0 || n % 7 == 0 || n % 11 == 0 || n % 13 == 0 { return false; } let root = (n as f64).sqrt() as u64 + 1;...
Give a code snippet in #Rust An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   e...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle
Pascal's triangle/Puzzle
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the...
#PicoLisp
PicoLisp
(be number (@N @Max) (^ @C (box 0)) (repeat) (or ((^ @ (>= (val (-> @C)) (-> @Max))) T (fail)) ((^ @N (inc (-> @C)))) ) )   (be + (@A @B @Sum) (^ @ (-> @A)) (^ @ (-> @B)) (^ @Sum (+ (-> @A) (-> @B))) )   (be + (@A @B @Sum) (^ @ (-> @A)) (^ @ (-> @Sum)) (^ @B (- (-> @Sum) (-> @A)))...
Give a code snippet in #PicoLisp This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbe...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#DCL
DCL
$ i = 1024 $Loop: $ IF ( i .LE. 0 ) THEN GOTO LoopEnd $ WRITE sys$output F$FAO( " i = !4UL", i ) ! formatted ASCII output, fixed-width field $ ! Output alternatives: $ ! WRITE sys$output F$STRING( i )  ! explicit integer-to-string conversion $ ! WRITE sys$output i  ! implicit conversion ...
Give a code snippet in #DCL Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward ...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I befo...
#DataWeave
DataWeave
var arr = ["apple", "orange"] sizeOf(arr)  
Give a code snippet in #DataWeave Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter f...
christopher/rosetta-code
http://rosettacode.org/wiki/Currying
Currying
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Create a simple demonstrative example of Currying in a specific la...
#AppleScript
AppleScript
-- curry :: (Script|Handler) -> Script on curry(f) script on |λ|(a) script on |λ|(b) |λ|(a, b) of mReturn(f) end |λ| end script end |λ| end script end curry     -- TESTS --------------------------------------------------...
Give a code snippet in #AppleScript This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Create a simple demonstrative...
christopher/rosetta-code
http://rosettacode.org/wiki/Cistercian_numerals
Cistercian numerals
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyp...
#Ruby
Ruby
def initN n = Array.new(15){Array.new(11, ' ')} for i in 1..15 n[i - 1][5] = 'x' end return n end   def horiz(n, c1, c2, r) for c in c1..c2 n[r][c] = 'x' end end   def verti(n, r1, r2, c) for r in r1..r2 n[r][c] = 'x' end end   def diagd(n, c1, c2, r) for c in...
Give a code snippet in #Ruby Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself repre...
christopher/rosetta-code
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#Picat
Picat
import util.   go => L = [I.parse_term() : I in split(read_line())], S = [[I,cond(F<=400,F,'TOO LARGE')] : I in L.len..-1..1, F=f(L[I])], println(S), nl.   f(T) = sqrt(abs(T)) + 5*T**3.
Give a code snippet in #Picat The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s,...
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...
#Scratch
Scratch
$ include "seed7_05.s7i";   const type: cacheType is hash [integer] boolean; var cacheType: cache is cacheType.value;   const func boolean: happy (in var integer: number) is func result var boolean: isHappy is FALSE; local var bitset: cycle is bitset.value; var integer: newnumber is 0; var integer: ...
Give a code snippet in #Scratch 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 endlessl...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Euphoria
Euphoria
function shuffle(sequence s) object temp integer j for i = length(s) to 1 by -1 do j = rand(i) if i != j then temp = s[i] s[i] = s[j] s[j] = temp end if end for return s end function   function inOrder(sequence s) for i = 1 to length(s)...
Give a code snippet in #Euphoria 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/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a progr...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[FactorionQ] FactorionQ[n_,b_:10]:=Total[IntegerDigits[n,b]!]==n Select[Range[1500000],FactorionQ[#,9]&] Select[Range[1500000],FactorionQ[#,10]&] Select[Range[1500000],FactorionQ[#,11]&] Select[Range[1500000],FactorionQ[#,12]&]
Give a code snippet in #Mathematica_.2F_Wolfram_Language Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#MAXScript
MAXScript
for i = 0 to 10 by 2 do format "%\n" i
Give a code snippet in #MAXScript Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Batch_File
Batch File
::max.cmd @echo off setlocal enabledelayedexpansion set a=.%~1 if "%a%" equ "." set /p a="Input stream: " call :max res %a% echo %res% endlocal goto :eof   :max set %1=%2 :loop shift /2 if "%2" equ "" goto :eof if %2 gtr !%1! set res=%2 goto loop
Give a code snippet in #Batch_File Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Inform_7
Inform 7
"Mandelbrot"   The story headline is "A Non-Interactive Set".   Include Glimmr Drawing Commands by Erik Temple.   [Q20 fixed-point or floating-point: see definitions below] Use floating-point math.   Finished is a room.   The graphics-window is a graphics g-window spawned by the main-window. The position is g-placeabov...
Give a code snippet in #Inform_7 Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definitio...
#Racket
Racket
  #lang racket (define-struct dlist (head tail) #:mutable #:transparent) (define-struct dlink (content prev next) #:mutable #:transparent)   (define (insert-between dlist before after data)  ; Insert a fresh link containing DATA after existing link  ; BEFORE if not nil and before existing link AFTER if not nil (de...
Give a code snippet in #Racket Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data typ...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Julia
Julia
  print("String? ") y = readline() println("Your input was \"", y, "\".\n") print("Integer? ") y = readline() try y = parse(Int, y) println("Your input was \"", y, "\".\n") catch println("Sorry, but \"", y, "\" does not compute as an integer.") end  
Give a code snippet in #Julia User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. T...
#Ring
Ring
  # Project : Sequence of primorial primes   max = 9999 primes = [] for n = 1 to max if isprime(n) = 1 add(primes, n) ok next for n = 1 to len(primes) sum = 1 for m = 1 to n sum = sum * primes[m] next if (isprime(sum+1) or isprime(sum-1)) = 1 see "" + n + " " ...
Give a code snippet in #Ring The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off bei...
christopher/rosetta-code
http://rosettacode.org/wiki/Window_management
Window management
Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of interest may or may not have b...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
nb=NotebookCreate[]; (*Create a window and store in a variable*) nb===nb2 (*test for equality with another window object*) SetOptions[nb,Visible->False](*Hide*) SetOptions[nb,Visible->True](*Show*) NotebookClose[nb] (*Close*) SetOptions[nb,WindowMargins->{{x,Automatic},{y,Automatic}}](*Move to x,y screen position*) Set...
Give a code snippet in #Mathematica.2FWolfram_Language Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a...
christopher/rosetta-code
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#PL.2FI
PL/I
stat: procedure options (main); /* 21 May 2014 */   stats: procedure (values, mean, standard_deviation); declare (values(*), mean, standard_deviation) float; declare n fixed binary (31) initial ( (hbound(values,1)) );   mean = sum(values)/n;   standard_deviation = sqrt( sum(values - mean)**2 / n);   end st...
Give a code snippet in #PL.2FI Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#SequenceL
SequenceL
import <Utilities/Sequence.sl>;   main(args(2)) := Sequence::reverse(args[1]);
Give a code snippet in #SequenceL Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string E...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Generic
Generic
  generic coordinaat { ecs uuii   coordinaat() { ecs=+a uuii=+a}   coordinaat(ecs_set uuii_set) { ecs = ecs_set uuii=uuii_set }   operaator<(c) { iph ecs < c.ecs return troo iph c.ecs < ecs return phals iph uuii < c.uuii return troo return phals }   operaator==(connpair) // eecuuols and not eecuuols...
Give a code snippet in #Generic Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture
Euler's sum of powers conjecture
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power, except for the trivial case...
#Microsoft_Small_Basic
Microsoft Small Basic
' Euler sum of powers conjecture - 03/07/2015 'find: x1^5+x2^5+x3^5+x4^5=x5^5 '-> x1=27 x2=84 x3=110 x4=133 x5=144 maxn=250 For i=1 to maxn p5[i]=Math.Power(i,5) EndFor For x1=1 to maxn-4 For x2=x1+1 to maxn-3 'TextWindow.WriteLine("x1="+x1+", x2="+x2) For x3=x2+1 to maxn-2 'TextWin...
Give a code snippet in #Microsoft_Small_Basic There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to...
christopher/rosetta-code
http://rosettacode.org/wiki/Singleton
Singleton
A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
#OxygenBasic
OxygenBasic
  Class Singleton static sys inst 'private int instantiated() { return inst } void constructor(){ if not inst then inst=@this }   'all other methods start with @this=inst end class     'if not singleton.instantiated new Singleton MySingleton 'endif  
Give a code snippet in #OxygenBasic A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
christopher/rosetta-code
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#COBOL
COBOL
identification division. program-id. Query.   environment division. configuration section. special-names. call-convention 0 is extern.   repository. function all intrinsic.   data division. working-storage section. 01 query-result. ...
Give a code snippet in #COBOL This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Josephus_problem
Josephus problem
Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\displaystyle 0} , removing eve...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) m := integer(A[1]) | 41 c := integer(A[2]) | 3 write("With ",m," men, counting to ",c," last position is: ", j(m,c)) end   procedure j(m,c) return if m==1 then 0 else (j(m-1,c)+c)%m end
Give a code snippet in #Icon_and_Unicon Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner ...
christopher/rosetta-code
http://rosettacode.org/wiki/Truth_table
Truth table
A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function. Task Input a Boolean function from the user as a string then calculate and print a formatted truth table for the g...
#8080_Assembly
8080 Assembly
;;; CP/M truth table generator ;;; Supported operators: ;;; ~ (not), & (and), | (or), ^ (xor) and => (implies) ;;; Variables are A-Z, constants are 0 and 1. putch: equ 2 puts: equ 9 TVAR: equ 32 TCONST: equ 64 TOP: equ 96 TPAR: equ 128 TMASK: equ 31 TTYPE: equ 224 org 100h lxi h,80h ; Have we got a command line ...
Give a code snippet in #8080_Assembly A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function. Task Input a Boolean function from the user as a string then calculate and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#PL.2FI
PL/I
  /* Sierpinski carpet */   Sierpinski_carpet: procedure options (main); /* 28 January 2013 */   call carpet(3);   In_carpet: procedure (a, b) returns (bit(1)); declare (a, b) fixed binary nonassignable; declare (x, y) fixed binary; declare (true value ('1'b), false value ('0'b)) bit (1);   x = a ; y = b; ...
Give a code snippet in #PL.2FI Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # #...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_definition
Singly-linked list/Element definition
singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, Lis...
#BBC_BASIC
BBC BASIC
DIM node{pNext%, iData%}  
Give a code snippet in #BBC_BASIC singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body...
#Wren
Wren
for (i in 10..0) System.write("%(i) ") System.print()
Give a code snippet in #Wren Task Write a   for   loop which writes a countdown from   10   to   0. 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/Increme...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Argile
Argile
 
Give a code snippet in #Argile Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#REXX
REXX
/*REXX program displays an ASCII plot (character plot) of a Julia set. */ parse arg real imag fine . /*obtain optional arguments from the CL*/ if real=='' | real=="," then real= -0.8 /*Not specified? Then use the default.*/ if imag=='' | imag=="," then imag= 0.156 ...
Give a code snippet in #REXX Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#PL.2FI
PL/I
do i = 1 to 100; select; when (mod(i,15) = 0) put skip list ('FizzBuzz'); when (mod(i,3) = 0) put skip list ('Fizz'); when (mod(i,5) = 0) put skip list ('Buzz'); otherwise put skip list (i); end; end;
Give a code snippet in #PL.2FI Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuz...
christopher/rosetta-code
http://rosettacode.org/wiki/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.)
#Liberty_BASIC
Liberty BASIC
'This is a comment REM This is a comment   print "This has a comment on the end of the line." 'This is a comment print "This also has a comment on the end of the line." : REM This is a comment
Give a code snippet in #Liberty_BASIC 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/Fork
Fork
Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
#Perl
Perl
FORK: if ($pid = fork()) { # parent code } elsif (defined($pid)) { setsid; # tells apache to let go of this process and let it run solo # disconnect ourselves from input, output, and errors close(STDOUT); close(STDIN); close(STDERR); # re-open to /dev/null to prevent irrelevant warn mess...
Give a code snippet in #Perl Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Oforth
Oforth
import: date   : returnFourValues 12 13 14 15 ; : returnOneObject [ 12, 13, 14, 15, [16, 17 ], Date now, 1.2, "abcd" ] ;   "Showing four values returned on the parameter stack:" println returnFourValues .s clr   "\nShowing one object containing four values returned on the parameter stack:" println returnOneObject .s c...
Give a code snippet in #Oforth Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#Ada
Ada
with AWS.URL; with Ada.Text_IO; use Ada.Text_IO; procedure Encode is Normal : constant String := "http://foo bar/"; begin Put_Line (AWS.URL.Encode (Normal)); end Encode;
Give a code snippet in #Ada Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes in...
christopher/rosetta-code
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#Scala
Scala
import java.lang.Long.bitCount   object PopCount extends App { val nNumber = 30   def powersThree(start: Long): LazyList[Long] = start #:: powersThree(start * 3L)   println("Population count of 3ⁿ :") println(powersThree(1L).map(bitCount).take(nNumber).mkString(", "))   def series(start: Long): LazyList[Long]...
Give a code snippet in #Scala Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
(* String creation and destruction *) BinaryString = {}; BinaryString = . ; (* String assignment *) BinaryString1 = {12,56,82,65} , BinaryString2 = {83,12,56,65} -> {12,56,82,65} -> {83,12,56,65} (* String comparison *) BinaryString1 === BinaryString2 -> False (* String cloning and copying *) BinaryString3 = Bi...
Give a code snippet in #Mathematica_.2F_Wolfram_Language Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary byt...
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...
#Nemerle
Nemerle
def message = "How long am I anyways?"; def charlength = message.Length;
Give a code snippet in #Nemerle 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/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#BQN
BQN
A ← { A 0‿n: n+1; A m‿0: A (m-1)‿1; A m‿n: A (m-1)‿(A m‿(n-1)) }
Give a code snippet in #BQN The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#Logo
Logo
make "a mdarray [10 10]   for [j 1 10] [for [i 1 10] [mdsetitem list :i :j :a (1 + random 20)]]   to until.20 for [j 1 10] [ for [i 1 10] [ type mditem list :i :j :a type "| | if equal? 20 mditem list :i :j :a [stop] ] print "|| ] end until.20
Give a code snippet in #Logo Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met...
christopher/rosetta-code
http://rosettacode.org/wiki/Abelian_sandpile_model/Identity
Abelian sandpile model/Identity
Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that contain a number from 0 to 3 inclusive. (The numbers are said to represent grains of sand in each area of the sandpile). E.g. s1 = 1 2 0 2 1 1 0 1 3 and s2 = 2 1 3 1 0 1 0 1 0 Addition on sandpiles is done by a...
#Raku
Raku
class ASP { has $.h = 3; has $.w = 3; has @.pile = 0 xx $!w * $!h;   method topple { my $buf = $!w * $!h; my $done; repeat { $done = True; loop (my int $row; $row < $!h; $row = $row + 1) { my int $rs = $row * $!w; # row start ...
Give a code snippet in #Raku Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that contain a number from 0 to 3 inclusive. (The numbers are said to represent grains of sand in each area of the sandpile). E.g. s1 = 1 2 0 2 1 1 0 1 3 and s2 = 2 1 3 1 0 1 0 1 0 Addi...
christopher/rosetta-code
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file
Append a record to the end of a text file
Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most useful in the case of log files,...
#Common_Lisp
Common Lisp
(defvar *initial_data* (list (list "jsmith" "x" 1001 1000 (list "Joe Smith" "Room 1007" "(234)555-8917" "(234)555-0077" "jsmith@rosettacode.org") "/home/jsmith" "/bin/bash") (list "jdoe" "x" 1002 1000 (list "Jane Doe" "Room 1004" "(234)555-8914" "(234)555-0044" "jdoe@rosettacode.org") ...
Give a code snippet in #Common_Lisp Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" o...
#Sidef
Sidef
say (File.new(__FILE__).open_r.slurp == ARGF.slurp);
Give a code snippet in #Sidef Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints
Largest int from concatenated ints
Task Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests   and   show your program output here.   {1, 34, 3, 98, 9, 76, 45, 4}   {54,...
#Ceylon
Ceylon
shared void run() {   function comparator(Integer x, Integer y) { assert (is Integer xy = Integer.parse(x.string + y.string), is Integer yx = Integer.parse(y.string + x.string)); return yx <=> xy; }   function biggestConcatenation({Integer*} ints) => "".join(ints.sort(comparator));   value test1 = {1, 34, 3,...
Give a code snippet in #Ceylon Task Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests   and   show your program output here.   {1, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#R
R
> sprintf("%f", pi) [1] "3.141593" > sprintf("%.3f", pi) [1] "3.142" > sprintf("%1.0f", pi) [1] "3" > sprintf("%5.1f", pi) [1] " 3.1" > sprintf("%05.1f", pi) [1] "003.1" > sprintf("%+f", pi) [1] "+3.141593" > sprintf("% f", pi) [1] " 3.141593" > sprintf("%-10f", pi)# left justified [1] "3.141593 " > sprintf("%e", pi)...
Give a code snippet in #R Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#zkl
zkl
System.getenv("HOME") /home/craigd System.getenv() //--> Dictionary of all env vars
Give a code snippet in #zkl Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/State_name_puzzle
State name puzzle
Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the...
#zkl
zkl
#<<< // here doc states:=("Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware, Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana, Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana, Nebraska, Nevada, New Ha...
Give a code snippet in #zkl Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rear...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Clojure
Clojure
(defn qsort [L] (if (empty? L) '() (let [[pivot & L2] L] (lazy-cat (qsort (for [y L2 :when (< y pivot)] y)) (list pivot) (qsort (for [y L2 :when (>= y pivot)] y))))))
Give a code snippet in #Clojure 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/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#Aime
Aime
o_("-- ", sshell().plan("expr", "8", "*", "9").link.b_dump('\n'), " --\n");
Give a code snippet in #Aime Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant_odd_numbers
Abundant odd numbers
An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternately,   has the sigma sum of ...
#zkl
zkl
fcn oddAbundants(startAt=3){ //--> iterator Walker.zero().tweak(fcn(rn){ n:=rn.value; while(True){ sum:=0; foreach d in ([3.. n.toFloat().sqrt().toInt(), 2]){ if( (y:=n/d) *d != n) continue; sum += ((y==d) and y or y+d) } if(sum>n){ rn.set(n+2); return(n) } n+=2; } }.fp(Ref(...
Give a code snippet in #zkl An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alterna...
christopher/rosetta-code
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Slate
Slate
(File newNamed: 'input.txt') fileInfo fileSize. (File newNamed: '/input.txt') fileInfo fileSize.
Give a code snippet in #Slate Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
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...
#Python
Python
from fractions import Fraction from math import ceil   class Fr(Fraction): def __repr__(self): return '%s/%s' % (self.numerator, self.denominator)   def ef(fr): ans = [] if fr >= 1: if fr.denominator == 1: return [[int(fr)], Fr(0, 1)] intfr = int(fr) ans, fr = [[i...
Give a code snippet in #Python 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/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...
#AWK
AWK
  # syntax: GAWK -f GUESS_THE_NUMBER.AWK BEGIN { srand() n = int(rand() * 10) + 1 print("I am thinking of a number between 1 and 10. Try to guess it.") while (1) { getline ans if (ans !~ /^[0-9]+$/) { print("Your input was not a number. Try again.") continue } if ...
Give a code snippet in #AWK 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/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifi...
#D
D
import std.stdio, std.string, std.range;   ubyte[16] md4(const(ubyte)[] inData) pure nothrow { enum f = (uint x, uint y, uint z) => (x & y) | (~x & z); enum g = (uint x, uint y, uint z) => (x & y) | (x & z) | (y & z); enum h = (uint x, uint y, uint z) => x ^ y ^ z; enum r = (uint v, uint s) => (v << s) ...
Give a code snippet in #D Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete p...
christopher/rosetta-code
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You...
#Tcl
Tcl
package require Tcl 8.6   proc maxTrianglePathSum {definition} { # Parse the definition, stripping whitespace and leading zeroes. set lines [lmap line [split [string trim $definition] "\n"] { lmap val $line {scan $val %d} }] # Paths are bit strings (0 = go left, 1 = go right). # Enumerate the possi...
Give a code snippet in #Tcl Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such wa...
christopher/rosetta-code
http://rosettacode.org/wiki/Concurrent_computing
Concurrent computing
Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
#Forth
Forth
require tasker.fs require random.fs   : task ( str len -- ) 64 NewTask 2 swap pass ( str len -- ) 10 0 do 100 random ms pause 2dup cr type loop 2drop ;   : main s" Enjoy" task s" Rosetta" task s" Code" task begin pause single-tasking? until ; main
Give a code snippet in #Forth Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your l...
christopher/rosetta-code
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#REXX
REXX
/* REXX --------------------------------------------------------------- * Format seconds into a time string *--------------------------------------------------------------------*/ Call test 7259 ,'2 hr, 59 sec' Call test 86400 ,'1 d' Call test 6000000 ,'9 wk, 6 d, 10 hr, 40 min' Call test 123.50 ,'2 min, 3.5 sec'...
Give a code snippet in #REXX Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., ...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#jq
jq
def unoptimized_repeat(f; n): if n <= 0 then empty else f, repeat(f; n-1) end;
Give a code snippet in #jq Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Ruby
Ruby
> "a".ord => 97 > 97.chr => "a"
Give a code snippet in #Ruby 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). Conve...
christopher/rosetta-code
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a function to find the closest two p...
#Pascal
Pascal
program closestPoints; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} const PointCnt = 10000;//31623; type TdblPoint = Record ptX, ptY : double; end; tPtLst = array of TdblPoint;   tMinDIstIdx = record md1, md2 : NativeInt; ...
Give a code snippet in #Pascal This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a fu...
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#C
C
#include <stdio.h> #include <string.h> #include <openssl/sha.h>   int main (void) { const char *s = "Rosetta code"; unsigned char *d = SHA256(s, strlen(s), 0);   int i; for (i = 0; i < SHA256_DIGEST_LENGTH; i++) printf("%02x", d[i]); putchar('\n');   return 0; }
Give a code snippet in #C SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5c...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.41421356...
#Java
Java
import java.io.*;   public class FloatArray { public static void writeDat(String filename, double[] x, double[] y, int xprecision, int yprecision) throws IOException { assert x.length == y.length; PrintWriter out = new PrintWriter(filename); for (int i...
Give a code snippet in #Java Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3...
christopher/rosetta-code
http://rosettacode.org/wiki/Index_finite_lists_of_positive_integers
Index finite lists of positive integers
It is known that the set of finite lists of positive integers is   countable. This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers. Task Implement such a mapping:   write a function     rank     which assigns an integer to any finite, arbi...
#REXX
REXX
/*REXX program assigns an integer for a finite list of arbitrary non-negative integers. */ parse arg $ /*obtain optional argument (int list).*/ if $='' | $="," then $=3 14 159 265358979323846 /*Not specified? Then use the default.*/ ...
Give a code snippet in #REXX It is known that the set of finite lists of positive integers is   countable. This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers. Task Implement such a mapping:   write a function     rank     which assigns ...
christopher/rosetta-code
http://rosettacode.org/wiki/Synchronous_concurrency
Synchronous concurrency
The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th...
#Ada
Ada
package Synchronous_Concurrent is task Printer is entry Put(Item : in String); entry Get_Count(Count : out Natural); end Printer; end Synchronous_Concurrent;
Give a code snippet in #Ada The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
x = {1.47, 1.50 , 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83}; y = {52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46}; X = {x^0, x^1, x^2}; LeastSquares[Transpose@X, y]
Give a code snippet in #Mathematica.2FWolfram_Language Task Given a set of data vectors in the following format: y = { y 1 , y 2 , ...
christopher/rosetta-code
http://rosettacode.org/wiki/One_of_n_lines_in_a_file
One of n lines in a file
A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of the file if possible and m...
#Kotlin
Kotlin
// version 1.1.51   import java.util.Random   val r = Random()   fun oneOfN(n: Int): Int { var choice = 1 for (i in 2..n) { if (r.nextDouble() < 1.0 / i) choice = i } return choice }   fun main(args: Array<String>) { val n = 10 val freqs = IntArray(n) val reps = 1_000_000 repeat(...
Give a code snippet in #Kotlin A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second li...
christopher/rosetta-code
http://rosettacode.org/wiki/Yellowstone_sequence
Yellowstone sequence
The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a permutation of the natural n...
#D
D
import std.numeric; import std.range; import std.stdio;   class Yellowstone { private bool[int] sequence_; private int min_ = 1; private int n_ = 0; private int n1_ = 0; private int n2_ = 0;   public this() { popFront(); }   public bool empty() { return false; }   ...
Give a code snippet in #D The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a p...
christopher/rosetta-code
http://rosettacode.org/wiki/Stream_merge
Stream merge
2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was. N-strea...
#C.2B.2B
C++
//#include <functional> #include <iostream> #include <vector>   template <typename C, typename A> void merge2(const C& c1, const C& c2, const A& action) { auto i1 = std::cbegin(c1); auto i2 = std::cbegin(c2);   while (i1 != std::cend(c1) && i2 != std::cend(c2)) { if (*i1 <= *i2) { action...
Give a code snippet in #C.2B.2B 2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from whi...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Intercal
Intercal
PLEASE GIVE UP
Give a code snippet in #Intercal Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Optional_parameters
Optional parameters
Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicographic by default. column ...
#Lasso
Lasso
define sortarray( // params are set by position items::array, // required param ordering::string = 'lexicographic', // optional param column::integer = 1, reverse::boolean = false ) => { // sorting process local(sorteditems = array) // Lasso has no build in method to sort an array of arrays by position in the c...
Give a code snippet in #Lasso Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lex...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#EchoLisp
EchoLisp
  (lib 'matrix)   (define M (list->array (iota 6) 3 2)) (array-print M) 0 1 2 3 4 5 (array-print (matrix-transpose M)) 0 2 4 1 3 5  
Give a code snippet in #EchoLisp Transpose an arbitrarily sized rectangular Matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square r...
#Julia
Julia
  a = [25 15 5; 15 18 0; -5 0 11] b = [18 22 54 22; 22 70 86 62; 54 86 174 134; 42 62 134 106]   println(a, "\n => \n", chol(a, :L)) println(b, "\n => \n", chol(b, :L))  
Give a code snippet in #Julia Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interp...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#PHP
PHP
<?php   class Vector { private $values;   public function setValues(array $values) { if (count($values) != 3) throw new Exception('Values must contain exactly 3 values'); foreach ($values as $value) if (!is_int($value) && !is_float($value)) throw new Exception('Value "' . $value . '" has an invalid typ...
Give a code snippet in #PHP A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numb...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Gambas
Gambas
Public Sub Main() Dim sString As New String[10] 'Array for the input text Dim sLine As New String[] 'Array of each word in a line Dim siCount0, siCount1 As Short 'Counters Dim sOutput, sReverse, sTemp As String...
Give a code snippet in #Gambas Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spa...
christopher/rosetta-code
http://rosettacode.org/wiki/Minkowski_question-mark_function
Minkowski question-mark function
The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The decimal point takes the place o...
#Perl
Perl
use strict; use warnings; use feature 'say'; use POSIX qw(floor);   my $MAXITER = 50;   sub minkowski { my($x) = @_;   return floor($x) + minkowski( $x - floor($x) ) if $x > 1 || $x < 0 ;   my $y = my $p = floor($x); my ($q,$s,$d) = (1,1,1); my $r = $p + 1;   while () { last if ( $y + ($...
Give a code snippet in #Perl The Minkowski question-mark function converts the continued fraction representation [a0; a1, a2, a3, ...] of a number into a binary decimal representation in which the integer part a0 is unchanged and the a1, a2, ... become alternating runs of binary zeroes and ones of those lengths. The d...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#C.23
C#
using System; using System.Windows.Forms;   class Program { static void Main(string[] args) { Application.EnableVisualStyles(); //Optional. MessageBox.Show("Goodbye, World!"); } }
Give a code snippet in #C.23 Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Extensible_prime_generator
Extensible prime generator
Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In thi...
#Nim
Nim
import tables   type PrimeType = int   proc primesHashTable(): iterator(): PrimeType {.closure.} = iterator output(): PrimeType {.closure.} = # some initial values to avoid race and reduce initializations... yield 2.PrimeType; yield 3.PrimeType; yield 5.PrimeType; yield 7.PrimeType var h = initTable[Prime...
Give a code snippet in #Nim Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or progra...
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#jq
jq
def look_and_say: def head(c; n): if .[n:n+1] == c then head(c; n+1) else n end; tostring | if length == 0 then "" else head(.[0:1]; 1) as $len | .[0:$len] as $head | ($len | tostring) + $head[0:1] + (.[$len:] | look_and_say) end ;   # look and say n times def look_and_say(n): if n == 0 then...
Give a code snippet in #jq The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Crystal
Crystal
values.max
Give a code snippet in #Crystal Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#PowerShell
PowerShell
  Add-Type -Language CSharp -TypeDefinition @' public class MyClass { public MyClass() { } public void SomeMethod() { } private int _variable; public int Variable { get { return _variable; } set { _variable = value; } } public static void Main() { ...
Give a code snippet in #PowerShell In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of th...
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...
#Rust
Rust
/// # Panics /// /// If string is empty. fn first_char(string: &str) -> char { string.chars().next().unwrap() }   /// # Panics /// /// If string is empty. fn first_and_last_char(string: &str) -> (char, char) { ( first_char(string), first_char(string.rmatches(|_: char| true).next().unwrap()), ...
Give a code snippet in #Rust 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 cat...
christopher/rosetta-code
http://rosettacode.org/wiki/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#Draco
Draco
proc gcd(word m, n) word: word t; while n /= 0 do t := m; m := n; n := t % n od; m corp   proc lcm(word m, n) word: if m=0 or n=0 then 0 else m*n / gcd(m,n) fi corp   proc main() void: writeln(lcm(12, 18)) corp
Give a code snippet in #Draco Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Ela
Ela
reverse_string str = rev len str where len = length str rev 0 str = "" rev n str = toString (str : nn) +> rev nn str where nn = n - 1   reverse_string "Hello"
Give a code snippet in #Ela Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty s...
christopher/rosetta-code
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "...
#Icon_and_Unicon
Icon and Unicon
link printf   procedure main() every put(environment := [], hailenv(1 to 12,0)) # setup environments printf("Sequences:\n") while (e := !environment).sequence > 1 do { every hailstep(!environment) printf("\n") } printf("\nCounts:\n") every printf("%4d ",(!environment).count) prin...
Give a code snippet in #Icon_and_Unicon According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous ...
christopher/rosetta-code