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/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#Icon_and_Unicon
Icon and Unicon
procedure main(A) mode := A[1] if \mode then system("xrandr -s " || \mode || " >/dev/null") else system("xrandr -q") # Display available modes end
Give a code snippet in #Icon_and_Unicon The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
christopher/rosetta-code
http://rosettacode.org/wiki/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:...
#Factor
Factor
USING: kernel strings io checksums checksums.md5 ; "The quick brown fox jumps over the lazy dog" md5 checksum-bytes hex-string print
Give a code snippet in #Factor Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Excel
Excel
asciiTable =LAMBDA(i, justifyRight(3)(" ")(i) & ": " & ( justifyRight( 3 )(" ")( IF(32 = i, "Spc", IF(127 = i, "Del", CHAR(i) ) ) ) ) )( SEQUENCE(16, 6, 32, 1) )
Give a code snippet in #Excel 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Nested_templated_data
Nested templated data
A template for data is an arbitrarily nested tree of integer indices. Data payloads are given as a separate mapping, array or other simpler, flat, association of indices to individual items of data, and are strings. The idea is to create a data structure with the templates' nesting, and the payload corresponding to e...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
t = ToExpression[StringReplace["[[[1,2],[3,4,1],5]]", {"[" -> "{", "]" -> "}"}]]; p = "Payload#" <> ToString[#] & /@ Range[6]; Map[p[[#]] &, t, {-1}]
Give a code snippet in #Mathematica.2FWolfram_Language A template for data is an arbitrarily nested tree of integer indices. Data payloads are given as a separate mapping, array or other simpler, flat, association of indices to individual items of data, and are strings. The idea is to create a data structure with th...
christopher/rosetta-code
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#Modula-2
Modula-2
MODULE Catamorphism; FROM InOut IMPORT WriteString, WriteCard, WriteLn;   (* Alas, there are no generic types. This function works for CARDINAL only - you would have to copy it and change the types to reduce functions of other types. *) TYPE Reduction = PROCEDURE (CARDINAL, CARDINAL): CARDINAL; PROCEDURE reduce(f...
Give a code snippet in #Modula-2 Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language....
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Slate
Slate
Dictionary new*, 'MI' -> 'Michigan', 'MN' -> 'Minnesota'
Give a code snippet in #Slate 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/Web_scraping
Web scraping
Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page. If possible,...
#Erlang
Erlang
-module(scraping). -export([main/0]). -define(Url, "http://tycho.usno.navy.mil/cgi-bin/timer.pl"). -define(Match, "<BR>(.+ UTC)").   main() -> inets:start(), {ok, {_Status, _Header, HTML}} = httpc:request(?Url), {match, [Time]} = re:run(HTML, ?Match, [{capture, all_but_first, binary}]), io:format("~s~n",[Time])...
Give a code snippet in #Erlang Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this p...
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#OCaml
OCaml
let rec seeAndSay = function | [], nys -> List.rev nys | x::xs, [] -> seeAndSay(xs, [x; 1]) | x::xs, y::n::nys when x=y -> seeAndSay(xs, y::1+n::nys) | x::xs, nys -> seeAndSay(xs, x::1::nys)
Give a code snippet in #OCaml The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence...
christopher/rosetta-code
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#FunL
FunL
import io.File   for f <- sort( list(File( "." ).list()).filterNot(s -> s.startsWith(".")) ) println( f )
Give a code snippet in #FunL Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#PureBasic
PureBasic
Procedure Saludo() PrintN("Hola mundo!") EndProcedure   Procedure.s Copialo(txt.s, siNo.b, final.s = "") Define nuevaCadena.s, resul.s   For cont.b = 1 To siNo nuevaCadena + txt Next   Resul = Trim(nuevaCadena) + final   ProcedureReturn resul EndProcedure   Procedure testNumeros(a.i, b.i, c.i = 0) Pri...
Give a code snippet in #PureBasic Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable...
#Delphi
Delphi
  program Increment_loop_index_within_loop_body;   {$APPTYPE CONSOLE}   uses System.SysUtils;   function IsPrime(const a: UInt64): Boolean; var d: UInt64; begin if (a < 2) then exit(False);   if (a mod 2) = 0 then exit(a = 2);   if (a mod 3) = 0 then exit(a = 3);   d := 5;   while (d * d <= a)...
Give a code snippet in #Delphi Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which...
christopher/rosetta-code
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribut...
#Hy
Hy
(import [scipy.stats [chisquare]] [collections [Counter]])   (defn uniform? [f repeats &optional [alpha .05]] "Call 'f' 'repeats' times and do a chi-squared test for uniformity of the resulting discrete distribution. Return false iff the null hypothesis of uniformity is rejected for the test with size 'alph...
Give a code snippet in #Hy Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean t...
christopher/rosetta-code
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language...
#Sather
Sather
class MAIN is main is dog ::= "Benjamin"; Dog ::= "Samba"; DOG ::= "Bernie"; #OUT + #FMT("The three dogs are %s, %s and %s\n", dog, Dog, DOG); end; end;
Give a code snippet in #Sather Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, S...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#Perl
Perl
use Gtk3 '-init';   my $window = Gtk3::Window->new(); $window->set_default_size(320, 240); $window->set_border_width(10); $window->set_title("Draw a Pixel"); $window->set_app_paintable(TRUE);   my $da = Gtk3::DrawingArea->new(); $da->signal_connect('draw' => \&draw_in_drawingarea); $window->add($da); $window->show_all(...
Give a code snippet in #Perl Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
christopher/rosetta-code
http://rosettacode.org/wiki/Idiomatically_determine_all_the_characters_that_can_be_used_for_symbols
Idiomatically determine all the characters that can be used for symbols
Idiomatically determine all the characters that can be used for symbols. The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to name, ...
#Raku
Raku
sub postfix:<𒋦>($n) { say "$n trilobites" }   sub term:<𝍧> { unival('𝍧') }   𝍧𒋦
Give a code snippet in #Raku Idiomatically determine all the characters that can be used for symbols. The word symbols is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer p...
christopher/rosetta-code
http://rosettacode.org/wiki/Latin_Squares_in_reduced_form
Latin Squares in reduced form
A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin S...
#Go
Go
package main   import ( "fmt" "sort" )   type matrix [][]int   // generate derangements of first n numbers, with 'start' in first place. func dList(n, start int) (r matrix) { start-- // use 0 basing a := make([]int, n) for i := range a { a[i] = i } a[0], a[start] = start, a[0] so...
Give a code snippet in #Go A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element withi...
christopher/rosetta-code
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149....
#Nim
Nim
import gnuplot   let x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]   plot(x, y, "Coordinate pairs") discard stdin.readChar # Needed as when the program exits, “gnuplot” is closed.
Give a code snippet in #Nim Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 5...
christopher/rosetta-code
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute z...
#Lua
Lua
function convert_temp(k) local c = k - 273.15 local r = k * 1.8 local f = r - 459.67 return k, c, r, f end   print(string.format([[ Kelvin: %.2f K Celcius: %.2f °C Rankine: %.2f °R Fahrenheit: %.2f °F ]],convert_temp(21.0)))
Give a code snippet in #Lua There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 ke...
christopher/rosetta-code
http://rosettacode.org/wiki/Determinant_and_permanent
Determinant and permanent
For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the permanent is given by ...
#jq
jq
# Eliminate row i and row j def except(i;j): reduce del(.[i])[] as $row ([]; . + [$row | del(.[j]) ] );   def det: def parity(i): if i % 2 == 0 then 1 else -1 end; if length == 1 and (.[0] | length) == 1 then .[0][0] else . as $m | reduce range(0; length) as $i (0; . + parity($i) * $m[0][$i] * ( $m ...
Give a code snippet in #jq For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#EchoLisp
EchoLisp
  (define (A xs) (// (for/sum ((x xs)) x) (length xs)))   (define (G xs) (expt (for/product ((x xs)) x) (// (length xs))))   (define (H xs) (// (length xs) (for/sum ((x xs)) (// x))))   (define xs (range 1 11)) (and (>= (A xs) (G xs)) (>= (G xs) (H xs))) → #t  
Give a code snippet in #EchoLisp Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\...
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...
#PARI.2FGP
PARI/GP
toGray(n)=bitxor(n,n>>1); fromGray(n)=my(k=1,m=n);while(m>>k,n=bitxor(n,n>>k);k+=k);n; bin(n)=concat(apply(k->Str(k),binary(n)))   for(n=0,31,print(n"\t"bin(n)"\t"bin(g=toGray(n))"\t"fromGray(g)))
Give a code snippet in #PARI.2FGP 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 m...
christopher/rosetta-code
http://rosettacode.org/wiki/Reflection/Get_source
Reflection/Get source
Task The goal is to get the source code or file path and line number where a programming object (e.g. module, class, function, method) is defined.
#Raku
Raku
say &sum.file; say Date.^find_method("day-of-week").file;
Give a code snippet in #Raku Task The goal is to get the source code or file path and line number where a programming object (e.g. module, class, function, method) is defined.
christopher/rosetta-code
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the...
#Swift
Swift
import Foundation   func encode(_ scalar: UnicodeScalar) -> Data { return Data(String(scalar).utf8) }   func decode(_ data: Data) -> UnicodeScalar? { guard let string = String(data: data, encoding: .utf8) else { assertionFailure("Failed to convert data to a valid String") return nil } assert(string.unic...
Give a code snippet in #Swift As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes rep...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#C.23
C#
System.IO.File.WriteAllText("filename.txt", "This file contains a string.");
Give a code snippet in #C.23 Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
christopher/rosetta-code
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#Yabasic
Yabasic
5 REM Adaptation to Yabasic of the program published in Tim Hartnell's book "Artificial Intelligence: Concepts and Programs", with some minor modifications. 6/2018. 10 REM TICTAC 15 INPUT "English (0), Spanish (other key): " IDIOMA : IF NOT IDIOMA THEN RESTORE 2020 ELSE RESTORE 2010 END IF 20 GOSUB 1180: REM INICIALIZA...
Give a code snippet in #Yabasic Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorl...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#OpenEdge.2FProgress
OpenEdge/Progress
DEF VAR dcResult AS DECIMAL NO-UNDO. DEF VAR n AS INT NO-UNDO.   DO n = 1 TO 1000 : dcResult = dcResult + 1 / (n * n) . END.   DISPLAY dcResult .
Give a code snippet in #OpenEdge.2FProgress Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n...
christopher/rosetta-code
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#UNIX_Shell
UNIX Shell
#!/usr/bin/env bash # play tic-tac-toe main() { local play_again=1 while (( play_again )); do local board=(1 2 3 4 5 6 7 8 9) tokens=(X O) show_board "${board[@]}" # player colors: computer is red, human is green local computer=31 human=32 if (( RANDOM % 2 )); then players=(computer human)...
Give a code snippet in #UNIX_Shell Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathW...
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
#Ursa
Ursa
import "filename.u"
Give a code snippet in #Ursa 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/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identif...
#LiveCode
LiveCode
put 1 into Δ add 1 to Δ put Δ -- result is 2
Give a code snippet in #LiveCode Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related t...
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.
#Run_BASIC
Run BASIC
print shell$("dir") ' shell out to the os and print it
Give a code snippet in #Run_BASIC The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
christopher/rosetta-code
http://rosettacode.org/wiki/Same_fringe
Same fringe
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is allowed here, but many compu...
#Java
Java
import java.util.*;   class SameFringe { public interface Node<T extends Comparable<? super T>> { Node<T> getLeft(); Node<T> getRight(); boolean isLeaf(); T getData(); }   public static class SimpleNode<T extends Comparable<? super T>> implements Node<T> { private final T data; public ...
Give a code snippet in #Java Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution i...
christopher/rosetta-code
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#REBOL
REBOL
rebol [ Title: "Variadic Arguments" ]   print-all: func [ args [block!] {the arguments to print} ] [ foreach arg args [print arg] ]   print-all [rebol works this way]
Give a code snippet in #REBOL Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. R...
christopher/rosetta-code
http://rosettacode.org/wiki/Arena_storage_pool
Arena storage pool
Dynamically allocated objects take their memory from a heap. The memory for an object is provided by an allocator which maintains the storage pool used for the heap. Often a call to allocator is denoted as P := new T where   T   is the type of an allocated object,   and   P   is a reference to the object. The stora...
#Nim
Nim
  #################################################################################################### # Pool management.   # Pool of objects. type Block[Size: static Positive, T] = ref array[Size, T] Pool[BlockSize: static Positive, T] = ref object blocks: seq[Block[BlockSize, T]] # List of blocks. ...
Give a code snippet in #Nim Dynamically allocated objects take their memory from a heap. The memory for an object is provided by an allocator which maintains the storage pool used for the heap. Often a call to allocator is denoted as P := new T where   T   is the type of an allocated object,   and   P   is a refere...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Traversal
Singly-linked list/Traversal
Traverse from the beginning of a singly-linked list to the end. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked ...
#Java
Java
LinkedList<Type> list = new LinkedList<Type>();   for(Type i: list){ //each element will be in variable "i" System.out.println(i); }
Give a code snippet in #Java Traverse from the beginning of a singly-linked list to the end. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definiti...
christopher/rosetta-code
http://rosettacode.org/wiki/Topic_variable
Topic variable
Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate h...
#Phix
Phix
with javascript_semantics object _ _ = 3 ?_ ?_*_
Give a code snippet in #Phix Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic variable within the languag...
christopher/rosetta-code
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the s...
#zkl
zkl
fcn properDivs(n){ [1.. (n + 1)/2 + 1].filter('wrap(x){ n%x==0 and n!=x }) } fcn aliquot(k){ //-->Walker Walker(fcn(rk){ k:=rk.value; if(k)rk.set(properDivs(k).sum()); k }.fp(Ref(k))) }(10).walk(15).println();
Give a code snippet in #zkl An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications f...
christopher/rosetta-code
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla...
#C_sharp
C_sharp
using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace RosettaCode { class Program { static void QuickSort(IComparable[] elements, int left, int right) { int i = left, j = right; IComparable pivot = elements[left + (right - left)...
Give a code snippet in #C_sharp The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Line_printer
Hello world/Line printer
Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be...
#Simula
Simula
BEGIN OUTTEXT("Hello World!"); OUTIMAGE END
Give a code snippet in #Simula Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With som...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Dc
Dc
[ I ~ S! d 0!=S L! + ] sS   1 lS x p 1234 lS x p 16 i FE lS x p F0E lS x p
Give a code snippet in #Dc Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
christopher/rosetta-code
http://rosettacode.org/wiki/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ...
#Kotlin
Kotlin
// version 1.0.5-2   @Suppress("DIVISION_BY_ZERO", "FLOAT_LITERAL_CONFORMS_ZERO")   fun main(args: Array<String>) { val inf = 1.0 / 0.0 val negInf = -1.0 / 0.0 val nan = 0.0 / 0.0 val negZero = -1.0e-325   println("*** Indirect ***\n") println("Infinity  : $inf") println(...
Give a code snippet in #Kotlin The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_letter-first_letter
Last letter-first letter
A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the category, they fall out of the ga...
#Java
Java
// derived from C final class LastLetterFirstLetter { static int maxPathLength = 0; static int maxPathLengthCount = 0; static final StringBuffer maxPathExample = new StringBuffer(500);   static final String[] names = {"audino", "bagon", "baltoy", "banette", "bidoof", "braviary", "bronzor", "carr...
Give a code snippet in #Java A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the cat...
christopher/rosetta-code
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Scala
Scala
scala> new java.io.File("/").listFiles.sorted.foreach(println) /bin /boot /core /dev /etc /home /lib /lib64 /local /lost+found /media /mnt /opt /proc /root /run /sbin /selinux /srv /sys /tmp /user /usr /var
Give a code snippet in #Scala Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Exampl...
christopher/rosetta-code
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#Elixir
Elixir
a = <<"a = ~p~n:io.fwrite(a,[a])~n">> :io.fwrite(a,[a])
Give a code snippet in #Elixir A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. 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 Write a function to compute the arithmetic-geomet...
#AutoHotkey
AutoHotkey
agm(a, g, tolerance=1.0e-15){ While abs(a-g) > tolerance { an := .5 * (a + g) g := sqrt(a*g) a := an } return a } SetFormat, FloatFast, 0.15 MsgBox % agm(1, 1/sqrt(2))
Give a code snippet in #AutoHotkey This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. 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 Write a funct...
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. ...
#MACRO-10
MACRO-10
  TITLE DIRWLK - Directory Walker SUBTTL PDP-10 Assembly Language (MACRO-10 @ TOPS-20). KJX 2022.   SEARCH MONSYM,MACSYM  ;Get system-call names. .REQUIRE SYS:MACREL  ;Macros: TMSG, EJSHLT, etc.   STDAC.  ;Define standard register nam...
Give a code snippet in #MACRO-10 Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single director...
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...
#XPL0
XPL0
char Col;   func ColNum(Start, Piece); \Return column number of Piece int Start, Piece, I; [for I:= Start to 7 do if Col(I) = Piece then return I; return -1; ];   proc Shuffle; \Randomly rearrange pieces in columns int I, J, T; [for I:= 8-1 downto 1 do [J:= Ran(I); \range [0..I-1] (Sattol...
Give a code snippet in #XPL0 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#Visual_Basic_.NET
Visual Basic .NET
Dim x = 1024 Do Console.WriteLine(x) x = x \ 2 Loop While x > 0
Give a code snippet in #Visual_Basic_.NET Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   L...
christopher/rosetta-code
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#PARI.2FGP
PARI/GP
rot13(s)={ s=Vecsmall(s); for(i=1,#s, if(s[i]>109&s[i]<123,s[i]-=13,if(s[i]<110&s[i]>96,s[i]+=13,if(s[i]>77&s[i]<91,s[i]-=13,if(s[i]<78&s[i]>64,s[i]+=13)))) ); Strchr(s) };
Give a code snippet in #PARI.2FGP Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line ro...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler%27s_identity
Euler's identity
This page uses content from Wikipedia. The original article was at Euler's_identity. 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 mathematics, Euler's identity is the equality: ...
#Nim
Nim
import math, complex   echo "exp(iπ) + 1 = ", exp(complex(0.0, PI)) + 1, " ~= 0"
Give a code snippet in #Nim This page uses content from Wikipedia. The original article was at Euler's_identity. 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 mathematics, Euler's identity is...
christopher/rosetta-code
http://rosettacode.org/wiki/Determinant_and_permanent
Determinant and permanent
For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the permanent is given by ...
#Julia
Julia
using LinearAlgebra
Give a code snippet in #Julia For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while t...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#min
min
"Goodbye, World!" print
Give a code snippet in #min Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standar...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#AutoHotkey
AutoHotkey
MsgBox % factor(8388607) ; 47 * 178481   factor(n) { if (n = 1) return f = 2 while (f <= n) { if (Mod(n, f) = 0) { next := factor(n / f) return, % f "`n" next } f++ } }
Give a code snippet in #AutoHotkey The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /...
#C.2B.2B
C++
/* Using the Qt library's XML parser. */ #include <iostream>   #include <QDomDocument> #include <QObject>   int main() { QDomDocument doc;   doc.setContent( QObject::tr( "<Students>\n" "<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n" "<Student Name=\"Bo...
Give a code snippet in #C.2B.2B Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gende...
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...
#BASIC256
BASIC256
n = int(rand * 10) + 1 print "I am thinking of a number from 1 to 10" do input "Guess it > ",g if g <> n then print "No luck, Try again." endif until g = n print "Yea! You guessed my number."
Give a code snippet in #BASIC256 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/Xiaolin_Wu%27s_line_algorithm
Xiaolin Wu's line algorithm
Task Implement the   Xiaolin Wu's line algorithm   described in Wikipedia. This algorithm draws anti-aliased lines. Related task   See   Bresenham's line algorithm   for aliased lines.
#C.23
C#
  public class Line { private double x0, y0, x1, y1; private Color foreColor; private byte lineStyleMask; private int thickness; private float globalm;   public Line(double x0, double y0, double x1, double y1, Color color, byte lineStyleMask, int thickness) { ...
Give a code snippet in #C.23 Task Implement the   Xiaolin Wu's line algorithm   described in Wikipedia. This algorithm draws anti-aliased lines. Related task   See   Bresenham's line algorithm   for aliased lines.
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Maple
Maple
> sumprod := ( a, b ) -> (a + b, a * b): > sumprod( x, y ); x + y, x y   > sumprod( 2, 3 ); 5, 6
Give a code snippet in #Maple Task Show how to return more than one value from a function.
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 ...
#Factor
Factor
USING: kernel math.functions math.ranges math.text.utils prettyprint sequences ;   : munchausen? ( n -- ? ) dup 1 digit-groups dup [ ^ ] 2map sum = ;   5000 [1,b] [ munchausen? ] filter .
Give a code snippet in #Factor 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/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...
#Arturo
Arturo
sieve: function [upto][ composites: array.of: inc upto false loop 2..to :integer sqrt upto 'x [ if not? composites\[x][ loop range.step: x x^2 upto 'c [ composites\[c]: true ] ] ] result: new [] loop.with:'i composites 'c [ unless c -> ...
Give a code snippet in #Arturo 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/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 ≤...
#smart_BASIC
smart BASIC
INPUT n$ PRINT VAL(LEFT$(n$,(LEN(STR$(VAL(n$))))))+VAL(RIGHT$(n$,(LEN(n$)-LEN(STR$(VAL(n$)))-1)))
Give a code snippet in #smart_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/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#Chapel
Chapel
while true do writeln("SPAM");
Give a code snippet in #Chapel Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loo...
christopher/rosetta-code
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#11l
11l
V e0 = 0.0 V e = 2.0 V n = 0 V fact = 1 L (e - e0 > 1e-15) e0 = e n++ fact *= 2 * n * (2 * n + 1) e += (2.0 * n + 2) / fact   print(‘Computed e = ’e) print(‘Real e = ’math:e) print(‘Error = ’(math:e - e)) print(‘Number of iterations = ’n)
Give a code snippet in #11l Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
christopher/rosetta-code
http://rosettacode.org/wiki/Ulam_spiral_(for_primes)
Ulam spiral (for primes)
An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is shown with sequential integers,   ...
#zkl
zkl
var primes =Utils.Generator(Import("sieve.zkl").postponed_sieve); // lazy var offsets=Utils.cycle( T(0,1),T(-1,0),T(0,-1),T(1,0) ); // (N,E,S,W), lazy const BLACK=0, WHITE=0xff|ff|ff, GREEN=0x00|ff|00, EMPTY=0x080|80|80; fcn uspiral(N){ if((M:=N).isEven) M+=1; // need odd width, height img,p := PPM(M,M,EMPTY),...
Give a code snippet in #zkl An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is shown...
christopher/rosetta-code
http://rosettacode.org/wiki/Constrained_genericity
Constrained genericity
Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call the function eat on it. Write a ...
#Raku
Raku
subset Eatable of Any where { .^can('eat') };   class Cake { method eat() {...} }   role FoodBox[Eatable] { has %.foodbox; }   class Yummy does FoodBox[Cake] { } # composes correctly # class Yucky does FoodBox[Int] { } # fails to compose   my Yummy $foodbox .= new; say $foodbox;
Give a code snippet in #Raku Constrained genericity or bounded quantification means that a parametrized type or function (see parametric polymorphism) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. Say a type is called "eatable" if you can call th...
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.
#J
J
assert n = 42
Give a code snippet in #J 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/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#Excel
Excel
departmentNumbers =validRows( LAMBDA(ab, LET( x, INDEX(ab, 0, 1), y, INDEX(ab, 0, 2), z, 12 - (x + y),   IF(y <> z, IF(1 <= z, IF(7 >= z, CHOOSE({1, 2, 3}, x, y, z), NA() ...
Give a code snippet in #Excel There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (di...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#MUMPS
MUMPS
MEAN(X)  ;X is assumed to be a list of numbers separated by "^" QUIT:'$DATA(X) "No data" QUIT:X="" "Empty Set" NEW S,I SET S=0,I=1 FOR QUIT:I>$L(X,"^") SET S=S+$P(X,"^",I),I=I+1 QUIT (S/$L(X,"^"))
Give a code snippet in #MUMPS Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an esta...
christopher/rosetta-code
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#FreeBASIC
FreeBASIC
Function sameDigits(Byval n As Integer, Byval b As Integer) As Boolean Dim f As Integer = n Mod b : n \= b While n > 0 If n Mod b <> f Then Return False Else n \= b Wend Return True End Function   Function isBrazilian(Byval n As Integer) As Boolean If n < 7 Then Return False If n Mod 2...
Give a code snippet in #FreeBASIC Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B wh...
christopher/rosetta-code
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#Klingphix
Klingphix
1e300 dup mult tostr "inf" equal ["Infinity" print] if   " " input
Give a code snippet in #Klingphix Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherw...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#Verilog
Verilog
module main; integer i;   initial begin i = 1;   while(i > 0) begin $display(i); i = i + 1; end $finish ; end endmodule
Give a code snippet in #Verilog Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations ...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Action.21
Action!
BYTE RTCLOK1=$13 BYTE RTCLOK2=$14 BYTE PALNTSC=$D014   PROC Count(CARD max) CARD i   FOR i=1 TO max DO OD RETURN   CARD FUNC GetFrame() CARD res BYTE lsb=res,msb=res+1   lsb=RTCLOK2 msb=RTCLOK1 RETURN (res)   CARD FUNC FramesToMs(CARD frames) CARD res   IF PALNTSC=15 THEN res=frames*60 ELSE re...
Give a code snippet in #Action.21 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 bet...
christopher/rosetta-code
http://rosettacode.org/wiki/Monads/Writer_monad
Monads/Writer monad
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming...
#zkl
zkl
class Writer{ fcn init(x){ var X=x, logText=Data(Void," init \U2192; ",x.toString()) } fcn unit(text) { logText.append(text); self } fcn lift(f,name){ unit("\n  %s \U2192; %s".fmt(name,X=f(X))) } fcn bind(f,name){ lift.fp(f,name) } fcn toString{ "Result = %s\n%s".fmt(X,logText.text) }   fcn root{ li...
Give a code snippet in #zkl The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. De...
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...
#Kotlin
Kotlin
fun main(args: Array<String>) { for (i in 99.downTo(1)) { println("$i bottles of beer on the wall") println("$i bottles of beer") println("Take one down, pass it around") } println("No more bottles of beer on the wall!") }
Give a code snippet in #Kotlin 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 9...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#D
D
import std.stdio;   void showByteLen(T)(T[] str) { writefln("Byte length: %2d - %(%02x%)", str.length * T.sizeof, cast(ubyte[])str); }   void main() { string s1a = "møøse"; // UTF-8 showByteLen(s1a); wstring s1b = "møøse"; // UTF-16 showByteLen(s1b); dstring s1c = "møøse"; // UTF-32...
Give a code snippet in #D Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containi...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base
Exponentiation with infix operators in (or operating on) the base
(Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Some languages treat/honor infix operators when performing exponentiation   (raising numbers to some power by the language's exponentiation operator,   if ...
#F.23
F#
  printfn "-5.0**2.0=%f; -(5.0**2.0)=%f" (-5.0**2.0) (-(5.0**2.0))  
Give a code snippet in #F.23 (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Some languages treat/honor infix operators when performing exponentiation   (raising numbers to some power by the language's ...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_time_of_day
Averages/Mean time of day
Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of Averages/Mean angle compute ...
#Scheme
Scheme
  (import (scheme base) (scheme inexact) (scheme read) (scheme write) (srfi 1)) ; for fold   ;; functions copied from "Averages/Mean angle" task (define (average l) (/ (fold + 0 l) (length l)))   (define pi 3.14159265358979323846264338327950288419716939937510582097)   (define ...
Give a code snippet in #Scheme Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas...
christopher/rosetta-code
http://rosettacode.org/wiki/Curzon_numbers
Curzon numbers
A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1. Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1. Base here does not imply the radix of the counting sys...
#jq
jq
# To take advantage of gojq's arbitrary-precision integer arithmetic: def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);   def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;   # gojq does not currently define _nwise def _nwise($n): def n: if length <= $n then . else .[0:$n] , (.[$n:...
Give a code snippet in #jq A Curzon number is defined to be a positive integer n for which 2n + 1 is evenly divisible by 2 × n + 1. Generalized Curzon numbers are those where the positive integer n, using a base integer k, satisfy the condition that kn + 1 is evenly divisible by k × n + 1. Base here does not imply t...
christopher/rosetta-code
http://rosettacode.org/wiki/Mian-Chowla_sequence
Mian-Chowla sequence
The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ai + aj is distinct, fo...
#Go
Go
package main   import "fmt"   func contains(is []int, s int) bool { for _, i := range is { if s == i { return true } } return false }   func mianChowla(n int) []int { mc := make([]int, n) mc[0] = 1 is := []int{2} var sum int for i := 1; i < n; i++ { le...
Give a code snippet in #Go The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise s...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming langu...
#Ruby
Ruby
for n in 0..33 puts " %6b %3o %2d %2X" % [n, n, n, n] end puts [2,8,10,16,36].each {|i| puts " 100.to_s(#{i}) => #{100.to_s(i)}"}
Give a code snippet in #Ruby Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard rout...
christopher/rosetta-code
http://rosettacode.org/wiki/Monads/Maybe_monad
Monads/Maybe monad
Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and return a monadic number, e.g. Int ...
#Kotlin
Kotlin
// version 1.2.10   import java.util.Optional   /* doubles 'i' before wrapping it */ fun getOptionalInt(i: Int) = Optional.of(2 * i)   /* returns an 'A' repeated 'i' times wrapped in an Optional<String> */ fun getOptionalString(i: Int) = Optional.of("A".repeat(i))   /* does same as above if i > 0, otherwise returns an ...
Give a code snippet in #Kotlin Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and re...
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 ...
#Red
Red
>> if 10 > 2 [print "ten is bigger"] ten is bigger
Give a code snippet in #Red Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common co...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Ruby
Ruby
class Integer # Converts a normal integer to a Gray code. def to_gray raise Math::DomainError, "integer is negative" if self < 0 self ^ (self >> 1) end   # Converts a Gray code to a normal integer. def from_gray raise Math::DomainError, "integer is negative" if self < 0 recurse = proc do |i| ...
Give a code snippet in #Ruby 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 p...
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...
#Sidef
Sidef
require('Tk')   class Honeycombs( Number size = 36, Array letters = @('A' .. 'Z').shuffle.first(20), ) {   define tk = %S<Tk> has changed = Hash()   func altitude(n) { sqrt(3/4) * n }   method polygon_coordinates(x, y, size) { var alt = altitude(size) return (x - ...
Give a code snippet in #Sidef 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 a...
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 ...
#Oforth
Oforth
import: math   : testReal E println Pi println 9 sqrt println 2 ln println 2 exp println -3.4 abs println 3.4 exp println   2.4 floor println 3.9 floor println 5.5 floor println -2.4 floor println -3.9 floor println -5.5 floor println   2.4 ceil println 3.9 ceil println 5.5 ...
Give a code snippet in #Oforth 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. "...
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 ...
#Liberty_BASIC
Liberty BASIC
' define & call a function   print multiply( 3, 1.23456)   wait   function multiply( m1, m2) multiply =m1 *m2 end function   end
Give a code snippet in #Liberty_BASIC 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 d...
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
#Quackery
Quackery
[ ' [ 0 1 2 3 ] permutations ] constant is numorders ( --> [ )   [ [] 4 3 ** times [ [] i^ 3 times [ 4 /mod 4 + rot join swap ] drop nested join ] ] constant is oporders ( --> [ )   [ [] numorders witheach [ oporders ...
Give a code snippet in #Quackery 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/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Kotlin
Kotlin
// version 1.0.6   import java.awt.BorderLayout import java.awt.event.ActionEvent import java.awt.event.ActionListener import javax.swing.*   class Clicks : JFrame(), ActionListener { private var clicks = 0 private val label: JLabel private val clicker: JButton private var text: String   init { ...
Give a code snippet in #Kotlin Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#Objective-C
Objective-C
- (NSArray *) toCharArray {   NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[self length]]; for (int i=0; i < [self length]; i++) { NSString *ichar = [NSString stringWithFormat:@"%C", [self characterAtIndex:i]]; [characters addObject:ichar]; }   return characters; }   + (BOOL) luhnCheck...
Give a code snippet in #Objective-C The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the or...
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 ...
#Scala
Scala
object StoogeSort extends App { def stoogeSort(a: Array[Int], i: Int, j: Int) { if (a(j) < a(i)) { val temp = a(j) a(j) = a(i) a(i) = temp } if (j - i > 1) { val t = (j - i + 1) / 3 stoogeSort(a, i, j - t) stoogeSort(a, i + t, j) stoogeSort(a, i, j - t) } } ...
Give a code snippet in #Scala 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/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#MiniZinc
MiniZinc
  %Zigzag Matrix. Nigel Galloway, February 3rd., 2020 int: Size; array [1..Size,1..Size] of var 1..Size*Size: zigzag; constraint zigzag[1,1]=1 /\ zigzag[Size,Size]=Size*Size; constraint forall(n in {2*g | g in 1..Size div 2})(zigzag[1,n]=zigzag[1,n-1]+1 /\ forall(g in 2..n)(zigzag[g,n-g+1]=zigzag[g-1,n-g+2]+1)); constr...
Give a code snippet in #MiniZinc Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform
Burrows–Wheeler transform
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Burrows–Wheeler transform (BWT, also called block-s...
#Java
Java
import java.util.ArrayList; import java.util.List;   public class BWT { private static final String STX = "\u0002"; private static final String ETX = "\u0003";   private static String bwt(String s) { if (s.contains(STX) || s.contains(ETX)) { throw new IllegalArgumentException("String can...
Give a code snippet in #Java This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Burrows–Wheeler trans...
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...
#Lua
Lua
local bottles = 99   local function plural (bottles) if bottles == 1 then return '' end return 's' end while bottles > 0 do print (bottles..' bottle'..plural(bottles)..' of beer on the wall') print (bottles..' bottle'..plural(bottles)..' of beer') print ('Take one down, pass it around') bottles = bottle...
Give a code snippet in #Lua 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 b...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaysty...
#Factor
Factor
USING: accessors generalizations io kernel math math.functions parser prettyprint prettyprint.custom sequences ; IN: rosetta-code.modular-arithmetic RENAME: ^ math.functions => **   ! Define a modular integer class. TUPLE: mod-int { n integer read-only } { mod integer read-only } ;   ! Define a constructor for mod-...
Give a code snippet in #Factor Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, ...
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.
#C.23
C#
using System; using System.Windows.Forms;   public class Window { [STAThread] static void Main() { Form form = new Form();   form.Text = "Window"; form.Disposed += delegate { Application.Exit(); };   form.Show(); Application.Run(); } }
Give a code snippet in #C.23 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/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#F.23
F#
let rec recurse n = recurse (n+1)   recurse 0
Give a code snippet in #F.23 Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Nim
Nim
import intsets, math, algorithm   proc factors(n: int): seq[int] = var fs: IntSet for x in 1 .. int(sqrt(float(n))): if n mod x == 0: fs.incl(x) fs.incl(n div x)   for x in fs: result.add(x) result.sort()   echo factors(45)
Give a code snippet in #Nim Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Co...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Java
Java
1. //double equal to 1.0 1.0 //double 2432311.7567374 //double 1.234E-10 //double 1.234e-10 //double 758832d //double 728832f //float 1.0f //float 758832D //double 728832F //float 1.0F //float 1 / 2. //double 1 / 2 //int equal to 0
Give a code snippet in #Java 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/A...
christopher/rosetta-code
http://rosettacode.org/wiki/Taxicab_numbers
Taxicab numbers
A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also known as:   taxi numbers   tax...
#Julia
Julia
using Printf, DataStructures, IterTools   function findtaxinumbers(nmax::Integer) cube2n = Dict{Int,Int}(x ^ 3 => x for x in 0:nmax) sum2cubes = DefaultDict{Int,Set{NTuple{2,Int}}}(Set{NTuple{2,Int}}) for ((c1, _), (c2, _)) in product(cube2n, cube2n) if c1 ≥ c2 push!(sum2cubes[c1 + c2], ...
Give a code snippet in #Julia A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also kn...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#M2000_Interpreter
M2000 Interpreter
  A$=format$("J\u0332o\u0332s\u0332e\u0301\u0332") Print Len(A$) = 9 ' true Utf-16LE Print Len.Disp(A$) = 4 \\ display length Buffer Clear Mem as Byte*100 \\ Write at memory at offset 0 or address Mem(0) Return Mem, 0:=A$ Print Eval$(Mem, 0, 18) For i=0 to 17 step 2 \\ print hex value and character Hex Eva...
Give a code snippet in #M2000_Interpreter Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible g...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#BASIC
BASIC
OPTION COLLAPSE TRUE FOR x$ IN "Hello cruel world" PRINT x$ NEXT   FOR y$ IN "1,2,\"3,4\",5" STEP "," PRINT y$ NEXT
Give a code snippet in #BASIC Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops...
christopher/rosetta-code
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Action.21
Action!
INCLUDE "D2:IO.ACT" ;from the Action! Tool Kit   PROC Dir(CHAR ARRAY filter) BYTE dev=[1] CHAR ARRAY line(255)   Close(dev) Open(dev,filter,6) DO InputSD(dev,line) PrintE(line) IF line(0)=0 THEN EXIT FI OD Close(dev) RETURN   CARD FUNC FileSize(CHAR ARRAY src,dst) DEFINE BUF_LEN="1...
Give a code snippet in #Action.21 Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
christopher/rosetta-code