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/Count_in_factors
Count in factors
Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would be shown as   2 × 3 {\di...
#Delphi
Delphi
function Factorize(n : Integer) : String; begin if n <= 1 then Exit('1'); var k := 2; while n >= k do begin while (n mod k) = 0 do begin Result += ' * '+IntToStr(k); n := n div k; end; Inc(k); end; Result:=SubStr(Result, 4); end;   var i : Integer; for i := 1 to ...
Give a code snippet in #Delphi Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it woul...
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#Sidef
Sidef
func double (n) { n << 1 } func halve (n) { n >> 1 } func isEven (n) { n&1 == 0 }   func ethiopian_mult(a, b) { var r = 0 while (a > 0) { r += b if !isEven(a) a = halve(a) b = double(b) } return r }   say ethiopian_mult(17, 34)
Give a code snippet in #Sidef Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and w...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#11l
11l
F mul_inv(=a, =b) V b0 = b V x0 = 0 V x1 = 1 I b == 1 {R 1}   L a > 1 V q = a I/ b (a, b) = (b, a % b) (x0, x1) = (x1 - q * x0, x0)   I x1 < 0 {x1 += b0} R x1   print(mul_inv(42, 2017))
Give a code snippet in #11l From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\di...
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...
#SNUSP
SNUSP
/@+@@@+++# 27 | halve odd /===count<<\ /recurse\ #/?\ zero $>@/===!/===-?\==>?!/-<+++\ \!/=!\@\>?!\@/<@\.!\-/ /+<-\!>\?-<+>/++++<\?>+++/*6+4 | | \=/ \=itoa=@@@+@+++++# \=>?/<=!=\ | |  ! /+ !/+ !/+ !/+ \ mod10 |//!==/========\ | /<+> -\!?-\!?-...
Give a code snippet in #SNUSP 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/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program dpixel.s */   /* compile with as */ /* link with gcc and options -lX11 -L/usr/lpp/X11/lib */   /********************************************/ /*Constantes */ /********************************************/ .equ STDOUT, ...
Give a code snippet in #ARM_Assembly Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
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...
#Nim
Nim
iterator lookAndSay(n: int): string = var current = "1" yield current for round in 2..n: var ch = current[0] var count = 1 var next = "" for i in 1..current.high: if current[i] == ch: inc count else: next.add $count & ch ch = current[i] count = 1 cur...
Give a code snippet in #Nim 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/Old_lady_swallowed_a_fly
Old lady swallowed a fly
Task Present a program which emits the lyrics to the song   I Knew an Old Lady Who Swallowed a Fly,   taking advantage of the repetitive structure of the song's lyrics. This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output. Other tasks related to st...
#Commodore_BASIC
Commodore BASIC
  1 rem rosetta code 2 rem old lady who swallowed a fly 5 print chr$(147);chr$(14) 10 dim a$(10),ex$(10),mu$(8,3):a=1 15 for i=1 to 8:read a$(i),ex$(i):next i 20 for c=1 to 8 30 print chr$(147):print " Old Lady Who Swallowed A Fly ":print 40 print "I know an old lady who swallowed" 45 print " a ";a$(c):g...
Give a code snippet in #Commodore_BASIC Task Present a program which emits the lyrics to the song   I Knew an Old Lady Who Swallowed a Fly,   taking advantage of the repetitive structure of the song's lyrics. This song has multiple versions with slightly different lyrics, so all these programs might not emit identi...
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...
#Delphi
Delphi
writeln(uppercase('alphaBETA')); writeln(lowercase('alphaBETA'));
Give a code snippet in #Delphi 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/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#Factor
Factor
: print-exists? ( path -- ) [ write ": " write ] [ exists? "exists." "doesn't exist." ? print ] bi ;   { "input.txt" "/input.txt" "docs" "/docs" } [ print-exists? ] each
Give a code snippet in #Factor Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works wi...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_clock
Draw a clock
Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy...
#Locomotive_Basic
Locomotive Basic
10 mode 1:defint a-y:deg 20 input "Current time (HH:MM)";t$ 30 h=val(mid$(t$,1,2)) 40 m=val(mid$(t$,4,2)) 50 cls 60 r=150:s=-1 70 ph=0:pm=0 80 origin 320,200 90 for a=0 to 360 step 6 100 if a mod 30>0 then z=.9 else z=.8 110 move z*r*sin(a),z*r*cos(a) 120 draw r*sin(a),r*cos(a) 130 next 140 move 0,r 150 for a=0 to 360 ...
Give a code snippet in #Locomotive_Basic Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly c...
christopher/rosetta-code
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#Python
Python
def stern_brocot(predicate=lambda series: len(series) < 20): """\ Generates members of the stern-brocot series, in order, returning them when the predicate becomes false   >>> print('The first 10 values:', stern_brocot(lambda series: len(series) < 10)[:10]) The first 10 values: [1, 1, 2, 1...
Give a code snippet in #Python For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered memb...
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...
#min
min
(true) ("SPAM" puts!) while
Give a code snippet in #min 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/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#Run_BASIC
Run BASIC
FOR i = 1 TO 15 PRINT i;" ";catalan(i) NEXT   FUNCTION catalan(n) catalan = 1 if n <> 0 then catalan = ((2 * ((2 * n) - 1)) / (n + 1)) * catalan(n - 1) END FUNCTION
Give a code snippet in #Run_BASIC Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n ! ...
christopher/rosetta-code
http://rosettacode.org/wiki/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ...
#Pascal
Pascal
#!/usr/bin/perl use strict; use warnings;   my $nzero = -0.0; my $nan = 0 + "nan"; my $pinf = +"inf"; my $ninf = -"inf";   printf "\$nzero = %.1f\n", $nzero; print "\$nan = $nan\n"; print "\$pinf = $pinf\n"; print "\$ninf = $ninf\n\n";   printf "atan2(0, 0) = %g\n", atan2(0, 0); printf "atan2(0, \$nzero) = %g\n", atan2...
Give a code snippet in #Pascal The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language...
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...
#Raven
Raven
time dup print "\n" print int '%a %b %e %H:%M:%S %Y' date
Give a code snippet in #Raven 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/Eertree
Eertree
An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the string "eertree", then outp...
#Go
Go
package main   import "fmt"   func main() { tree := eertree([]byte("eertree")) fmt.Println(subPalindromes(tree)) }   type edges map[byte]int   type node struct { length int edges suffix int }   const evenRoot = 0 const oddRoot = 1   func eertree(s []byte) []node { tree := []node{ evenRoo...
Give a code snippet in #Go An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the...
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.
#C.23
C#
int[] values = new int[] {1,2,3,4,5,6,7,8,9,10};   int max = values.Max();
Give a code snippet in #C.23 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/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, sho...
#Groovy
Groovy
def wordWrap(text, length = 80) { def sb = new StringBuilder() def line = ''   text.split(/\s/).each { word -> if (line.size() + word.size() > length) { sb.append(line.trim()).append('\n') line = '' } line += " $word" } sb.append(line.trim()).toString(...
Give a code snippet in #Groovy Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or pro...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Simple_moving_average
Averages/Simple moving average
Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an avera...
#Common_Lisp
Common Lisp
(defun simple-moving-average (period &aux (sum 0) (count 0) (values (make-list period)) (pointer values)) (setf (rest (last values)) values) ; construct circularity (lambda (n) (when (first pointer) (decf sum (first pointer))) ; subtract old value (incf sum n) ; add new v...
Give a code snippet in #Common_Lisp Computing the simple moving average of a series of numbers. Task[edit] Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving avera...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitcoin/public_point_to_address
Bitcoin/public point to address
Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion. The encoding steps are: take the X and Y coordinates of the given public point, and concatenate them in order to have a 64 byte-longed st...
#Wren
Wren
import "/crypto" for Sha256, Ripemd160 import "/str" for Str import "/fmt" for Conv   // converts an hexadecimal string to a byte list. var HexToBytes = Fn.new { |s| Str.chunks(s, 2).map { |c| Conv.atoi(c, 16) }.toList }   // Point is a class for a bitcoin public point class Point { construct new() { _x = L...
Give a code snippet in #Wren Bitcoin uses a specific encoding format to encode the digest of an elliptic curve public point into a short ASCII string. The purpose of this task is to perform such a conversion. The encoding steps are: take the X and Y coordinates of the given public point, and concatenate them in ord...
christopher/rosetta-code
http://rosettacode.org/wiki/Mind_boggling_card_trick
Mind boggling card trick
Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the trick in a way that mimics th...
#Rust
Rust
extern crate rand; // 0.5.5 use rand::Rng; use std::iter::repeat;   #[derive(Debug, Eq, PartialEq, Clone)] enum Colour { Black, Red, } use Colour::*;   fn main() { let mut rng = rand::thread_rng();   //Create our deck. let mut deck: Vec<_> = repeat(Black).take(26) .chain(repeat(Red).take(26)...
Give a code snippet in #Rust Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the...
christopher/rosetta-code
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers...
#zkl
zkl
fcn subleq(a,a1,a2,etc){ a=vm.arglist.copy(); i:=0; while(i>=0){ A,B,C:=a[i,3]; if(A==-1) a[B]=ask("::").toInt(); // or File.stdin.read(1)[0] // int else if(B==-1) print(a[A].toChar()); else if( (a[B]-=a[A]) <=0) { i=C; continue; } i+=3; } }
Give a code snippet in #zkl Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of sign...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Objective-C
Objective-C
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:13], @"hello", [NSNumber numberWithInt:31], @"world", [NSNumber numberWithInt:71], @"!", nil];   // iterating over keys: for (id key in myDict) { NSLog(@...
Give a code snippet in #Objective-C Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collection...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Tcl
Tcl
proc getNthLineFromFile {filename n} { set f [open $filename] while {[incr n -1] > 0} { if {[gets $f line] < 0} { close $f error "no such line" } } close $f return $line }   puts [getNthLineFromFile example.txt 7]
Give a code snippet in #Tcl Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in ...
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...
#Python
Python
  import sys with open(sys.argv[0]) as quine: code = raw_input("Enter source code: ") if code == quine.read(): print("Accept") else: print("Reject")  
Give a code snippet in #Python 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 p...
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...
#Python
Python
import pyprimes   def primorial_prime(_pmax=500): isprime = pyprimes.isprime n, primo = 0, 1 for prime in pyprimes.nprimes(_pmax): n, primo = n+1, primo * prime if isprime(primo-1) or isprime(primo+1): yield n   if __name__ == '__main__': # Turn off warning on use of probabil...
Give a code snippet in #Python 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 b...
christopher/rosetta-code
http://rosettacode.org/wiki/Interactive_programming_(repl)
Interactive programming (repl)
Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. Task Show how to start this...
#Kotlin
Kotlin
c:\kotlin-compiler-1.0.6>kotlinc Welcome to Kotlin version 1.0.6-release-127 (JRE 1.8.0_31-b13) Type :help for help, :quit for quit >>> fun f(s1: String, s2: String, sep: String) = s1 + sep + sep + s2 >>> f("Rosetta", "Code", ":") Rosetta::Code >>> :quit
Give a code snippet in #Kotlin Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell....
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Tcl
Tcl
if {$foo == 3} { puts "foo is three" } elseif {$foo == 4} { puts "foo is four" } else { puts "foo is neither three nor four" }
Give a code snippet in #Tcl Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common co...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of thi...
#Ksh
Ksh
  #!/bin/ksh   # Strip whitespace from a string/Top and tail   # # Variables: # str=${1:-" This is a test. "}   # # Functions: #   # # Function _striphead(str) - Return str with leading while space stripped # function _striphead { typeset _str ; _str="$1"   echo "${_str##*(\s)}" }     # # Function _striptail(str) -...
Give a code snippet in #Ksh Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace remo...
christopher/rosetta-code
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit ...
#ALGOL_68
ALGOL 68
[]INT sedol weights = (1, 3, 1, 7, 3, 9); STRING reject = "AEIOUaeiou";   PROC strcspn = (STRING s,reject)INT: ( INT out:=0; FOR i TO UPB s DO IF char in string(s[i], LOC INT, reject) THEN return out FI; out:=i OD; return out: out );   PROC sedol checksum = (REF STRING sedol6)INT: ( INT out;...
Give a code snippet in #ALGOL_68 Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#Swift
Swift
func perfect(n:Int) -> Bool { var sum = 0 for i in 1..<n { if n % i == 0 { sum += i } } return sum == n }   for i in 1..<10000 { if perfect(i) { println(i) } }
Give a code snippet in #Swift Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself...
christopher/rosetta-code
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#Bracmat
Bracmat
( 1000001:?i & whl ' ( !i+-2:>0:?i & !i:?L & whl'(!L^1/2:#?^1/2&@(!L:% ?L)) & !L:~ ) & out$("left:" !i) & 1000001:?i & whl ' ( !i+-2:>0:?i & !i:?R & whl'(!R^1/2:#?^1/2&@(!R:?R %@)) & !R:~ ) & out$("right:" !i) )
Give a code snippet in #Bracmat A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncat...
christopher/rosetta-code
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Haskell
Haskell
main = print $ "Incoming error--" ++ undefined -- When run in GHC: -- "Incoming error--*** Exception: Prelude.undefined
Give a code snippet in #Haskell
christopher/rosetta-code
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to chec...
#AWK
AWK
#!/usr/bin/awk -f BEGIN { allChars="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; print isPangram("The quick brown fox jumps over the lazy dog."); print isPangram("The quick brown fo."); }   function isPangram(string) { delete X; for (k=1; k<length(string); k++) { X[toupper(substr(string,k,1))]++; # histogram ...
Give a code snippet in #AWK Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/code_generator
Compiler/code generator
A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine code, that can be run by the Vi...
#Phix
Phix
-- -- demo\rosetta\Compiler\cgen.e -- ============================ -- -- The reusable part of cgen.exw -- without js -- (machine code!) include parse.e global sequence vars = {}, strings = {}, stringptrs = {} global integer chain = 0 global sequence code = {} function var_idx(sequenc...
Give a code snippet in #Phix A code generator translates the output of the syntax analyzer and/or semantic analyzer into lower level code, either assembly, object, or virtual. Task[edit] Take the output of the Syntax analyzer task - which is a flattened Abstract Syntax Tree (AST) - and convert it to virtual machine c...
christopher/rosetta-code
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Factor
Factor
: step-up ( -- ) step [ step-up step-up ] unless ;
Give a code snippet in #Factor From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function de...
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 ...
#Action.21
Action!
INCLUDE "H6:REALMATH.ACT"   DEFINE PTR="CARD"   PROC Sort(PTR ARRAY a INT count) INT i,j,minpos REAL POINTER tmp   FOR i=0 TO count-2 DO minpos=i FOR j=i+1 TO count-1 DO IF RealGreaterOrEqual(a(minpos),a(j)) THEN minpos=j FI OD   IF minpos#i THEN tmp=a(i) a(i)...
Give a code snippet in #Action.21 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 val...
christopher/rosetta-code
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth, ...
#Rust
Rust
  // This version is based on the Go version on Rosettacode   #[derive(PartialEq, Debug, Copy, Clone)] enum Month { May, June, July, August, }   #[derive(PartialEq, Debug, Copy, Clone)] struct Birthday { month: Month, day: u8, }   impl Birthday { fn month_unique_in(&self, birthdays: &[Birthd...
Give a code snippet in #Rust Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells A...
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#Nim
Nim
import ../compiler/[nimeval, llstream, ast], strformat, os   let std = findNimStdLibCompileTime() let modules = [std, std / "pure", std / "std", std / "core"] var intr = createInterpreter("script", modules)   #dynamic variable let varname = commandLineParams()[0] let expr = commandLineParams()[1]   #wrap the naked vari...
Give a code snippet in #Nim Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicabl...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_index
Inverted index
An Inverted Index is a data structure used to create full text search. Task Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms. The search index can be i...
#C.2B.2B
C++
  #include <algorithm> #include <fstream> #include <iostream> #include <vector> #include <string>   const std::string _CHARS = "abcdefghijklmnopqrstuvwxyz0123456789.:-_/"; const size_t MAX_NODES = 41;   class node { public: node() { clear(); } node( char z ) { clear(); } ~node() { for( int x = 0; x < MAX_NO...
Give a code snippet in #C.2B.2B An Inverted Index is a data structure used to create full text search. Task Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / ...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Java
Java
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
Give a code snippet in #Java The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#Rust
Rust
// [dependencies] // svg = "0.8.0"   const SQRT3_2: f64 = 0.86602540378444;   fn sierpinski_triangle( mut document: svg::Document, mut x: f64, mut y: f64, mut side: f64, order: usize, ) -> svg::Document { use svg::node::element::Polygon;   if order == 1 { let mut points = Vec::new();...
Give a code snippet in #Rust Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#Dragon
Dragon
val = 0 do{ val++ showln val }while(val % 6 != 0)
Give a code snippet in #Dragon Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/...
christopher/rosetta-code
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and...
#Elixir
Elixir
defmodule Test do def crc32(str) do IO.puts :erlang.crc32(str) |> Integer.to_string(16) end end   Test.crc32("The quick brown fox jumps over the lazy dog")
Give a code snippet in #Elixir Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets th...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/DOM_serialization
XML/DOM serialization
Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
#D
D
module xmltest ;   import std.stdio ; import std.xml ;   void main() { auto doc = new Document("root") ; //doc.prolog = q"/<?xml version="1.0"?>/" ; // default doc ~= new Element("element", "Some text here") ; writefln(doc) ; // output: <?xml version="1.0"?><root><element>Some text here</element></root> }
Give a code snippet in #D Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
christopher/rosetta-code
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a met...
#Julia
Julia
using Primes   function carmichael(pmax::Integer) if pmax ≤ 0 throw(DomainError("pmax must be strictly positive")) end car = Vector{typeof(pmax)}(0) for p in primes(pmax) for h₃ in 2:(p-1) m = (p - 1) * (h₃ + p) pmh = mod(-p ^ 2, h₃) for Δ in 1:(h₃+p-1) ...
Give a code snippet in #Julia A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to inves...
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...
#Java
Java
import java.util.Arrays; import java.util.List;   public class Cistercian { private static final int SIZE = 15; private final char[][] canvas = new char[SIZE][SIZE];   public Cistercian(int n) { initN(); draw(n); }   public void initN() { for (var row : canvas) { ...
Give a code snippet in #Java 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/Interactive_programming_(repl)
Interactive programming (repl)
Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. Task Show how to start this...
#Forth
Forth
$ gforth Gforth 0.7.0, Copyright (C) 1995-2008 Free Software Foundation, Inc. Gforth comes with ABSOLUTELY NO WARRANTY; for details type `license' Type `bye' to exit ok : f ( separator suffix prefix -- ) compiled pad place 2swap 2dup compiled pad +place compiled pad +place compiled pad +place c...
Give a code snippet in #Forth Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. ...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Golfscript
Golfscript
[296,{3/)}%-1%["No more"]+[" bottles":b]294*[b-1<]2*+[b]+[" of beer on the wall\n".8<"\nTake one down, pass it around\n"+1$n+]99*]zip
Give a code snippet in #Golfscript Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall...
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#Argile
Argile
use std, array   let A = accumulator 42 print(A 0) print(A 1) print(A 10) print(A 100)   let B = accumulator 4.2 print(B 0) print(B 1) print(B 10.0) print(B 100.4)   ~A ; ~B (: use dbg; check mem leak :)   (: accumulator call :) =: <accumulator a> <num x> := -> (a.t) call ((a.func) as function(any)(a.t)->(a.t)) with...
Give a code snippet in #Argile A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values pa...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Visual_Basic_.NET
Visual Basic .NET
Dim s As String = "123"   s = CStr(CInt("123") + 1) ' or s = (CInt("123") + 1).ToString
Give a code snippet in #Visual_Basic_.NET Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecib...
#zkl
zkl
fcn semiprime(n){ reg f = 0; p:=2; while(f < 2 and p*p <= n){ while(0 == n % p){ n /= p; f+=1; } p+=1; } return(f + (n > 1) == 2); }
Give a code snippet in #zkl Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chose...
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#PL.2FI
PL/I
  declare (L(30), R(30)) fixed binary; declare (i, s) fixed binary;   L, R = 0; put skip list ('Hello, please type two values and I will print their product:'); get list (L(1), R(1)); put edit ('The product of ', trim(L(1)), ' and ', trim(R(1)), ' is ') (a); do i = 1 by 1 while (L(i) ^= 0); ...
Give a code snippet in #PL.2FI Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Van_der_Corput_sequence
Van der Corput sequence
When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 {\displaystyle 2^{1}} ; and so o...
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   PROC Generate(INT value,base REAL POINTER res) REAL denom,rbase,r1,r2   IntToReal(0,res) IntToReal(1,denom) IntToReal(base,rbase) WHILE value#0 DO RealMult(denom,rbase,r1) RealAssign(r1,denom) IntToReal(value MOD base,r1) RealDiv(r1,denom,r2...
Give a code snippet in #Action.21 When counting integers in binary, if you put a (binary) point to the righEasyLangt of the count then the column immediately to the left denotes a digit with a multiplier of 2 0 {\displaystyle 2^{0}} ; the digit in the next column to the left has a multiplier of 2 1 ...
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 ...
#PowerShell
PowerShell
  function gnomesort($a) { $size, $i, $j = $a.Count, 1, 2 while($i -lt $size) { if ($a[$i-1] -le $a[$i]) { $i = $j $j++ } else { $a[$i-1], $a[$i] = $a[$i], $a[$i-1] $i-- if($i -eq 0) { $i = $j ...
Give a code snippet in #PowerShell 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/Stirling_numbers_of_the_second_kind
Stirling numbers of the second kind
Stirling numbers of the second kind, or Stirling partition numbers, are the number of ways to partition a set of n objects into k non-empty subsets. They are closely related to Bell numbers, and may be derived from them. Stirling numbers of the second kind obey the recurrence relation: S2(n, 0) and S2(0, k) = 0 ...
#Ruby
Ruby
@memo = {}   def sterling2(n, k) key = [n,k] return @memo[key] if @memo.key?(key) return 1 if n.zero? and k.zero? return 0 if n.zero? or k.zero? return 1 if n == k return 0 if k > n res = k * sterling2(n-1, k) + sterling2(n - 1, k-1) @memo[key] = res end   r = (0..12) puts "Sterling2 numbers:" puts "n/...
Give a code snippet in #Ruby Stirling numbers of the second kind, or Stirling partition numbers, are the number of ways to partition a set of n objects into k non-empty subsets. They are closely related to Bell numbers, and may be derived from them. Stirling numbers of the second kind obey the recurrence relation: ...
christopher/rosetta-code
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#ActionScript
ActionScript
var object:Object = new Object(); object.foo = "bar";
Give a code snippet in #ActionScript Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
beadsort[ a ] := Module[ { m, sorted, s ,t }, sorted = a; m = Max[a]; t=ConstantArray[0, {m,m} ]; If[ Min[a] < 0, Print["can't sort"]]; For[ i = 1, i < Length[a], i++, t[[i,1;;a[[i]]]]=1 ] For[ i = 1 ,i <= m, i++, s = Total[t[[;;,i]]]; t[[ ;; , i]] = 0; t[[1 ;; s , i]] = 1; ] For[ i=1,i<=Length[a],i++, sorted[[i]] ...
Give a code snippet in #Mathematica.2FWolfram_Language Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort |...
christopher/rosetta-code
http://rosettacode.org/wiki/Test_a_function
Test a function
Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
#C.2B.2B
C++
#include <algorithm> #include <string>   constexpr bool is_palindrome(std::string_view s) { return std::equal(s.begin(), s.begin()+s.length()/2, s.rbegin()); }  
Give a code snippet in #C.2B.2B Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
christopher/rosetta-code
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the...
#C
C
  #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gmp.h>   int main(void) { mpz_t n, d, e, pt, ct;   mpz_init(pt); mpz_init(ct); mpz_init_set_str(n, "9516311845790656153499716760847001433441357", 10); mpz_init_set_str(e, "65537", 10); mpz_init_set_str(d, "5617843187844953170...
Give a code snippet in #C Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Colorful_numbers
Colorful numbers
A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique. E.G. 24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840 Every product is unique. 2346 ...
#Raku
Raku
sub is-colorful (Int $n) { return True if 0 <= $n <= 9; return False if $n.contains(0) || $n.contains(1) || $n < 0; my @digits = $n.comb; my %sums = @digits.Bag; return False if %sums.values.max > 1; for 2..@digits -> $group { @digits.rotor($group => 1 - $group).map: { %sums{ [×] $_ }++ ...
Give a code snippet in #Raku A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique. E.G. 24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840 Eve...
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...
#COBOL
COBOL
identification division. program-id. hailstones. remarks. cobc -x hailstones.cob.   data division. working-storage section. 01 most constant as 1000000. 01 coverage constant as 100000. 01 stones usage binary-long. ...
Give a code snippet in #COBOL 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/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#APL
APL
toRoman←{ ⍝ Digits and corresponding values ds←((⊢≠⊃)⊆⊢)' M CM D CD C XC L XL X IX V IV I' vs←1000, ,100 10 1∘.×9 5 4 1 ⍝ Input ≤ 0 is invalid ⍵≤0:⎕SIGNAL 11 { 0=d←⊃⍸vs≤⍵:⍬ ⍝ Find highest digit in number (d⊃ds),∇⍵-d⊃vs ⍝ While one exists, add it and subtract from number }⍵ }
Give a code snippet in #APL Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   k_ = Rexx bigDigits = 999999999 -- Maximum setting for digits allowed by NetRexx numeric digits bigDigits   loop k_ = 1 say k_ end k_  
Give a code snippet in #NetRexx Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations ...
christopher/rosetta-code
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#6502_Assembly
6502 Assembly
LDA #3 JSR $FE95
Give a code snippet in #6502_Assembly The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
christopher/rosetta-code
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#PowerShell
PowerShell
<# .Synopsis ABC Problem .DESCRIPTION You are given a collection of ABC blocks. Just like the ones you had when you were a kid. There are twenty blocks with two letters on each block. You are guaranteed to have a complete alphabet amongst all sides of the blocks blocks = "BO","XK","DQ","CP","NA","GT","R...
Give a code snippet in #PowerShell ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete al...
christopher/rosetta-code
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#Raven
Raven
define doId use $x $x dup * $x /   define doPower use $v, $p $v $p pow   define doSort group 20000 each choose list sort reverse   define timeFunc use $fName time as $t1 $fName "" prefer call time as $t2 $fName $t2 $t1 -"%.4g secs for %s\n" print   "NULL" timeFunc 42 "doId" timeFunc 12 2 "...
Give a code snippet in #Raven Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/With_multiple_ranges
Loops/With multiple ranges
Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as integers. */ prod=...
#Red
Red
Red ["For loop with multiple ranges"]   ->: make op! function [start end][ res: copy [] repeat n 1 + absolute to-integer end - start [ append res start + either start > end [1 - n][n - 1] ] ] by: make op! function [s w] [extract s absolute w]   for: function ['word ranges body][ inp: copy [] ...
Give a code snippet in #Red Loops/With multiple ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages allow multiple loop ranges, such as the PL/I example (snippet) below. /* all variables are DECLARED as...
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 ...
#TI-83_BASIC
TI-83 BASIC
[[3,4][5,11][12,8][9,5][5,6]]->[A] Dim([A])->N:0->A For(I,1,N) I+1->J:If J>N:Then:1->J:End A+[A](I,1)*[A](J,2)-[A](J,1)*[A](I,2)->A End Abs(A)/2->A
Give a code snippet in #TI-83_BASIC 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 retu...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#FreeBASIC
FreeBASIC
' version 16-09-2015 ' compile with: fbc -s console ' OR compile with: fbc -s gui   ' Ported from the C version Sub Br_line(x0 As Integer, y0 As Integer, x1 As Integer, y1 As Integer, Col As Integer = &HFFFFFF)   Dim As Integer dx = Abs(x1 - x0), dy = Abs(y1 - y0) Dim As Integer sx = IIf(x0 < x1, 1, -1) Dim...
Give a code snippet in #FreeBASIC Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
christopher/rosetta-code
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#Euler_Math_Toolbox
Euler Math Toolbox
  >function try24 (v) ... $n=cols(v); $if n==1 and v[1]~=24 then $ "Solved the problem", $ return 1; $endif $loop 1 to n $ w=tail(v,2); $ loop 1 to n-1 $ h=w; a=v[1]; b=w[1]; $ w[1]=a+b; if try24(w); ""+a+"+"+b+"="+(a+b), return 1; endif; $ w[1]=a-b; if try24(w); ""+a+"-"+b+"="+(a-b), return 1; endif; $ ...
Give a code snippet in #Euler_Math_Toolbox task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
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 ...
#WDTE
WDTE
let a => import 'arrays'; a.sort [39; 47; 40; 53; 14; 23; 88; 52; 78; 62; 41; 92; 88; 66; 5; 40] < -- io.writeln io.stdout;
Give a code snippet in #WDTE 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/Color_quantization
Color quantization
full color Example: Gimp 16 color Color quantization is the process of reducing number of colors used in an image while trying to maintain the visual appearance of the original image. In general, it is a form of cluster analysis, if each RGB color value is considered as a coordinate triple in the 3D colorspace. There...
#Common_Lisp
Common Lisp
(defpackage #:quantize (:use #:cl #:opticl))   (in-package #:quantize)   (defun image->pixels (image) (check-type image 8-bit-rgb-image) (let (pixels) (do-pixels (y x) image (push (pixel* image y x) pixels)) pixels))   (defun greatest-color-range (pixels) (loop for (r g b) in pixels ...
Give a code snippet in #Common_Lisp full color Example: Gimp 16 color Color quantization is the process of reducing number of colors used in an image while trying to maintain the visual appearance of the original image. In general, it is a form of cluster analysis, if each RGB color value is considered as a coordina...
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 |...
#Frink
Frink
test = "🐱abcdefg😾" n = 3 m = 2 println[substrLen[test, n, m]] println[right[test, -m]] println[left[test, -1]] pos = indexOf["c"] if pos != -1 println[substrLen[test, pos, m]] pos = indexOf[test, "cd"] if pos != -1 println[substrLen[test, pos, m]]  
Give a code snippet in #Frink 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/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
#MiniScript
MiniScript
keys = ["foo", "bar", "val"] values = ["little", "miss", "muffet"]   d = {} for i in range(keys.len-1) d[keys[i]] = values[i] end for   print d
Give a code snippet in #MiniScript 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/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute z...
#zkl
zkl
K:=ask(0,"Kelvin: ").toFloat(); println("K %.2f".fmt(K)); println("F %.2f".fmt(K*1.8 - 459.67)); println("C %.2f".fmt(K - 273.15)); println("R %.2f".fmt(K*1.8));
Give a code snippet in #zkl There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 ke...
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...
#Sidef
Sidef
var words = [[]] var file = %f'unixdict.txt'   file.open_r(\var fh, \var err) -> || die "Can't open file #{file}: $#{err}"   fh.each { |line| line.trim! if (line == line.sort) { words[line.length] := [] << line } }   say words[-1].join(' ')
Give a code snippet in #Sidef 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 locall...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The ...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 PRINT "Use integer numbers and signs"'"+ - * / ( )"'' 20 LET s$="": REM last symbol 30 LET pc=0: REM parenthesis counter 40 LET i$="1+2*(3+(4*5+6*7*8)-9)/10" 50 PRINT "Input = ";i$ 60 FOR n=1 TO LEN i$ 70 LET c$=i$(n) 80 IF c$>="0" AND c$<="9" THEN GO SUB 170: GO TO 130 90 IF c$="+" OR c$="-" THEN GO SUB 200: GO TO ...
Give a code snippet in #ZX_Spectrum_Basic Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling ...
christopher/rosetta-code
http://rosettacode.org/wiki/Minesweeper_game
Minesweeper game
There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid...
#Ceylon
Ceylon
import ceylon.random {   DefaultRandom }   class Cell() {   shared variable Boolean covered = true; shared variable Boolean flagged = false; shared variable Boolean mined = false; shared variable Integer adjacentMines = 0;   string => if (covered && !flagged) then "." else if (covered && flagged) ...
Give a code snippet in #Ceylon There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coor...
christopher/rosetta-code
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations   func Kaprekar(N, B); \Returns 'true' if N is a Kaprekar number in base B int N, B; real N2, D; int Q, R; [N2:= sq(float(N)); \N squared D:= float(B); \(divider) loop [Q:= fix(N2/D - Mod(N2,1.)); \get left pa...
Give a code snippet in #XPL0 A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as ...
christopher/rosetta-code
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial ...
#CoffeeScript
CoffeeScript
pascal = () -> a = [] return () -> if a.length is 0 then a = [1] else b = (a[i] + a[i+1] for i in [0 ... a.length - 1]) a = [1].concat(b).concat [1]   show = (a) -> show_x = (e) -> switch e when 0 then "" when 1 then "x" els...
Give a code snippet in #CoffeeScript The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   a...
christopher/rosetta-code
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#Perl
Perl
use strict; use warnings; # Find a knight's tour   my @board;   # Choose starting position - may be passed in on command line; if # not, choose random square. my ($i, $j); if (my $sq = shift @ARGV) { die "$0: illegal start square '$sq'\n" unless ($i, $j) = from_algebraic($sq); } else { ($i, $j) = (int rand 8, int ...
Give a code snippet in #Perl Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; ...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
Rosetta Code/Rank languages by popularity
Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 2022 at 14:13 +02 Rank: 1 (1,...
#Haskell
Haskell
{-# LANGUAGE OverloadedStrings #-}   import Data.Aeson import Network.HTTP.Base (urlEncode) import Network.HTTP.Conduit (simpleHttp) import Data.List (sortBy, groupBy) import Data.Function (on) import Data.Map (Map, toList)   -- Record representing a single language. data Language = Language { name ...
Give a code snippet in #Haskell Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 jui...
christopher/rosetta-code
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#LFE
LFE
  $ ./bin/lfe -pa ebin/ -c "alpha beta" -h "gamma"  
Give a code snippet in #LFE Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
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...
#UnixPipes
UnixPipes
(echo 1024>p.res;tail -f p.res) | while read a ; do test $a -gt 0 && (expr $a / 2 >> p.res ; echo $a) || exit 0 done
Give a code snippet in #UnixPipes 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/Dow...
christopher/rosetta-code
http://rosettacode.org/wiki/Cramer%27s_rule
Cramer's rule
linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1...
#Groovy
Groovy
class CramersRule { static void main(String[] args) { Matrix mat = new Matrix(Arrays.asList(2d, -1d, 5d, 1d), Arrays.asList(3d, 2d, 2d, -6d), Arrays.asList(1d, 3d, 3d, -1d), Arrays.asList(5d, -2d, -3d, 3d)) List<Double> b = Arrays.asList(-3d, -32d, -47...
Give a code snippet in #Groovy linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+...
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 ...
#AppleScript
AppleScript
reverseString("Hello World!")   on reverseString(str) reverse of characters of str as string end reverseString
Give a code snippet in #AppleScript 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Delphi
Delphi
program Project2; {$APPTYPE CONSOLE} uses SysUtils;   function Recursive(Level : Integer) : Integer; begin try Level := Level + 1; Result := Recursive(Level); except on E: EStackOverflow do Result := Level; end; end;   begin Writeln('Recursion Level is ', Recursive(0)); Writeln('Press any ...
Give a code snippet in #Delphi Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <assert.h> #include <gsl/gsl_vector.h>   #define MAX(A,B) (((A)>(B))?(A):(B))   void reoshift(gsl_vector *v, int h) { if ( h > 0 ) { gsl_vector *temp = gsl_vector_alloc(v->size); gsl_vector_view p = gsl_vector_subvector(v, 0, v->size - h); ...
Give a code snippet in #C 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 div...
christopher/rosetta-code
http://rosettacode.org/wiki/Brilliant_numbers
Brilliant numbers
Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10. Brilliant numbers are useful in cryptography and when testing prime factoring algorithms. E.G. 3 × 3 (9) is a bri...
#Perl
Perl
use strict; use warnings; use feature 'say'; use List::AllUtils <max head firstidx uniqint>; use ntheory <primes is_semiprime forsetproduct>;   sub table { my $t = shift() * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr } sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ ...
Give a code snippet in #Perl Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10. Brilliant numbers are useful in cryptography and when testing prime factoring algorithm...
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 |...
#Picat
Picat
go => S = "Picat is fun", N = 3, M = 4, C = 'i', % must be a char SS = "is", test(S,N,M,C,SS).   test(S,N,M,C,SS) => println($test(S,N,M,C,SS)),    % - starting from n characters in and of m length; println(1=slice(S,N,N+M)), println(1=S[N..N+M]),    % - starting from n characters in, up to the en...
Give a code snippet in #Picat 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/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Red
Red
Red []   factors: function [n [integer!]] [ n: absolute n collect [ repeat i (sq: sqrt n) - 1 [ if n % i = 0 [ keep i keep n / i ] ] if sq = sq: to-integer sq [keep sq] ] ]   foreach num [ 24 -64  ; negative 64 ...
Give a code snippet in #Red 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 Co...
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...
#Elena
Elena
public program() { while (true) { console.writeLine:"spam" } }
Give a code snippet in #Elena 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   Loop...
christopher/rosetta-code
http://rosettacode.org/wiki/Pseudo-random_numbers/Splitmix64
Pseudo-random numbers/Splitmix64
Splitmix64 is the default pseudo-random number generator algorithm in Java and is included / available in many other languages. It uses a fairly simple algorithm that, though it is considered to be poor for cryptographic purposes, is very fast to calculate, and is "good enough" for many random number needs. It passes s...
#Perl
Perl
use strict; use warnings; no warnings 'portable'; use feature 'say'; use Math::AnyNum qw(:overload);   package splitmix64 {   sub new { my ($class, %opt) = @_; bless {state => $opt{seed}}, $class; }   sub next_int { my ($self) = @_; my $next = $self->{state} = ($self->{state}...
Give a code snippet in #Perl Splitmix64 is the default pseudo-random number generator algorithm in Java and is included / available in many other languages. It uses a fairly simple algorithm that, though it is considered to be poor for cryptographic purposes, is very fast to calculate, and is "good enough" for many ra...
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...
#REALbasic
REALbasic
Function Repeat(s As String, count As Integer) As String Dim output As String For i As Integer = 0 To count output = output + s Next Return output End Function  
Give a code snippet in #REALbasic 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("*",...
christopher/rosetta-code
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#zkl
zkl
continue; continue(n); // continue nth nested loop break; break(n); // break out of nth nested loop try{ ... }catch(exception){ ... } [else{ ... }] onExit(fcn); // run fcn when enclosing function exits
Give a code snippet in #zkl Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. ...
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
#Quackery
Quackery
say " ________ ___ ___ ________ ________ ___ __ _______ ________ ___ ___" cr say "|\ __ \|\ \|\ \|\ __ \|\ ____\|\ \|\ \ |\ ___ \ |\ __ \|\ \ / /|" cr say "\ \ \|\ \ \ \ \ \ \ \|\ \ \ \___|\ \ \/ /|\ \ __/|\ \ \|\ \ \ \/ / /" cr say " \ \ \ \ \ \ \ \ \ \ __ \ \ \...
Give a code snippet in #Quackery 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/Gauss-Jordan_matrix_inversion
Gauss-Jordan matrix inversion
Task Invert matrix   A   using Gauss-Jordan method. A   being an   n × n   matrix.
#Fortran
Fortran
!----------------------------------------------------------------------- ! gjinv - Invert a matrix, Gauss-Jordan algorithm ! A is destroyed. ! !___Name_______Type_______________In/Out____Description_________________ ! A(LDA,N) Real In An N by N matrix ! LDA Integer In ...
Give a code snippet in #Fortran Task Invert matrix   A   using Gauss-Jordan method. A   being an   n × n   matrix.
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...
#Erlang
Erlang
  -module(cei). -export([plaus/0,count/3]).   plaus() -> {ok,Words} = file:read_file("unixdict.txt"), ...
Give a code snippet in #Erlang 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 individual...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#Java
Java
import java.io.*;   public class Test {   public static void main(String[] args) throws IOException { try (BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"))) { bw.write("abc"); } } }
Give a code snippet in #Java Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
christopher/rosetta-code