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/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score...
#Ring
Ring
  min = 1 max = 100 see "think of a number between " + min + " and " + max + nl see "i will try to guess your number." + nl while true guess =floor((min + max) / 2) see "my guess is " + guess + nl see "is it higher than, lower than or equal to your number " give answer ans = left(answer,1) ...
Give a code snippet in #Ring Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The c...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#Lang5
Lang5
read read + .   read " " split expand drop + .
Give a code snippet in #Lang5 A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separate...
christopher/rosetta-code
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations def Pi = 3.14159265358979323846;   func real ATan(Y); \Arc tangent real Y; return ATan2(Y, 1.0);   func real Deg(X); \Convert radians to degrees real X; return 57.2957795130823 * X;   func real Rad(X); \Convert degrees to radians real X; return...
Give a code snippet in #XPL0 Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evalua...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#68000_Assembly
68000 Assembly
Factorial: ;input: D0.W: number you wish to get the factorial of. ;output: D0.L CMP.W #0,D0 BEQ .isZero CMP.W #1,D0 BEQ .isOne MOVEM.L D4-D5,-(SP) MOVE.W D0,D4 MOVE.W D0,D5 SUBQ.W #2,D5 ;D2 = LOOP COUNTER. ;Since DBRA stops at FFFF we can't use it as our multiplier. ;If we did, we'd always return 0! .lo...
Give a code snippet in #68000_Assembly Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factori...
christopher/rosetta-code
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#Ruby
Ruby
class Integer   def munchausen? self.digits.map{|d| d**d}.sum == self end   end   puts (1..5000).select(&:munchausen?)
Give a code snippet in #Ruby A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see ...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Julia
Julia
julia> "My String"[2:end] # without first character "y String"   julia> "My String"[1:end-1] # without last character "My Strin"   julia> "My String"[2:end-1] # without first and last characters "y Strin"
Give a code snippet in #Julia The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed I...
christopher/rosetta-code
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if ...
#Clojure
Clojure
(defn initial-mtx [i1 i2 value] (vec (repeat i1 (vec (repeat i2 value)))))   (defn operation [f mtx1 mtx2] (if (vector? mtx1) (vec (map #(vec (map f %1 %2)) mtx1 mtx2))) (recur f (initial-mtx (count mtx2) (count (first mtx2)) mtx1) mtx2) ))
Give a code snippet in #Clojure This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exp...
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#BQN
BQN
B10 ← 10{⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)} IsNarc ← {𝕩=+´⋆⟜≠B10 𝕩}   /IsNarc¨ ↕1e7
Give a code snippet in #BQN A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m} ...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Ursala
Ursala
  #import std #import nat   table "n" =   ~&plrTS( ~&xS pad` @xS <'x ','--'>-- --' | '*hS %nP* nrange/1 "n", ^CthPiC(`-!*h,~&) mat` *xSSK7 pad` *K7ihxPBSS (~&i&& %nP)** nleq&&product**iiK0lK2x nrange/1 "n")   #show+   main = table 12  
Give a code snippet in #Ursala Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
christopher/rosetta-code
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#Fortran
Fortran
PROGRAM SPIRAL   IMPLICIT NONE   INTEGER, PARAMETER :: size = 5 INTEGER :: i, x = 0, y = 1, count = size, n = 0 INTEGER :: array(size,size)   DO i = 1, count x = x + 1 array(x,y) = n n = n + 1 END DO   DO count = count - 1 DO i = 1, count y = y + 1 array(x,y) = n ...
Give a code snippet in #Fortran Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/lexical_analyzer
Compiler/lexical analyzer
Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is als...
#kotlin
kotlin
// Input: command line argument of file to process or console input. A two or // three character console input of digits followed by a new line will be // checked for an integer between zero and twenty-five to select a fixed test // case to run. Any other console input will be parsed.   // Code based on the Java versio...
Give a code snippet in #kotlin Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or ...
christopher/rosetta-code
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#ML
ML
  val test_array = ["123","12345","1234567","987654321","10001","~10001","~123","~100","100","~12345","1","2","~1","~10","2002","~2002","0"];   fun even (x rem 2 = 0) = true | _ = false;   fun middleThreeDigits (h :: t, s, 1 ) = s @ " --> too small" | (h :: t, s, 2 ) = s @ " --> has even digits" | (h :: t, s...
Give a code snippet in #ML Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be teste...
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#11l
11l
F multifact(n, d) R product((n .< 1).step(-d))   L(d) 1..5 print(‘Degree ’d‘: ’(1..10).map(n -> multifact(n, @d)))
Give a code snippet in #11l The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#Wart
Wart
def (ackermann m n) (if m=0 n+1 n=0 (ackermann m-1 1)  :else (ackermann m-1 (ackermann m n-1)))
Give a code snippet in #Wart The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { ...
christopher/rosetta-code
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#Python
Python
import copy   class T: def classname(self): return self.__class__.__name__   def __init__(self): self.myValue = "I'm a T."   def speak(self): print self.classname(), 'Hello', self.myValue   def clone(self): return copy.copy(self)   class S1(T): def speak(self): print self.c...
Give a code snippet in #Python An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x wer...
christopher/rosetta-code
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#PowerShell
PowerShell
  function horner($coefficients, $x) { $accumulator = 0 foreach($i in ($coefficients.Count-1)..0){ $accumulator = ( $accumulator * $x ) + $coefficients[$i] } $accumulator } $coefficients = @(-19, 7, -4, 6) $x = 3 horner $coefficients $x  
Give a code snippet in #PowerShell A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#Fantom
Fantom
class DotProduct { static Int dotProduct (Int[] a, Int[] b) { Int result := 0 [a.size,b.size].min.times |i| { result += a[i] * b[i] } return result }   public static Void main () { Int[] x := [1,2,3,4] Int[] y := [2,3,4]   echo ("Dot product of $x and $y is ${dotProduct(x...
Give a code snippet in #Fantom Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#Stata
Stata
display "Number of rows?" _request(nr) display "Number of columns?" _request(nc) matrix define a=J($nr,$nc,0) matrix a[1,2]=1.5 matrix list a matrix drop a
Give a code snippet in #Stata Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numb...
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#JavaScript
JavaScript
  function crt(num, rem) { let sum = 0; const prod = num.reduce((a, c) => a * c, 1);   for (let i = 0; i < num.length; i++) { const [ni, ri] = [num[i], rem[i]]; const p = Math.floor(prod / ni); sum += ri * p * mulInv(p, ni); } return sum % prod; }   function mulInv(a, b) { const b0 = b; let [x...
Give a code snippet in #JavaScript Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\dis...
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 ...
#ActionScript
ActionScript
function gnomeSort(array:Array) { var pos:uint = 0; while(pos < array.length) { if(pos == 0 || array[pos] >= array[pos-1]) pos++; else { var tmp = array[pos]; array[pos] = array[pos-1]; array[pos-1] = tmp; pos--; } } return array; }
Give a code snippet in #ActionScript Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Q...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the...
#AutoHotkey
AutoHotkey
; Example: Calls the Windows API function "MessageBox" and report which button the user presses.   WhichButton := DllCall("MessageBox", "int", "0", "str", "Press Yes or No", "str", "Title of box", "int", 4) MsgBox You pressed button #%WhichButton%.
Give a code snippet in #AutoHotkey Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content...
christopher/rosetta-code
http://rosettacode.org/wiki/String_prepend
String prepend
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 |...
#jq
jq
"world!" as $s | "Hello " + $s
Give a code snippet in #jq 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 Con...
christopher/rosetta-code
http://rosettacode.org/wiki/Plasma_effect
Plasma effect
The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid. Task Create a plasma effect. See also Computer Graphics Tutorial (lod...
#Sidef
Sidef
require('Imager')   class Plasma(width=400, height=400) {   has img = nil   method init { img = %O|Imager|.new(xsize => width, ysize => height) }   method generate { for y=(^height), x=(^width) { var hue = (4 + sin(x/19) + sin(y/9) + sin((x+y)/25) + sin(hypot(x, y)/8)) ...
Give a code snippet in #Sidef The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid. Task Create a plasma effect. See also ...
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...
#Ring
Ring
  load "stdlib.ring"     cStr = read("unixdict.txt") wordList = str2list(cStr) sum = 0 sortList = []   see "working..." + nl + nl   for n = 1 to len(wordList) num = 0 len = len(wordList[n])-1 for m = 1 to len asc1 = ascii(wordList[n][m]) asc2 = ascii(wordList[n][m+1]) if asc1 <= as...
Give a code snippet in #Ring 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The follow...
#Forth
Forth
: >gray ( n -- n' ) dup 2/ xor ; \ n' = n xor (n logically right shifted 1 time) \ 2/ is Forth divide by 2, ie: shift right 1 : gray> ( n -- n ) 0 1 31 lshift ( -- g b mask ) begin >r ...
Give a code snippet in #Forth Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ternary_logic
Ternary logic
This page uses content from Wikipedia. The original article was at Ternary logic. 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 logic, a three-valued logic (also trivalent, ternary, or trinary...
#Groovy
Groovy
enum Trit { TRUE, MAYBE, FALSE   private Trit nand(Trit that) { switch ([this,that]) { case { FALSE in it }: return TRUE case { MAYBE in it }: return MAYBE default  : return FALSE } } private Trit nor(Trit that) { this.or(that).not() }   ...
Give a code snippet in #Groovy This page uses content from Wikipedia. The original article was at Ternary logic. 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 logic, a three-valued logic (als...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Ruby
Ruby
class RGBColour def values [@red, @green, @blue] end end   class Pixmap def save(filename) File.open(filename, 'w') do |f| f.puts "P6", "#{@width} #{@height}", "255" f.binmode @height.times do |y| @width.times do |x| f.print @data[x][y].values.pack('C3') end ...
Give a code snippet in #Ruby Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
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
#Sidef
Sidef
var text = <<'EOT';   *** * * * ** * * * * * * *** ** *** * **** * * * * * * * ***** * * * * * * * * * * * * * *** * **** *** * EOT   func banner3D(text, shift=-1) { var txt = text.lines.map{|line| line...
Give a code snippet in #Sidef 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/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#Retro
Retro
: gcd ( ab-n ) [ tuck mod dup ] while drop ;
Give a code snippet in #Retro Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest...
christopher/rosetta-code
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbe...
#11l
11l
F reversed(Int =n) V result = 0 L result = 10 * result + n % 10 n I/= 10 I n == 0 R result   V limit = 1'000'000 V is_prime = [0B] * 2 [+] [1B] * (limit - 1) L(n) 0 .< Int(limit ^ 0.5 + 1.5) I is_prime[n] L(i) (n * n .< limit + 1).step(n) is_prime[i] = 0B   F is_emirp(...
Give a code snippet in #11l An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   em...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequ...
#Groovy
Groovy
println 'decimal octal' for (def i = 0; i <= Integer.MAX_VALUE; i++) { printf ('%7d  %#5o\n', i, i) }
Give a code snippet in #Groovy Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Lah_numbers
Lah numbers
Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets. Lah numbers a...
#Factor
Factor
USING: combinators combinators.short-circuit formatting infix io kernel locals math math.factorials math.ranges prettyprint sequences ; IN: rosetta-code.lah-numbers   ! Yes, Factor can do infix arithmetic with local variables! ! This is a good use case for it.   INFIX:: (lah) ( n k -- m ) ( factorial(n) * factorial...
Give a code snippet in #Factor Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly...
christopher/rosetta-code
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#Oz
Oz
functor import Application Open OS System define fun {TimeStamp} N = {OS.localTime} in (1900+N.year)#"-"#(1+N.mon)#"-"#N.mDay#", "#N.hour#":"#N.min#":"#N.sec end   fun {Join X|Xr Sep} {FoldL Xr fun {$ Z X} Z#Sep#X end X} end   case {Application.getArgs plain} of nil th...
Give a code snippet in #Oz Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT fo...
christopher/rosetta-code
http://rosettacode.org/wiki/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   Th...
#J
J
  fusc_term =: ({~ -:@#)`([: +/ ({~ ([: -: _1 1 + #)))@.(2 | #) fusc =: (, fusc_term)@:]^:[ 0 1"_   NB. show the first 61 fusc numbers (starting at zero) in a horizontal format. 61 {. fusc 70 0 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 1 6 5 9 4 11 7 10 3 11 8 13 5 12 7 9 2 9 7 12 5 13 8 11 3 ...
Give a code snippet in #J Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts...
christopher/rosetta-code
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro...
#REXX
REXX
/*REXX program determines the least costly path between two vertices given a list. */ $.= copies(9, digits() ) /*edge cost: indicates doesn't exist. */ xList= '!. @. $. beg fin bestP best$ xx yy' /*common EXPOSEd variables for subs. */ @abc= 'abcdefghijklmnopqrstuvwxyz' ...
Give a code snippet in #REXX This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the s...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#Tcl
Tcl
package require Tcl 8.5 set year [lindex $argv 0] foreach dm {02/1 03/1 04/1 05/1 06/1 07/1 08/1 09/1 10/1 11/1 12/1 12/32} { # The [clock scan] code is unhealthily clever; use it for our own evil purposes set t [clock scan "last friday" -base [clock scan $dm/$year -gmt 1] -gmt 1] # Print the interesting pa...
Give a code snippet in #Tcl Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-0...
christopher/rosetta-code
http://rosettacode.org/wiki/Shell_one-liner
Shell one-liner
Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different comman...
#Erlang
Erlang
$ erl -noshell -eval 'io:format("hello~n").' -s erlang halt hello
Give a code snippet in #Erlang Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementat...
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 ...
#Scala
Scala
def median[T](s: Seq[T])(implicit n: Fractional[T]) = { import n._ val (lower, upper) = s.sortWith(_<_).splitAt(s.size / 2) if (s.size % 2 == 0) (lower.last + upper.head) / fromInt(2) else upper.head }
Give a code snippet in #Scala Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values....
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Pascal
Pascal
print "Give me a number: "; chomp(my $a = <>);   $a == 42 or die "Error message\n";   # Alternatives die "Error message\n" unless $a == 42; die "Error message\n" if not $a == 42; die "Error message\n" if $a != 42;
Give a code snippet in #Pascal Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Vogel%27s_approximation_method
Vogel's approximation method
Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem. The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that: A will require 30 hours ...
#Racket
Racket
#lang racket (define-values (1st 2nd 3rd) (values first second third))   (define-syntax-rule (?: x t f) (if (zero? x) f t))   (define (hash-ref2 hsh# key-1 key-2 #:fail-2 (fail-2 (λ () (error 'hash-ref2 "key-2:~a is not found in hash" key-2))) #:fail-1 (fail-1 (λ () (error 'hash-ref2 "key-1:~...
Give a code snippet in #Racket Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem. The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate ...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#8th
8th
  \ Array of doors; init to empty; accessing a non-extant member will return \ 'null', which is treated as 'false', so we don't need to initialize it: [] var, doors   \ given a door number, get the value and toggle it: : toggle-door \ n -- doors @ over a:@ not rot swap a:! drop ;   \ print which doors are open: :...
Give a code snippet in #8th There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...)...
christopher/rosetta-code
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioin...
#Red
Red
Red ["ASCII table"]   repeat i 16 [ repeat j 6 [ n: j - 1 * 16 + i + 31 prin append pad/left n 3 ": " prin pad switch/default n [ 32 ["spc"] 127 ["del"] ] [to-char n] 4 ] prin newline ]
Give a code snippet in #Red Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I b...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#Emacs_Lisp
Emacs Lisp
(setq my-table (make-hash-table)) (puthash 'key 'value my-table)
Give a code snippet in #Emacs_Lisp Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definit...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#Ruby
Ruby
arr1 = [1, 2, 3] arr2 = [4, 5, 6] arr3 = [7, 8, 9] arr4 = arr1 + arr2 # => [1, 2, 3, 4, 5, 6] arr4.concat(arr3) # => [1, 2, 3, 4, 5, 6, 7, 8, 9]
Give a code snippet in #Ruby Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/Forest_fire
Forest fire
This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Drossel and Schwabl definition of the fores...
#8086_Assembly
8086 Assembly
;;; Simulation settings (probabilities are P/65536) probF: equ 7 ; P(spontaneous combustion) ~= 0.0001 probP: equ 655 ; P(spontaneous growth) ~= 0.01 HSIZE: equ 320 ; Field width (320x200 fills CGA screen) VSIZE: equ 200 ; Field height FSIZE: equ HSIZE*VSIZE ; Field size FPARA: equ FSIZE/16+1 ; Field size in para...
Give a code snippet in #8086_Assembly This page uses content from Wikipedia. The original article was at Forest-fire model. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Implement the Dros...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Pop11
Pop11
sysobey('ls');
Give a code snippet in #Pop11 Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by...
#AsciiDots
AsciiDots
  ``warps %$ABCPR   ``outputs all primes up to and including the input .-#?-A B-P/$_#$_" " R-*~ \/   ``primality test /---------------*-\ //-----------{*}*~-+\ ///--#1--\ /#1>/ \/ || \\*/#2>*-\-~#0*>R || /*>*+--++{%}/ \+>C || ``signal to C triggers next number |\--/>-/| || || ``to be input from fo...
Give a code snippet in #AsciiDots Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for bein...
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>
#XSLT
XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes" /> <xsl:template match="/"> <!-- replace the root of the incoming document with our own model --> <xsl:element name="root"> <xsl:element name="element"> <xsl:text>Some text here<...
Give a code snippet in #XSLT 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/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#360_Assembly
360 Assembly
SPIRALM CSECT USING SPIRALM,R13 SAVEAREA B STM-SAVEAREA(R15) DC 17F'0' DC CL8'SPIRALM' STM STM R14,R12,12(R13) ST R13,4(R15) ST R15,8(R13) LR R13,R15 * ---- CODE LA R0,0 LA R1,1 LH R1...
Give a code snippet in #360_Assembly Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Set_of_real_numbers
Set of real numbers
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary: [a, b]: {x | a ≤ x and x ≤ b } (a, b): {x | ...
#Delphi
Delphi
  program Set_of_real_numbers;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type TSet = TFunc<Double, boolean>;   function Union(a, b: TSet): TSet; begin Result := function(x: double): boolean begin Result := a(x) or b(x); end; end;   function Inter(a, b: TSet): TSet; begin Result := fun...
Give a code snippet in #Delphi All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary: [a, b]: {x | ...
christopher/rosetta-code
http://rosettacode.org/wiki/Attractive_numbers
Attractive numbers
A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task Show sequence items up to   120....
#ALGOL_W
ALGOL W
% find some attractive numbers - numbers whose prime factor count is prime  % begin  % implements the sieve of Eratosthenes  %  % s(i) is set to true if i is prime, false otherwise  %  % algol W doesn't have a upb operator, so we pass the size of the  ...
Give a code snippet in #ALGOL_W A number is an   attractive number   if the number of its prime factors (whether distinct or not) is also prime. Example The number   20,   whose prime decomposition is   2 × 2 × 5,   is an   attractive number   because the number of its prime factors   (3)   is also prime. Task ...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#TI-89_BASIC
TI-89 BASIC
:aplusb(a,b) :a+b
Give a code snippet in #TI-89_BASIC A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, se...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Perl
Perl
use integer;   sub bitwise($$) { ($a, $b) = @_; print 'a and b: '. ($a & $b) ."\n"; print 'a or b: '. ($a | $b) ."\n"; print 'a xor b: '. ($a ^ $b) ."\n"; print 'not a: '. (~$a) ."\n"; print 'a >> b: ', $a >> $b, "\n"; # logical right shift   use integer; # "use integer" enables bitwise oper...
Give a code snippet in #Perl 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 C...
christopher/rosetta-code
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#MUMPS
MUMPS
BOXING(DEGREE)  ;This takes in a degree heading, nominally from 0 to 360, and returns the compass point name. QUIT:((DEGREE<0)||(DEGREE>360)) "land lubber can't read a compass" NEW DIRS,UNP,UNPACK,SEP,DIR,DOS,D,DS,I,F SET DIRS="N^NbE^N-NE^NEbN^NE^NEbE^E-NE^EbN^E^EbS^E-SE^SEbE^SE^SEbS^S-SE^SbE^" SET DIRS=DIRS_"S^SbW...
Give a code snippet in #MUMPS There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and di...
christopher/rosetta-code
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. C...
#Prolog
Prolog
church_zero(z).   church_successor(Z, c(Z)).   church_add(z, Z, Z). church_add(c(X), Y, c(Z)) :- church_add(X, Y, Z).   church_multiply(z, _, z). church_multiply(c(X), Y, R) :- church_add(Y, S, R), church_multiply(X, Y, S).   % N ^ M church_power(z, z, z). church_power(N, c(z), N). church_power(N, c(c(Z)), ...
Give a code snippet in #Prolog Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied t...
christopher/rosetta-code
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#11l
11l
V cellcountx = 6 V cellcounty = 5 V celltable = [(1, 2) = 1, (1, 3) = 1, (0, 3) = 1] DefaultDict[(Int, Int), Int] universe universe[(1, 1)] = 1 universe[(2, 1)] = 1 universe[(3, 1)] = 1 universe[(1, 4)] = 1 universe[(2, 4)] = 1 universe[(3, 4)] = 1   L(i) 4 print("\nGeneration "i‘:’) ...
Give a code snippet in #11l The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   i...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I befo...
#Transd
Transd
#lang transd   MainModule : { _start: (lambda (with v ["apple", "orange"] (lout (size v)) ) (lout (size ["apple", "orange"])) ) }
Give a code snippet in #Transd Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter freq...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#ALGOL_68
ALGOL 68
# -*- coding: utf-8 -*- #   COMMENT REQUIRED BY "prelude_combinations_generative.a68" MODE COMBDATA = ~; PROVIDES: # COMBDATA*=~* # # comb*=~ list* # END COMMENT   MODE COMBDATALIST = REF[]COMBDATA; MODE COMBDATALISTYIELD = PROC(COMBDATALIST)VOID;   PROC comb gen combinations = (INT m, COMBDATALIST list, COMBDATALIST...
Give a code snippet in #ALGOL_68 Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#Ruby
Ruby
res = (1 .. 20_000).map{|n| n.proper_divisors.sum <=> n }.tally puts "Deficient: #{res[-1]} Perfect: #{res[0]} Abundant: #{res[1]}"  
Give a code snippet in #Ruby These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient ...
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...
#Nim
Nim
import std/wordwrap   let txt = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue e...
Give a code snippet in #Nim 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 provid...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The...
#Clojure
Clojure
(ns rosettacode.html-table (:use 'hiccup.core))   (defn <tr> [el sq] [:tr (map vector (cycle [el]) sq)])   (html [:table (<tr> :th ["" \X \Y \Z]) (for [n (range 1 4)] (->> #(rand-int 10000) (repeatedly 3) (cons n) (<tr> :td)))])
Give a code snippet in #Clojure Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled w...
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const proc: main is func local const float: r is 7.125; begin writeln( r digits 3 lpad 9); writeln(-r digits 3 lpad 9); writeln( r digits 3 lpad0 9); writeln(-r digits 3 lpad0 9); writeln( r digits 3); writeln(-r digits 3); end func;
Give a code snippet in #Seed7 Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/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.
#Retro
Retro
needs assertion' needs hash'   : palindrome? ( $-f ) dup ^hash'hash [ ^strings'reverse ^hash'hash ] dip = ;   with assertion' : t0 ( - ) "hello" palindrome? 0 assert=  ; assertion : t1 ( - ) "ingirumimusnocteetconsumimurigni" palindrome? -1 assert=  ; assertion : test ( - ) t0 t1 ; test
Give a code snippet in #Retro 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/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#ERRE
ERRE
  PROGRAM NTH_SOLVE   ! ! for rosettacode.org !   PROCEDURE NTH(S%,E%) LOCAL I%,SUFF$ FOR I%=S% TO E% DO SUFF$="th" IF I% MOD 10=1 AND I% MOD 100<>11 THEN SUFF$="st" END IF IF I% MOD 10=2 AND I% MOD 100<>12 THEN SUFF$="nd" END IF IF I% MOD 10=3 AND I% MOD 100<>13 THEN SUFF$="...
Give a code snippet in #ERRE Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show ...
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...
#Swift
Swift
import Foundation   let str = "the quick brown fox jumps over the lazy dog"   func isPangram(str:String) -> Bool { let stringArray = Array(str.lowercaseString) for char in "abcdefghijklmnopqrstuvwxyz" { if (find(stringArray, char) == nil) { return false } } return true }   is...
Give a code snippet in #Swift 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 Wri...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Action.21
Action!
PROC PrintArray(INT ARRAY a INT size) INT i   Put('[) FOR i=0 TO size-1 DO IF i>0 THEN Put(' ) FI PrintI(a(i)) OD Put(']) PutE() RETURN   PROC InsertionSort(INT ARRAY a INT size) INT i,j,value   FOR i=1 TO size-1 DO value=a(i) j=i-1 WHILE j>=0 AND a(j)>value DO a(j+1)=a(j...
Give a code snippet in #Action.21 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 | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#C.2B.2B
C++
#include <string> #include <sstream> #include <vector> #include <iterator> #include <iostream> #include <algorithm> int main() { std::string s = "Hello,How,Are,You,Today"; std::vector<std::string> v; std::istringstream buf(s); for(std::string token; getline(buf, token, ','); ) v.push_back(token)...
Give a code snippet in #C.2B.2B Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#Asymptote
Asymptote
string s1 = "Hello"; write(s1 + " World!"); write(s1, " World!"); string s2 = s1 + " World!"; write(s2);
Give a code snippet in #Asymptote String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string...
christopher/rosetta-code
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the ...
#Lua
Lua
local d, digits, alpha = '01230120022455012623010202', {}, ('A'):byte() d:gsub(".",function(c) digits[string.char(alpha)] = c alpha = alpha + 1 end)   function soundex(w) local res = {} for c in w:upper():gmatch'.'do local d = digits[c] if d then if #res==0 then res[1] = c elseif #...
Give a code snippet in #Lua Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Burlesque
Burlesque
  blsq ) {"acb" "Abc" "Acb" "acc" "ADD"}>< {"ADD" "Abc" "Acb" "acb" "acc"} blsq ) {"acb" "Abc" "Acb" "acc" "ADD"}(zz)CMsb {"Abc" "acb" "Acb" "acc" "ADD"}  
Give a code snippet in #Burlesque 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 | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#RLaB
RLaB
>> class(sin) function >> type(sin) builtin
Give a code snippet in #RLaB A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract f...
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Ol
Ol
  (define (shuffle tp) (let ((items (vm:cast tp (type tp)))) ; make a copy (for-each (lambda (i) (let ((a (ref items i)) (j (+ 1 (rand! i)))) (set-ref! items i (ref items j)) (set-ref! items j a))) (reverse (iota (size items) 1))) items...
Give a code snippet in #Ol The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#MAXScript
MAXScript
fn binarySearchIterative arr value = ( lower = 1 upper = arr.count while lower <= upper do ( mid = (lower + upper) / 2 if arr[mid] > value then ( upper = mid - 1 ) else if arr[mid] < value then ( lower = mid + 1 ) el...
Give a code snippet in #MAXScript A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secr...
christopher/rosetta-code
http://rosettacode.org/wiki/Shortest_common_supersequence
Shortest common supersequence
The   shortest common supersequence   is a problem closely related to the   longest common subsequence,   which you can use as an external function for this task. Task Given two strings u {\displaystyle u} and v {\displaystyle v} , find the shortest possible sequence s {\displaystyle s} , whic...
#Racket
Racket
#lang racket   (struct link (len letters))   (define (link-add li n letter) (link (+ n (link-len li)) (cons letter (link-letters li))))   (define (memoize f) (local ([define table (make-hash)]) (lambda args (dict-ref! table args (λ () (apply f args))))))   (define scs/list (memoize (lambda ...
Give a code snippet in #Racket The   shortest common supersequence   is a problem closely related to the   longest common subsequence,   which you can use as an external function for this task. Task Given two strings u {\displaystyle u} and v {\displaystyle v} , find the shortest possible sequence ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Heapsort
Sorting algorithms/Heapsort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Eiffel
Eiffel
  class HEAPSORT   feature   sort_array (ar: ARRAY [INTEGER]) -- Sorts array 'ar' in ascending order. require not_empty: ar.count > 0 local i, j, r, l, m, n: INTEGER sorted: BOOLEAN do n := ar.count j := 0 i := 0 m := 0 r := n l := (n // 2)+1 from until sorted loop ...
Give a code snippet in #Eiffel Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#Quackery
Quackery
randomise 10 random 1+ number$ say 'I chose a number between 1 and 10.' cr [ $ 'Your guess? ' input over = if done again ] drop say 'Well guessed!'
Give a code snippet in #Quackery Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * ...
#PL.2FI
PL/I
sierpinski: procedure options (main); /* 2010-03-30 */ declare t (79,79) char (1); declare (i, j, k) fixed binary; declare (y, xs, ys, xll, xrr, ixrr, limit) fixed binary;   t = ' '; xs = 40; ys = 1; /* Make initial triangle */ call make_triangle (xs, ys); y = ys + 4; xll = xs-4; xrr = xs+4; ...
Give a code snippet in #PL.2FI Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * ...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_ternary
Balanced ternary
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0" ...
#Raku
Raku
class BT { has @.coeff;   my %co2bt = '-1' => '-', '0' => '0', '1' => '+'; my %bt2co = %co2bt.invert;   multi method new (Str $s) { self.bless(coeff => %bt2co{$s.flip.comb}); } multi method new (Int $i where $i >= 0) { self.bless(coeff => carry $i.base(3).comb.reverse); } multi method ...
Give a code snippet in #Raku Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, th...
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...
#jq
jq
# Perform the action, then check the condition, etc def do_while( action; condition ): def w: action | if (condition | not) then empty else ., w end; w;
Give a code snippet in #jq 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/Down...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Count_examples
Rosetta Code/Count examples
task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'll need to use the Media Wiki AP...
#Julia
Julia
using HTTP, JSON, Dates   rosorg = "http://rosettacode.org" qURI = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=json" qdURI = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Draft_Programming_Tasks&cmlimit=500&format=json" sqURI = rosorg * "/wiki/"...
Give a code snippet in #Julia task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'l...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor
Terminal control/Hiding the cursor
The task is to hide the cursor and show it again.
#Furor
Furor
  cursoroff  
Give a code snippet in #Furor The task is to hide the cursor and show it again.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. 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 algor...
#Perl
Perl
sub combSort { my @arr = @_; my $gap = @arr; my $swaps = 1; while ($gap > 1 || $swaps) { $gap /= 1.25 if $gap > 1; $swaps = 0; foreach my $i (0 .. $#arr - $gap) { if ($arr[$i] > $arr[$i+$gap]) { @arr[$i, $i+$gap] = @arr[$i+$gap, $i]; $s...
Give a code snippet in #Perl Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. 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 so...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_easy
Abbreviations, easy
This task is an easier (to code) variant of the Rosetta Code task:   Abbreviations, simple. For this task, the following   command table   will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find ...
#Pascal
Pascal
  program Abbreviations_Easy; {$IFDEF WINDOWS} {$APPTYPE CONSOLE} {$ENDIF} {$IFDEF FPC} {$MODE DELPHI} uses SysUtils; {$ELSE} uses System.SysUtils; {$ENDIF}   const _TABLE_ = 'Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy ' + 'COUnt COVerlay CURsor DELete CDelete...
Give a code snippet in #Pascal This task is an easier (to code) variant of the Rosetta Code task:   Abbreviations, simple. For this task, the following   command table   will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPl...
christopher/rosetta-code
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-digit law, refers to the freque...
#Ruby
Ruby
EXPECTED = (1..9).map{|d| Math.log10(1+1.0/d)}   def fib(n) a,b = 0,1 n.times.map{ret, a, b = a, b, a+b; ret} end   # powers of 3 as a test sequence def power_of_threes(n) n.times.map{|k| 3**k} end   def heads(s) s.map{|a| a.to_s[0].to_i} end   def show_dist(title, s) s = heads(s) c = Array.new(10, 0) s.e...
Give a code snippet in #Ruby This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Benford's law, also called the first-d...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#JavaScript
JavaScript
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Draw a sphere</title> <script> var light=[30,30,-50],gR,gk,gambient;   function normalize(v){ var len=Math.sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]); v[0]/=len; v[1]/=len; v[2]/=len; return v; }   function dot(x,y){ var d=x[0]*y[0]+x[1]*y[1]+x[2]*y[2]; return...
Give a code snippet in #JavaScript Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw...
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 ...
#BBC_BASIC
BBC BASIC
DEF PROC_GnomeSort1(Size%) I%=2 J%=2 REPEAT IF data%(J%-1) <=data%(J%) THEN I%+=1 J%=I% ELSE SWAP data%(J%-1),data%(J%) J%-=1 IF J%=1 THEN I%+=1 J%=I% ENDIF ENDIF UNTIL I%>Size% ENDPROC
Give a code snippet in #BBC_BASIC 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 | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. C...
#Chapel
Chapel
class Church { // identity Church function by default proc this(f: shared Church): shared Church { return f; } }   // utility Church functions... class ComposeChurch : Church { const l, r: shared Church; override proc this(f: shared Church): shared Church { return l(r(f)); } }   proc composeChur...
Give a code snippet in #Chapel Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied t...
christopher/rosetta-code
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#Pascal
Pascal
program Gol; // Game of life {$IFDEF FPC} //save as gol.pp/gol.pas {$Mode delphi} {$ELSE} //for Delphi save as gol.dpr {$Apptype Console} {$ENDIF} uses crt;   const colMax = 76; rowMax = 22; dr = colMax+2; // element count of one row   cDelay = 20; // delay in ms   (* expand field by one row/column ...
Give a code snippet in #Pascal The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Order_disjoint_list_items
Order disjoint list items
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 ...
#C.2B.2B
C++
  #include <iostream> #include <vector> #include <algorithm> #include <string>   template <typename T> void print(const std::vector<T> v) { std::cout << "{ "; for (const auto& e : v) { std::cout << e << " "; } std::cout << "}"; }   template <typename T> auto orderDisjointArrayItems(std::vector<T> M, std::ve...
Give a code snippet in #C.2B.2B Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#Crystal
Crystal
def sierpinski_carpet(n) carpet = ["#"] n.times do carpet = carpet.map { |x| x + x + x } + carpet.map { |x| x + x.tr("#"," ") + x } + carpet.map { |x| x + x + x } end carpet end   5.times{ |i| puts "\nN=#{i}"; sierpinski_carpet(i).each { |row| puts row } }
Give a code snippet in #Crystal Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#Icon_and_Unicon
Icon and Unicon
procedure main()   every !(!(L := list(10)) := list(10)) := ?20 # setup a 2d array of random numbers up to 20   every i := 1 to *L do # using nested loops every j := 1 to *L[i] do if L[i,j] = 20 then break break write("L[",i,",",j,"]=20")   end
Give a code snippet in #Icon_and_Unicon Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 2...
christopher/rosetta-code
http://rosettacode.org/wiki/Joystick_position
Joystick position
The task is to determine the joystick position and represent this on the display via a crosshair. For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed. ...
#Haskell
Haskell
import qualified Graphics.UI.GLFW as GLFW -- cabal install GLFW-b import Graphics.Win32.Key import Control.Monad.RWS.Strict (liftIO)   main = do liftIO $ do _ <- GLFW.init GLFW.pollEvents (jxrot, jyrot) <- liftIO $ getJoystickDirections GLFW.Joystick'1 putStrLn $ (show jxrot...
Give a code snippet in #Haskell The task is to determine the joystick position and represent this on the display via a crosshair. For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according to the exte...
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
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 ...
#BBC_BASIC
BBC BASIC
DIM list$(15) list$() = "Now", "is", "the", "time", "for", "all", "good", "men", \ \ "to", "come", "to", "the", "aid", "of", "the", "party." num% = FNremoveduplicates(list$()) FOR i% = 0 TO num%-1 PRINT list$(i%) " " ; NEXT PRINT END   DEF FNremovedu...
Give a code snippet in #BBC_BASIC 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 | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort
Sorting algorithms/Stooge 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 ...
#COBOL
COBOL
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. stooge-sort-test.   DATA DIVISION. WORKING-STORAGE SECTION. 01 Arr-Len CONSTANT 7.   01 arr-area VALUE "00004001000020000005000230000000000". 03 arr-elt PIC 9(5) OCCURS Arr-Len...
Give a code snippet in #COBOL 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 so...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score...
#Ceylon
Ceylon
shared void run() { while(true) { variable value low = 1; variable value high = 10; variable value attempts = 1; print("Please choose a number between ``low`` and ``high``. Press enter when ready."); process.readLine(); while(true) { if(low ...
Give a code snippet in #Ceylon Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be ass...
#Sidef
Sidef
var dec = '0123459'; var hex_noprefix = 'abcf123'; var hex_withprefix = '0xabcf123'; var oct_noprefix = '7651'; var oct_withprefix = '07651'; var bin_noprefix = '101011001'; var bin_withprefix = '0b101011001';   say dec.num; # => 123459 say hex_noprefix.hex; # => 180154659 ...
Give a code snippet in #Sidef It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of ...
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...
#VBA
VBA
  Public Sub orderedwords(fname As String) ' find ordered words in dict file that have the longest word length ' fname is the name of the input file ' the words are printed in the immediate window ' this subroutine uses boolean function IsOrdered   Dim word As String 'word to be tested Dim l As Integer ...
Give a code snippet in #VBA 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Pop11
Pop11
;;; Generic filtering procedure which selects from ar elements ;;; satisfying pred define filter_array(ar, pred); lvars i, k; stacklength() -> k; for i from 1 to length(ar) do  ;;; if element satisfies pred we leave it on the stack if pred(ar(i)) then ar(i) endif; endfor;  ;;; Collect elemen...
Give a code snippet in #Pop11 Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ......
#JavaScript
JavaScript
let q = 1n, r = 180n, t = 60n, i = 2n; for (;;) { let y = (q*(27n*i-12n)+5n*r)/(5n*t); let u = 3n*(3n*i+1n)*(3n*i+2n); r = 10n*u*(q*(5n*i-2n)+r-y*t); q = 10n*q*i*(2n*i-1n); t = t*u; i = i+1n; process.stdout.write(y.toString()); if (i === 3n) { process.stdout.write('.'); } }
Give a code snippet in #JavaScript Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal...
christopher/rosetta-code
http://rosettacode.org/wiki/String_interpolation_(included)
String interpolation (included)
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 |...
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion call :interpolate %1 %2 res echo %res% goto :eof   :interpolate set pat=%~1 set str=%~2 set %3=!pat:X=%str%! goto :eof
Give a code snippet in #Batch_File 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 Operat...
christopher/rosetta-code