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/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#Phix
Phix
with javascript_semantics function allsame(sequence s) for i=2 to length(s) do if s[i]!=s[1] then return false end if end for return true end function function strict_order(sequence s) for i=2 to length(s) do if s[i]<=s[i-1] then return false end if end for return true end func...
Give a code snippet in #Phix Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false v...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.41421356...
#SAS
SAS
data _null_; input x y; file "output.txt"; put x 12.3 " " y 12.5; cards; 1 1 2 1.4142135623730951 3 1.7320508075688772 1e11 316227.76601683791 ; run;
Give a code snippet in #SAS Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3,...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_variables
Special variables
Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
#PL.2FI
PL/I
  Special variables in PL/I are termed "Pseudo-variables". They are used only on the LHS of an assignment statement.   They include: REAL to assign the real part of a COMPLEX variable; IMAG to assign the imaginary part of a COMPLEX variable; SUBSTR is used to assign part of a string (used on the LHS of an assi...
Give a code snippet in #PL.2FI Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
christopher/rosetta-code
http://rosettacode.org/wiki/MD4
MD4
Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifi...
#Sidef
Sidef
var digest = frequire('Digest::MD4'); say digest.md4_hex('Rosetta Code');
Give a code snippet in #Sidef Find the MD4 message digest of a string of octets. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. MD4 is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsole...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#Ursala
Ursala
#import std #import nat   cwr = ~&s+ -<&*+ ~&K0=>&^|DlS/~& iota # takes a set and a selection size   #cast %gLSnX   main = ^|(~&,length) cwr~~/(<'iced','jam','plain'>,2) ('1234567890',3)
Give a code snippet in #Ursala The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of...
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...
#GAP
GAP
# Built-in GcdInt(35, 42); # 7   # Euclidean algorithm GcdInteger := function(a, b) local c; a := AbsInt(a); b := AbsInt(b); while b > 0 do c := a; a := b; b := RemInt(c, b); od; return a; end;   GcdInteger(35, 42); # 7
Give a code snippet in #GAP Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest c...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#C.2B.2B
C++
#include<cstdlib> #include<ctime> #include<iostream>   using namespace std; int main() { int arr[10][10]; srand(time(NULL)); for(auto& row: arr) for(auto& col: row) col = rand() % 20 + 1;   ([&](){ for(auto& row : arr) for(auto& col: row) { ...
Give a code snippet in #C.2B.2B 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#Phix
Phix
integer n = 0 sequence digits={0} procedure nNiven() while 1 do n += 1 for i=length(digits) to 0 by -1 do if i=0 then digits = prepend(digits,1) exit end if if digits[i]<9 then digits[i] += 1 exit ...
Give a code snippet in #Phix The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task i...
christopher/rosetta-code
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#Octave
Octave
I = eye(10)
Give a code snippet in #Octave Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Ruby
Ruby
def move(num_disks, start=0, target=1, using=2) if num_disks == 1 @towers[target] << @towers[start].pop puts "Move disk from #{start} to #{target} : #{@towers}" else move(num_disks-1, start, using, target) move(1, start, target, using) move(num_disks-1, using, target, start) end end ...
Give a code snippet in #Ruby Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#smart_BASIC
smart BASIC
'Animation, by rbytes and Dutchman word$="Hello World! " 'use button window with text SET BUTTONS CUSTOM SET BUTTONS FONT SIZE 40 DRAW COLOR 0,0,0 DO 'the button is redrawn each loop BUTTON "anim" TEXT word$ AT 130,100 PAUSE .1 'touching the button reverses the scrolling IF BUTTON_PRESSED("anim") THEN flag=1-flag IF fl...
Give a code snippet in #smart_BASIC Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This t...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Get["myfile.m"]
Give a code snippet in #Mathematica_.2F_Wolfram_Language Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
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.
#LIL
LIL
## Array concatenation in LIL ## set a [list 1 2 3] set b [list 4 5 6] set c [quote $a $b]   print $c print "[index $c 0] [index $c 3]"
Give a code snippet in #LIL 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/Biorhythms
Biorhythms
For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia, but the main takeaway is that u...
#Factor
Factor
USING: calendar calendar.parser formatting io kernel math math.constants math.functions ;   : days-between ( ymd-str ymd-str -- n ) [ ymd>timestamp ] bi@ time- duration>days abs ;   : trend ( pos len -- str ) / 4 * floor 3 divisor? "↑" "↓" ? ;   : percent ( pos len -- x ) [ 2pi * ] [ / sin 100 * ] bi* ;   : .day ( ...
Give a code snippet in #Factor For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia,...
christopher/rosetta-code
http://rosettacode.org/wiki/Introspection
Introspection
Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop). Extra credit Repor...
#Phix
Phix
requires("0.8.2") -- crashes on 0.8.1 and earlier requires(WINDOWS) -- crashes on Linux requires(64) -- crashes on 32-bit
Give a code snippet in #Phix Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(...
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...
#REXX
REXX
/*REXX pgm computes & shows the factorial of a non─negative integer, and also its length*/ numeric digits 100000 /*100k digits: handles N up to 25k.*/ parse arg n /*obtain optional argument from the CL.*/ if n='' then call er 'no arg...
Give a code snippet in #REXX 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 nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#AutoHotkey
AutoHotkey
MsgBox % time("fx") Return   fx() { Sleep, 1000 }   time(function, parameter=0) { SetBatchLines -1 ; don't sleep for other green threads StartTime := A_TickCount %function%(parameter) Return ElapsedTime := A_TickCount - StartTime . " milliseconds" }
Give a code snippet in #AutoHotkey Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time be...
christopher/rosetta-code
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Retro
Retro
  # Determine The Average Word Name Length   To determine the average length of a word name two values are needed. First, the total length of all names in the Dictionary:   ~~~ #0 [ d:name s:length + ] d:for-each ~~~   And then the number of words in the Dictionary:   ~~~ #0 [ dr...
Give a code snippet in #Retro See also Related task: Comments Related task: Here_document
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Clojure
Clojure
(apply str (repeat 5 "ha"))
Give a code snippet in #Clojure Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the foll...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
FindCommonDirectory[x_] := If[StringTake[#, -1] != "/", StringTake[#, Max[StringPosition[#, "/"]]], #] & [Fold[LongestCommonSubsequence, First[x] , Rest[x]]]   FindCommonDirectory[{"/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"}] ->"/home/user1/tmp/"
Give a code snippet in #Mathematica.2FWolfram_Language Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward sla...
christopher/rosetta-code
http://rosettacode.org/wiki/P-Adic_square_roots
P-Adic square roots
Task. Convert rational a/b to its approximate p-adic square root. To check the result, square the root and construct rational m/n to compare with radicand a/b. For rational reconstruction Lagrange's lattice basis reduction algorithm is used. Recipe: find root x1 modulo p and build a sequence of solutions f(xk) ≡ 0 ...
#Nim
Nim
import strformat   const Emx = 64 # Exponent maximum. Amx = 6000 # Argument maximum. PMax = 32749 # Prime maximum.   type   Ratio = tuple[a, b: int]   Padic = object p: int # Prime. k: int # Precision. v: int d: array[-Emx..(Emx-1), ...
Give a code snippet in #Nim Task. Convert rational a/b to its approximate p-adic square root. To check the result, square the root and construct rational m/n to compare with radicand a/b. For rational reconstruction Lagrange's lattice basis reduction algorithm is used. Recipe: find root x1 modulo p and build a seq...
christopher/rosetta-code
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#Excel
Excel
REPCYCLES =LAMBDA(s, LET( n, LEN(s), xs, FILTERP( LAMBDA(pfx, s = TAKECYCLESTRING(n)(pfx) ) )( TAILCOLS( INITS( MID(s, 1, QUOTIENT(n, 2)) ) ) ),   IF(ISERROR(xs)...
Give a code snippet in #Excel Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at leas...
christopher/rosetta-code
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#11l
11l
L(ln) File(‘data.txt’).read_lines() I Float(ln.split(‘ ’, group_delimiters' 1B)[2]) > 6 print(ln)
Give a code snippet in #11l Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines fr...
christopher/rosetta-code
http://rosettacode.org/wiki/Introspection
Introspection
Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop). Extra credit Repor...
#Smalltalk
Smalltalk
| s v t sum hm | "uncomment the following to see what happens if bloop exists" "Smalltalk at: #bloop put: -10." s := Smalltalk version. (s =~ '(\d+)\.(\d+)\.(\d+)') ifMatched: [:match | v := (( (match at: 1) asInteger ) * 100) + (( (match at: 2) asInteger ) * 10) + ( (match at: 3) as...
Give a code snippet in #Smalltalk Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#Vlang
Vlang
for i := 1; i<10; i+=2 { println(i) }
Give a code snippet in #Vlang Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Inc...
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#TI-83_BASIC
TI-83 BASIC
If condition statement
Give a code snippet in #TI-83_BASIC Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. C...
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   ...
#PicoLisp
PicoLisp
(let Dir "." (recur (Dir) (for F (dir Dir) (let Path (pack Dir "/" F) (cond ((=T (car (info Path))) # Is a subdirectory? (recurse Path) ) # Yes: Recurse ((match '`(chop "s@.l") (chop F)) # Matches 's*.l'? ...
Give a code snippet in #PicoLisp Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   W...
christopher/rosetta-code
http://rosettacode.org/wiki/OpenGL
OpenGL
Task Display a smooth shaded triangle with OpenGL. Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
#Phix
Phix
-- -- demo\rosetta\OpenGL.exw -- ======================= -- with javascript_semantics requires("1.0.1") include pGUI.e include opengl.e Ihandln dlg Ihandle canvas constant fragment_shader = """ precision highp float; varying vec4 v_color; void main(void) { // "Varying" variables are implicitly interpolated across...
Give a code snippet in #Phix Task Display a smooth shaded triangle with OpenGL. Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Seed7
Seed7
$ include "seed7_05.s7i";   const func string: getLine (inout file: aFile, in var integer: lineNum) is func result var string: line is ""; begin while lineNum > 1 and hasNext(aFile) do readln(aFile); decr(lineNum); end while; line := getln(aFile); end func;   const proc: main is func ...
Give a code snippet in #Seed7 Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it i...
christopher/rosetta-code
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#Pure
Pure
F 0 = 1; M 0 = 0; F n = n - M(F(n-1)) if n>0; M n = n - F(M(n-1)) if n>0;
Give a code snippet in #Pure Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n )...
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to rais...
#EGL
EGL
record U0 type Exception end   record U1 type Exception end   program Exceptions   function main() foo(); end   function foo() try bar(); onException(ex U0) SysLib.writeStdout("Caught a U0 with message: '" :: ex.message :: "'"); end bar(); ...
Give a code snippet in #EGL Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisibl...
#Aime
Aime
o_text(bfxa(0, 0, 16, 1000000)); o_byte('\n'); o_text(bfxa(0, 0, 5, 1000000)); o_byte('\n'); o_text(bfxa(0, 0, 2, 1000000)); o_byte('\n');   o_integer(alpha("f4240", 16)); o_byte('\n'); o_integer(alpha("224000000", 5)); o_byte('\n'); o_integer(alpha("11110100001001000000", 2)); o_byte('\n');
Give a code snippet in #Aime Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary,...
christopher/rosetta-code
http://rosettacode.org/wiki/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#ActionScript
ActionScript
  var cube:Function = function(x) { return Math.pow(x, 3); }; var cuberoot:Function = function(x) { return Math.pow(x, 1/3); };   function compose(f:Function, g:Function):Function { return function(x:Number) {return f(g(x));}; } var functions:Array = [Math.cos, Math.tan, cube]; var inverse:Array = [Math.acos, Math...
Give a code snippet in #ActionScript A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_Chess960_starting_position
Generate Chess960 starting position
Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must be placed on the second rank. W...
#Sidef
Sidef
func is_valid_960 (backrank) { var king = backrank.index('♚') var (rook1, rook2) = backrank.indices_of('♜')... king.is_between(rook1, rook2) || return false var (bishop1, bishop2) = backrank.indices_of('♝')... bishop1+bishop2 -> is_odd }   func random_960_position(pieces = <♛ ♚ ♜ ♜ ♝ ♝ ♞ ♞>) { p...
Give a code snippet in #Sidef Chess960 is a variant of chess created by world champion Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: as in the standard chess game, all eight white pawns must b...
christopher/rosetta-code
http://rosettacode.org/wiki/Four_is_magic
Four is magic
Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the firs...
#Wren
Wren
import "/str" for Str   var small = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]   var tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy",...
Give a code snippet in #Wren Task Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of ch...
christopher/rosetta-code
http://rosettacode.org/wiki/Earliest_difference_between_prime_gaps
Earliest difference between prime gaps
When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it is also conjectured that betwe...
#Perl
Perl
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Earliest_difference_between_prime_gaps use warnings; use ntheory qw( primes );   my @gaps; my $primeref = primes( 1e9 ); for my $i ( 2 .. $#$primeref ) { my $diff = $primeref->[$i] - $primeref->[$i - 1]; $gaps[ $diff >> 1 ] //= $primeref->[$i - 1]; } ...
Give a code snippet in #Perl When calculating prime numbers > 2, the difference between adjacent primes is always an even number. This difference, also referred to as the gap, varies in an random pattern; at least, no pattern has ever been discovered, and it is strongly conjectured that no pattern exists. However, it ...
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#Objeck
Objeck
bundle Default { class Accumulator { @sum : Float;   New(sum : Float) { @sum := sum; }   method : public : Call(n : Float) ~ Float { @sum += n; return @sum; }   function : Main(args : String[]) ~ Nil { x := Accumulator->New(1.0); x->Call(5.0 ); x->Call(2.3)...
Give a code snippet in #Objeck A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values pa...
christopher/rosetta-code
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call
Respond to an unknown method call
Task Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions. Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin...
#J
J
example=:3 :0 doSomething_z_=: assert&0 bind 'doSomething was not implemented' doSomething__y '' )   doSomething_adhoc1_=: smoutput bind 'hello world' dSomethingElse_adhoc2_=: smoutput bind 'hello world'
Give a code snippet in #J Task Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions. Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of i...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Frink
Frink
  units = array[units[volume]] showApproximations[false]   for n = 99 to 0 step -1 { unit = units.removeRandom[] str = getBottleString[n, unit]   println["$str of beer on the wall, $str."]   if (n == 0) println["Go to the store and buy some more, 99 bottles of beer on the wall."] else println...
Give a code snippet in #Frink Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98...
christopher/rosetta-code
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X
Isqrt (integer square root) of X
Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your computer programming language,   assume...
#Nim
Nim
import strformat, strutils import bignum     func isqrt*[T: SomeSignedInt | Int](x: T): T = ## Compute integer square root for signed integers ## and for big integers.   when T is Int: result = newInt() var q = newInt(1) else: result = 0 var q = T(1)   while q <= x: q = q shl 2   var z =...
Give a code snippet in #Nim Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your computer p...
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: * * * * * * * * * * * * * * * ...
#PostScript
PostScript
%!PS-Adobe-3.0 %%BoundingBox 0 0 300 300   /F { 1 0 rlineto } def /+ { 120 rotate } def /- {-120 rotate } def /v {.5 .5 scale } def /^ { 2 2 scale } def /!0{ dup 1 sub dup -1 eq not } def   /X { !0 { v X + F - X - F + X ^ } { F } ifelse pop } def   0 1 8 { 300 300 scale 0 1 12 div moveto X + F + F fill showpag...
Give a code snippet in #PostScript 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/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#Maxima
Maxima
/* Maxima has integers of arbitrary length */ 170141183460469231731687303715884105727
Give a code snippet in #Maxima Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should b...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_the_coins
Count the coins
There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pennies   A nickel and 10 pen...
#C
C
#include <stdio.h> #include <stdlib.h> #include <stdint.h>   // ad hoc 128 bit integer type; faster than using GMP because of low // overhead typedef struct { uint64_t x[2]; } i128;   // display in decimal void show(i128 v) { uint32_t x[4] = {v.x[0], v.x[0] >> 32, v.x[1], v.x[1] >> 32}; int i, j = 0, len = 4; char b...
Give a code snippet in #C There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pen...
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 ...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
multiply a b: * a b
Give a code snippet in #D.C3.A9j.C3.A0_Vu 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Legendre_prime_counting_function
Legendre prime counting function
The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle. To calculate: Define φ(x, 0) = x φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number. then π(n) ...
#J
J
require'format/printf' {{echo '10^%d: %d' sprintf y;p:inv 10^y}}"0 i.10 10^0: 0 10^1: 4 10^2: 25 10^3: 168 10^4: 1229 10^5: 9592 10^6: 78498 10^7: 664579 10^8: 5761455 10^9: 50847534
Give a code snippet in #J The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle. To calculate: Define φ(x, 0) = x φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath...
christopher/rosetta-code
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th...
#Python
Python
def monkey_coconuts(sailors=5): "Parameterised the number of sailors using an inner loop including the last mornings case" nuts = sailors while True: n0, wakes = nuts, [] for sailor in range(sailors + 1): portion, remainder = divmod(n0, sailors) wakes.append((n0, ...
Give a code snippet in #Python Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so...
christopher/rosetta-code
http://rosettacode.org/wiki/Object_serialization
Object serialization
Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o...
#Python
Python
# Object Serialization in Python # serialization in python is accomplished via the Pickle module. # Alternatively, one can use the cPickle module if speed is the key, # everything else in this example remains the same.   import pickle   class Entity: def __init__(self): self.name = "Entity" def printName(self): p...
Give a code snippet in #Python Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each ...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Floating_point
Literals/Floating point
Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/ABNF/EBNF defining allowable fo...
#Scala
Scala
1. //Double equal to 1.0 1.0 //Double, a 64-bit IEEE-754 floating point number (equivalent to Java's double primitive type) 2432311.7567374 //Double 1.234E-10 //Double 1.234e-10 //Double 758832d //Double 728832f //32-bit IEEE-754 floating point number (equivalent to Java's float primitive type) 1.0f //Float 758832D //...
Give a code snippet in #Scala Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Burlesque
Burlesque
  "Hello, world!"<-  
Give a code snippet in #Burlesque Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string E...
christopher/rosetta-code
http://rosettacode.org/wiki/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules: ...
#ALGOL_68
ALGOL 68
BEGIN # rock/paper/scissors game # # counts of the number of times the player has chosen each move # # we initialise each to 1 so that the total isn't zero when we are # # choosing the computer's first move (as in the Ada version) # IN...
Give a code snippet in #ALGOL_68 Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The win...
christopher/rosetta-code
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
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 |...
#Oforth
Oforth
tvar: A 10 to A   tvar: B #A to B B .s [1] (Variable) #A >ok   12 B put A .s [1] (Integer) 12 [2] (Variable) #A >ok
Give a code snippet in #Oforth Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code
http://rosettacode.org/wiki/OpenGL
OpenGL
Task Display a smooth shaded triangle with OpenGL. Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
#R
R
library(rgl) x <- c(-1, -1, 1) y <- c(0, -1, -1) z <- c(0, 0, 0) M <- cbind(x,y,z) rgl.bg(color="gray15") triangles3d(M, col=rainbow(8))
Give a code snippet in #R Task Display a smooth shaded triangle with OpenGL. Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
christopher/rosetta-code
http://rosettacode.org/wiki/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#REXX
REXX
/*REXX program finds the LCM (Least Common Multiple) of any number of integers. */ numeric digits 10000 /*can handle 10k decimal digit numbers.*/ say 'the LCM of 19 and 0 is ───► ' lcm(19 0 ) say 'the LCM of 0 and 85 ...
Give a code snippet in #REXX Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has ...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#Delphi
Delphi
func isPerfect(num) { var sum = 0 for i in 1..<num { if !i { break } if num % i == 0 { sum += i } } return sum == num }   let max = 33550337 print("Perfect numbers from 0 to \(max):")   for x in 0..max { if isPerfect(x) { print("\(x) is...
Give a code snippet in #Delphi Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itsel...
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...
#Vlang
Vlang
fn main() { // make empty map mut my_map := map[string]int{}   //s et value my_map['foo'] = 3   // getting values y1 := my_map['foo']   // remove keys my_map.delete('foo')   // make map with values my_map = { 'foo': 2 'bar': 42 'baz': -1 } }
Give a code snippet in #Vlang Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the objec...
#Visual_Basic_.NET
Visual Basic .NET
Module Program Iterator Function IntegerPowers(exp As Integer) As IEnumerable(Of Integer) Dim i As Integer = 0 Do Yield CInt(Math.Pow(i, exp)) i += 1 Loop End Function   Function Squares() As IEnumerable(Of Integer) Return IntegerPowers(2) End Func...
Give a code snippet in #Visual_Basic_.NET A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or obje...
christopher/rosetta-code
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#Transd
Transd
#lang transd   MainModule: { _start: (λ (with files ["a.txt" "b.txt" "c.txt"] fs FileStream() (for f in files do (open-r fs f) (with s (replace (read-text fs) "Goodbye London!" "Hello New York!") (close fs) ...
Give a code snippet in #Transd Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#ML.2FI
ML/I
MCSET S4=1 MCNOTE Goodbye, World!
Give a code snippet in #ML.2FI Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out...
christopher/rosetta-code
http://rosettacode.org/wiki/Ascending_primes
Ascending primes
Generate and show all primes with strictly ascending decimal digits. Aside: Try solving without peeking at existing solutions. I had a weird idea for generating a prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial but generating them quickly is at least mildly interesting. T...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ps=Sort@Select[FromDigits /@ Subsets[Range@9, {1, \[Infinity]}], PrimeQ]; Multicolumn[ps, {Automatic, 6}, Appearance -> "Horizontal"]
Give a code snippet in #Mathematica.2FWolfram_Language Generate and show all primes with strictly ascending decimal digits. Aside: Try solving without peeking at existing solutions. I had a weird idea for generating a prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial but g...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindromic_gapful_numbers
Palindromic gapful numbers
Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numbers. Evenly divisible   mea...
#Nim
Nim
Forms palindromes using number<->string conversions.
Give a code snippet in #Nim Palindromic gapful numbers You are encouraged to solve this task according to the task description, using any language you may know. Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the first and last digit are known as   gapful numb...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle/Graphical
Sierpinski triangle/Graphical
Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
#Go
Go
package main   import ( "fmt" "image" "image/color" "image/draw" "image/png" "os" )   func main() { const order = 8 const width = 1 << order const margin = 10 bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin) im := image.NewGray(bounds) gBlack := colo...
Give a code snippet in #Go Produce a graphical representation of a Sierpinski triangle of order N in any orientation. An example of Sierpinski's triangle (order = 8) looks like this:
christopher/rosetta-code
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Objeck
Objeck
  use Gtk2;   bundle Default { class GtkHello { function : Main(args : String[]) ~ Nil { window := GtkWindow->New(); delete_callback := Events->DeleteEvent(GtkWidget) ~ Nil; window->SignalConnect(Signal->Destroy, window->As(GtkWidget), delete_callback); window->SetTitle("Title"); win...
Give a code snippet in #Objeck Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#XPL0
XPL0
string 0; \use zero-terminated strings code CrLf=9, IntOut=11;   func Roman(Str); \Convert Roman numeral string to decimal value char Str; int I, Val, Val0, Sum; [I:= 0; Sum:= 0; Val0:= 5000; loop [case Str(I) of ^M: Val:= 1000; ^D: Val:= 500; ^C:...
Give a code snippet in #XPL0 Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, sta...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#Liberty_BASIC
Liberty BASIC
dim d(4) input "Enter 4 digits: "; a$ nD=0 for i =1 to len(a$) c$=mid$(a$,i,1) if instr("123456789",c$) then nD=nD+1 d(nD)=val(c$) end if next 'for i = 1 to 4 ' print d(i); 'next   'precompute permutations. Dumb way. nPerm = 1*2*3*4 dim perm(nPerm, 4) n = 0 for i = 1 to 4 for j = 1 to...
Give a code snippet in #Liberty_BASIC task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#GAP
GAP
1 < 2; # true   2 < 1; # false   # GAP has also the value fail, which cannot be used as a boolean but may be used i$   1 = fail; # false   fail = fail; # true
Give a code snippet in #GAP Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
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...
#C.2B.2B
C++
#include <string> #include <iostream>   using namespace std;   string Suffix(int num) { switch (num % 10) { case 1 : if(num % 100 != 11) return "st"; break; case 2 : if(num % 100 != 12) return "nd"; break; case 3 : if(num % 100 != 13) return "rd"; }   return...
Give a code snippet in #C.2B.2B Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to sh...
christopher/rosetta-code
http://rosettacode.org/wiki/Honeycombs
Honeycombs
The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position...
#Liberty_BASIC
Liberty BASIC
  NoMainWin Dim hxc(20,2), ltr(26) Global sw, sh, radius, radChk, mx, my, h$, last h$="#g": radius = 40: radChk = 35 * 35: last = 0 sw = 400: sh = 380: WindowWidth = sw+6: WindowHeight= sh+32 Open "Liberty BASIC - Honeycombs" For graphics_nsb_nf As #g #g "Down; Cls; TrapClose xit"   Call shuffle Call grid 75, 15, "0 0 ...
Give a code snippet in #Liberty_BASIC The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in colum...
christopher/rosetta-code
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#Haskell
Haskell
import Data.PQueue.Prio.Min   main = print (toList (fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")]))
Give a code snippet in #Haskell A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Primes_-_allocate_descendants_to_their_ancestors
Primes - allocate descendants to their ancestors
The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'. The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance. This solution could be compared to the solution that would use the decomposition into primes for all the numbers betw...
#Simula
Simula
COMMENT cim --memory-pool-size=512 allocate-descendants-to-their-ancestors.sim ; BEGIN     COMMENT ABSTRACT FRAMEWORK CLASSES ;   CLASS ITEM; BEGIN END ITEM;   CLASS ITEMLIST; BEGIN   CLASS ITEMARRAY(N); INTEGER N; BEGIN REF(ITEM) ARRAY DATA(0:N-1); END ITEMARRAY;   ...
Give a code snippet in #Simula The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'. The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance. This solution could be compared to the solution that would use the decomposition into...
christopher/rosetta-code
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced...
#XPL0
XPL0
int I, Size, FD; char C, FN(80), Array; [I:= 0; \get file name from command line loop [C:= ChIn(8); if C = $20 \space\ then quit; FN(I):= C; I:= I+1; ]; FN(I):= 0; Size:= IntIn(8); \get number of bytes from command line if Size = 0 then [Text(0, "Length n...
Give a code snippet in #XPL0 Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating...
christopher/rosetta-code
http://rosettacode.org/wiki/Nonogram_solver
Nonogram solver
A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs of occupied cells. Using only...
#11l
11l
F gen_row(w, s) ‘Create all patterns of a row or col that match given runs.’ F gen_seg([[Int]] o, Int sp) -> [[Int]] I o.empty R [[2] * sp] [[Int]] r L(x) 1 .< sp - o.len + 2 L(tail) @gen_seg(o[1..], sp - x) r [+]= [2] * x [+] o[0] [+] tail R r   R gen_seg(...
Give a code snippet in #11l A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs ...
christopher/rosetta-code
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey se...
#Yabasic
Yabasic
// Rosetta Code problem: https://rosettacode.org/wiki/Farey_sequence // by Jjuanhdez, 06/2022   for i = 1 to 11 print "F", i, " = "; farey(i, FALSE) next i print for i = 100 to 1000 step 100 print "F", i; if i <> 1000 then print " "; else print ""; : fi print " = "; farey(i, FALSE) next i end  ...
Give a code snippet in #Yabasic The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a...
christopher/rosetta-code
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#PARI.2FGP
PARI/GP
Eratosthenes(lim)={ my(v=Vecsmall(lim\1,unused,1)); forprime(p=2,sqrt(lim), forstep(i=p^2,lim,p, v[i]=0 ) ); for(i=1,lim,if(v[i],print1(i", "))) };
Give a code snippet in #PARI.2FGP This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes...
christopher/rosetta-code
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#D
D
  import openldap; import std.stdio;   void main() { auto ldap = LDAP("ldap://localhost"); auto r = ldap.search_s("dc=example,dc=com", LDAP_SCOPE_SUBTREE, "(uid=%s)".format("test")); int b = ldap.bind_s(r[0].dn, "password"); scope(exit) ldap.unbind; if (b) { writeln("error on binding"); return; } ...
Give a code snippet in #D The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
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...
#MAXScript
MAXScript
s = "hello" print (s + " literal") s1 = s + " literal" print s1
Give a code snippet in #MAXScript 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/Square_but_not_cube
Square but not cube
Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
#Commodore_BASIC
Commodore BASIC
100 DIM SC(2): SC = 0: REM REMEMBER SQUARE CUBES 110 PRINT "SQUARES BUT NOT CUBES:" 120 N = 0: REM NUMBER OF NON-CUBE SQUARES FOUND 130 SR = 1: REM CURRENT SQUARE ROOT 140 CR = 1: CU = 1: REM CURRENT CUBE ROOT AND CUBE 150 REM BEGIN LOOP 160 : IF N >= 30 THEN 230 170 : SQ = SR * SR 180 : IF SQ > CU THEN CR = CR + 1: ...
Give a code snippet in #Commodore_BASIC Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
christopher/rosetta-code
http://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response
Keyboard input/Obtain a Y or N response
Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need t...
#Ada
Ada
function Yes_Or_No (Prompt : String := "Your answer (Y/N): ") return Boolean is Answer : Character; begin Ada.Text_IO.Put (Prompt); loop Ada.Text_IO.Get_Immediate (Answer); case Answer is when 'Y'|'y' => return True; when 'N'|'n' => return False; ...
Give a code snippet in #Ada Task Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#F.23
F#
open System   [<EntryPoint>] let main _ = let maxIt = 13 let maxItJ = 10 let mutable a1 = 1.0 let mutable a2 = 0.0 let mutable d1 = 3.2 Console.WriteLine(" i d") for i in 2 .. maxIt do let mutable a = a1 + (a1 - a2) / d1 for j in 1 .. maxItJ do let mutable ...
Give a code snippet in #F.23 Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#MAD
MAD
NORMAL MODE IS INTEGER BOOLEAN FOUND FOUND = 0B   R SEQUENCE OF NON-SQUARES FORMULA R FLOOR IS AUTOMATIC DUE TO INTEGER MATH INTERNAL FUNCTION NONSQR.(N) = N+(.5+SQRT.(N))   R PRINT VALUES FOR 1..N..22 THROUGH SHOW, FO...
Give a code snippet in #MAD Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037 ...
christopher/rosetta-code
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:...
#Phix
Phix
$string = "The quick brown fox jumped over the lazy dog's back"; echo md5( $string );
Give a code snippet in #Phix Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the W...
christopher/rosetta-code
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#C.23
C#
using System; using System.IO; // Needed for the method. using System.Text.RegularExpressions; using System.Collections.Generic;   void Main() { string blocks = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM"; List<string> words = new List<string>() { "A", "BARK", "BOOK", "TREAT", "COMMON", "S...
Give a code snippet in #C.23 ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet...
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 ...
#ActionScript
ActionScript
public function ackermann(m:uint, n:uint):uint { if (m == 0) { return n + 1; } if (n == 0) { return ackermann(m - 1, 1); }   return ackermann(m - 1, ackermann(m, n - 1)); }
Give a code snippet in #ActionScript 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/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually...
#Delphi
Delphi
  program List_monad;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type TmList = record Value: TArray<Integer>; function ToString: string; function Bind(f: TFunc<TArray<Integer>, TmList>): TmList; end;   function Create(aValue: TArray<Integer>): TmList; begin Result.Value := copy(aValue, 0, length...
Give a code snippet in #Delphi A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically ...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#M4
M4
define(`BOTTLES', `bottles of beer')dnl define(`BOTTLE', `bottle of beer')dnl define(`WALL', `on the wall')dnl define(`TAKE', `take one down, pass it around')dnl define(`NINETEEN', `$1 ifelse(`$1',`1',BOTTLE,BOTTLES) WALL $1 ifelse(`$1',`1',BOTTLE,BOTTLES) ifelse(`$1',`0',,`TAKE') ifelse(`$1',`0',,`NINETEEN(eval($1-1))...
Give a code snippet in #M4 Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bo...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort
Sorting algorithms/Radix 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 ...
#C.23
C#
using System;   namespace RadixSort { class Program { static void Sort(int[] old) { int i, j; int[] tmp = new int[old.Length]; for (int shift = 31; shift > -1; --shift) { j = 0; for (i = 0; i < old.Length; ++i) ...
Give a code snippet in #C.23 Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Optional_parameters
Optional parameters
Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicographic by default. column ...
#Wren
Wren
import "./sort" for Cmp, Sort import "./seq" for Lst   class TableSorter { // uses 'merge' sort to avoid mutating original table // column is zero based static sort(table, ordering, column, reverse) { if (ordering == null) ordering = Fn.new { |r1, r2| Cmp.string.call(r1[column], r2[column]) } var...
Give a code snippet in #Wren Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexi...
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...
#Lua
Lua
function splittokens(s) local res = {} for w in s:gmatch("%S+") do res[#res+1] = w end return res end   function textwrap(text, linewidth) if not linewidth then linewidth = 75 end   local spaceleft = linewidth local res = {} local line = {}   for _, word in ipairs...
Give a code snippet in #Lua 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/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#OCaml
OCaml
open Complex   let pi = 4. *. atan 1.   let () = for n = 1 to 10 do Printf.printf "%2d " n; for k = 1 to n do let ret = polar 1. (2. *. pi *. float_of_int k /. float_of_int n) in Printf.printf "(%f + %f i)" ret.re ret.im done; print_newline () done
Give a code snippet in #OCaml The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" o...
#Huginn
Huginn
#! /bin/sh exec huginn --no-argv -E "${0}" #! huginn   main() { c = "#! /bin/sh{1}~" "exec huginn --no-argv -E {3}${{0}}{3}{1}#! huginn{1}{1}~" "main() {{{1}{2}c = {3}{0}{3};{1}~" "{2}s = {3}{3};{1}~" "{2}while ( ( line = input() ) != none ) {{{1}~" "{2}{2}s += line;{1}~" "{2}}}{1}~" "{2}self = copy( c )...
Give a code snippet in #Huginn Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and p...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Haskell
Haskell
import Data.Char (toUpper)   import Data.Maybe (fromMaybe)   import Text.Printf (PrintfType, printf)   dirs :: [String] dirs = [ "N" , "NbE" , "N-NE" , "NEbN" , "NE" , "NEbE" , "E-NE" , "EbN" , "E" , "EbS" , "E-SE" , "SEbE" , "SE" , "SEbS" , "S-SE" , "SbE" , "S" , "SbW" , "S-SW" ...
Give a code snippet in #Haskell 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#Object_Pascal
Object Pascal
unit Multiplication; interface   function Double(Number: Integer): Integer; function Halve(Number: Integer): Integer; function Even(Number: Integer): Boolean; function Ethiopian(NumberA, NumberB: Integer): Integer;   implementation function Double(Number: Integer): Integer; begin result := Number * 2 end;   ...
Give a code snippet in #Object_Pascal Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainder...
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: * * * * * * * * * * * * * * * ...
#Vedit_macro_language
Vedit macro language
#3 = 16 // size (height) of the triangle Buf_Switch(Buf_Free) // Open a new buffer for output Ins_Char(' ', COUNT, #3*2+2) // fill first line with spaces Ins_Newline Line(-1) Goto_Col(#3) Ins_Char('*', OVERWRITE) // the top of triangle for (#10=0; #10 < #3-1; #10++) { BOL Reg_Copy(9,1) Reg_Ins(9) // dupl...
Give a code snippet in #Vedit_macro_language 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/Zeckendorf_arithmetic
Zeckendorf arithmetic
This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions. Addition Like bin...
#C.23
C#
using System; using System.Text;   namespace ZeckendorfArithmetic { class Zeckendorf : IComparable<Zeckendorf> { private static readonly string[] dig = { "00", "01", "10" }; private static readonly string[] dig1 = { "", "1", "10" };   private int dVal = 0; private int dLen = 0;   ...
Give a code snippet in #C.23 This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negat...
#BCPL
BCPL
get "libhdr" manifest $( MAXLEN = 256/BYTESPERWORD $)   let append(v1, v2) be $( for i=1 to v2%0 do v1%(v1%0+i) := v2%i v1%0 := v1%0 + v2%0 $)   let spell(n, v) = valof $( let small(n) = n=0 -> "", n=1 -> "one", n=2 -> "two", n=3 -> "three", n=4 -> "four", n=5 ->...
Give a code snippet in #BCPL Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than posit...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Python
Python
python -c 'import sys; sys.stdout.write(sys.stdin.read())'
Give a code snippet in #Python Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
christopher/rosetta-code
http://rosettacode.org/wiki/Long_year
Long year
Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
#Logo
Logo
to div :x :y output int quotient :x :y end   to dec31_weekday :year output remainder (sum :year div :year 4 div :year -100 div :year 400) 7 end   to iso_long_year? :year output or 4 = dec31_weekday :year 3 = dec31_weekday difference :year 1 end   for [y 1995 2045 1] [if iso_long_year? :y [print :y]]
Give a code snippet in #Logo Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#Frink
Frink
  include resources "SomeImage.png" include resources "SomeMovie.mpeg" include resources "SomeSound.aiff" include resources "SomeIcon.icns" include resources "Info.plist" //Custom preference file to replace FB's generic app preferences  
Give a code snippet in #Frink Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/Host_introspection
Host introspection
Print the word size and endianness of the host machine. See also: Variable size/Get
#C.23
C#
static void Main() { Console.WriteLine("Word size = {0} bytes,",sizeof(int));   if (BitConverter.IsLittleEndian) Console.WriteLine("Little-endian."); else Console.WriteLine("Big-endian."); }
Give a code snippet in #C.23 Print the word size and endianness of the host machine. See also: Variable size/Get
christopher/rosetta-code
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#jq
jq
  1 | exp # i.e. e 1 | atan * 4 # i.e. π sqrt log # Naperian log exp length # absolute value if the argument is numeric floor ceil # requires jq >= 1.5 pow(x; y) # requires jq >= 1.5
Give a code snippet in #jq Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magn...
christopher/rosetta-code
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ...
#Prolog
Prolog
:- use_module(library(clpfd)).   self_describling :- forall(between(1, 10, I), (findall(N, self_describling(I,N), L), format('Len ~w, Numbers ~w~n', [I, L]))).   % search of the self_describling numbers of a given len self_describling(Len, N) :- length(L, Len), Len1 is Len - 1, L = [H|T],   % the first f...
Give a code snippet in #Prolog Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when d...
christopher/rosetta-code