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/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 ...
#E
E
stderr.println("Goodbye, World!")
Give a code snippet in #E 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". T...
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...
#PHP
PHP
while(1) echo "SPAM\n";
Give a code snippet in #PHP Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/...
christopher/rosetta-code
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit ...
#ActionScript
ActionScript
//Return the code corresponding to a given character. //ActionScript does not have a character type, so 1-digit strings //are used instead function toSEDOLCode(char:String):uint { //Make sure only a single character was sent. if(char.length != 1) throw new Error("toSEDOL expected string length of 1, got " + char.le...
Give a code snippet in #ActionScript Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#Ol
Ol
  ; simple case - only lowercase letters (define (palindrome? str) (let ((l (string->runes str))) (equal? l (reverse l))))   (print (palindrome? "ingirumimusnocteetconsumimurigni")) ; ==> #true (print (palindrome? "thisisnotapalindrome")) ; ==> #false     ; complex case - with ignoring letter case and punctuat...
Give a code snippet in #Ol A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a ...
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...
#MiniScript
MiniScript
str = "one two three four five six seven eight nine ten eleven!" width = 15 words = str.split pos = 0 line = "" for word in words pos = pos + word.len + 1 if pos <= width then line = line + word + " " else print line[:-1] line = word + " " pos = word.len end if end for pr...
Give a code snippet in #MiniScript 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#BBC_BASIC
BBC BASIC
DIM matrix1(3,1), matrix2(1,2), product(3,2)   matrix1() = 1, 2, \ \ 3, 4, \ \ 5, 6, \ \ 7, 8   matrix2() = 1, 2, 3, \ \ 4, 5, 6   product() = matrix1() . matrix2()   FOR row% = 0 TO DIM(product(),1) FOR col% = 0 TO DI...
Give a code snippet in #BBC_BASIC Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#Forth
Forth
256 buffer: first-name 256 buffer: last-name : is ( a "name" -- ) parse-name rot place ;   : greet ( -- ) cr ." Hello, " first-name count type space last-name count type ." !" ;   first-name is Bob last-name is Hall greet     require mini-oof2.fs require string.fs object class field: given-name field: surname...
Give a code snippet in #Forth Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on b...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The ...
#ooRexx
ooRexx
  expressions = .array~of("2+3", "2+3/4", "2*3-4", "2*(3+4)+5/6", "2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10", "2*-3--4+-.25") loop input over expressions expression = createExpression(input) if expression \= .nil then say 'Expression "'input'" parses to "'expression~string'" and evaluates to "'expressio...
Give a code snippet in #ooRexx Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a s...
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...
#Icon_and_Unicon
Icon and Unicon
procedure main() every write( ![ 1., .1, 0.1, 2e10, 2E10, 3e-1, .4e2, 1.41e2, 8.e+3, 3.141e43 ]) end
Give a code snippet in #Icon_and_Unicon 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 expressi...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#6502_Assembly
6502 Assembly
; goodbyeworld.s for C= 8-bit machines, ca65 assembler format. ; String printing limited to strings of 256 characters or less.   a_cr = $0d ; Carriage return. bsout = $ffd2 ; C64 KERNEL ROM, output a character to current device. ; use $fded for Apple 2, $ffe3 (ascii) or $ffee (raw) for BBC. .code   ldx #0 ; Sta...
Give a code snippet in #6502_Assembly Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard...
christopher/rosetta-code
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bit...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
shE[s_String] := -Plus @@ ((# Log[2., #]) & /@ ((Length /@ Gather[#])/ Length[#]) &[Characters[s]])
Give a code snippet in #Mathematica_.2F_Wolfram_Language Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different ch...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#MoonScript
MoonScript
for i = 1,100 print ((a) -> a == "" and i or a) table.concat { i % 3 == 0 and "Fizz" or "" i % 5 == 0 and "Buzz" or ""}
Give a code snippet in #MoonScript Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   Fiz...
christopher/rosetta-code
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string....
#11l
11l
V target = Array(‘METHINKS IT IS LIKE A WEASEL’) V alphabet = ‘ ABCDEFGHIJLKLMNOPQRSTUVWXYZ’ V p = 0.05 V c = 100   F neg_fitness(trial) R sum(zip(trial, :target).map((t, h) -> Int(t != h)))   F mutate(parent) R parent.map(ch -> (I random:() < :p {random:choice(:alphabet)} E ch))   V parent = (0 .< target.len).ma...
Give a code snippet in #11l Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its a...
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Objeck
Objeck
  class Multifact { function : MultiFact(n : Int, deg : Int) ~ Int { result := n; while (n >= deg + 1){ result *= (n - deg); n -= deg; };   return result; }   function : Main(args : String[]) ~ Nil { for (i := 1; i <= 5; i+=1;){ IO.Console->Print("Degree...
Give a code snippet in #Objeck The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\di...
christopher/rosetta-code
http://rosettacode.org/wiki/Index_finite_lists_of_positive_integers
Index finite lists of positive integers
It is known that the set of finite lists of positive integers is   countable. This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers. Task Implement such a mapping:   write a function     rank     which assigns an integer to any finite, arbi...
#Sidef
Sidef
func rank(Array arr) { Number(arr.join('a'), 11) }   func unrank(Number n) { n.base(11).split('a').map { Num(_) } }   var l = [1, 2, 3, 10, 100, 987654321] say l var n = rank(l) say n var l = unrank(n) say l
Give a code snippet in #Sidef It is known that the set of finite lists of positive integers is   countable. This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers. Task Implement such a mapping:   write a function     rank     which assigns...
christopher/rosetta-code
http://rosettacode.org/wiki/Fork
Fork
Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
#PL.2FI
PL/I
  ATTACH SOLVE (X) THREAD (T5);  
Give a code snippet in #PL.2FI Task Spawn a new process which can run simultaneously with, and independently of, the original parent process.
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...
#C.2B.2B
C++
#include <iostream> #include <cstdint>   typedef uint64_t integer;   integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; }   // generates base 10 palindromes greater than 100 starting // with the specified digit class palindrome...
Give a code snippet in #C.2B.2B 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#Julia
Julia
x = rand(100, 100) y = rand(100, 100)   @inbounds begin for i = 1:100 for j = 1:100 x[i, j] *= y[i, j] y[i, j] += x[i, j] end end end  
Give a code snippet in #Julia Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Raku
Raku
my $original = 'Hello.'; my $copy = $original; say $copy; # prints "Hello." $copy = 'Goodbye.'; say $copy; # prints "Goodbye." say $original; # prints "Hello."
Give a code snippet in #Raku This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty st...
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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function Factorial_Iterative(n As Integer) As Integer Var result = 1 For i As Integer = 2 To n result *= i Next Return result End Function   Function Factorial_Recursive(n As Integer) As Integer If n = 0 Then Return 1 Return n * Factorial_Recursive(n - 1) End Function   For i As Inte...
Give a code snippet in #FreeBASIC 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant_odd_numbers
Abundant odd numbers
An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternately,   has the sigma sum of ...
#Ring
Ring
  #Project: Anbundant odd numbers   max = 100000000 limit = 25 nr = 0 m = 1 check = 0 index = 0 see "working..." + nl see "wait for done..." + nl while true check = 0 if m%2 = 1 nice(m) ok if check = 1 nr = nr + 1 ok if nr = max exit ok m = m + ...
Give a code snippet in #Ring An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or altern...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTPS/Client-authenticated
HTTPS/Client-authenticated
Demonstrate how to connect to a web server over HTTPS where that server requires that the client present a certificate to prove who (s)he is. Unlike with the HTTPS request with authentication task, it is not acceptable to perform the authentication by a username/password or a set cookie. This task is in general useful...
#Lasso
Lasso
local(sslcert = file('myCert.pem')) local(x = curl('https://sourceforge.net')) #x->set(CURLOPT_SSLCERT, #sslcert->readstring) #sslcert->close #x->result->asString
Give a code snippet in #Lasso Demonstrate how to connect to a web server over HTTPS where that server requires that the client present a certificate to prove who (s)he is. Unlike with the HTTPS request with authentication task, it is not acceptable to perform the authentication by a username/password or a set cookie. ...
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...
#WDTE
WDTE
let s => import 'stream'; let a => import 'arrays';   let mean nums => a.stream nums -> s.reduce [0; 0] (@ s p n => [+ (a.at p 0) 1; + (a.at p 1) n]) -> (@ s p => / (a.at p 1) (a.at p 0));
Give a code snippet in #WDTE 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 estab...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_frequency
Word frequency
Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a   letter   is.   Undersc...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
TakeLargest[10]@WordCounts[Import["https://www.gutenberg.org/files/135/135-0.txt"], IgnoreCase->True]//Dataset
Give a code snippet in #Mathematica_.2F_Wolfram_Language Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
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 ...
#Tcl
Tcl
  set x {lions, tigers, and} set y {bears, oh my!} set z {(from the "Wizard of OZ")}   lassign [lsort [list $x $y $z]] x y z   puts "x: $x" puts "y: $y" puts "z: $z"     set x 77444 set y -12 set z 0   lassign [lsort [list $x $y $z]] x y z   puts "x: $x" puts "y: $y" puts "z: $z"  
Give a code snippet in #Tcl 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#Ring
Ring
  load "stdlib.ring"   list = 1:4 lenList = len(list) permut = [] for perm = 1 to factorial(len(list)) for i = 1 to len(list) add(permut,list[i]) next perm(list) next for n = 1 to len(permut)/lenList for m = (n-1)*lenList+1 to n*lenList see "" + permut[m] if m < n*lenList ...
Give a code snippet in #Ring Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   gener...
christopher/rosetta-code
http://rosettacode.org/wiki/Pancake_numbers
Pancake numbers
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size...
#Go
Go
package main   import "fmt"   func pancake(n int) int { gap, sum, adj := 2, 2, -1 for sum < n { adj++ gap = gap*2 - 1 sum += gap } return n + adj }   func main() { for i := 0; i < 4; i++ { for j := 1; j < 6; j++ { n := i*5 + j fmt.Printf("p(%2d...
Give a code snippet in #Go Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacke...
christopher/rosetta-code
http://rosettacode.org/wiki/Compound_data_type
Compound data type
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#Crystal
Crystal
struct Point(T) getter x : T getter y : T def initialize(@x, @y) end end   puts Point(Int32).new 13, 12 #=> Point(Int32)(@x=13, @y=12)
Give a code snippet in #Crystal Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#Diego
Diego
me_lang(en)_cal(gregorian); me_msg()_now()_format(yyyy-mm-dd); me_msg()_now()_format(eeee, mmmm dd, yyyy);
Give a code snippet in #Diego This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints t...
#Jsish
Jsish
/* Nested function, in Jsish */ function makeList(separator) { var counter = 1;   function makeItem(item) { return counter++ + separator + item + "\n"; }   return makeItem("first") + makeItem("second") + makeItem("third"); }   ;makeList('. ');   /* =!EXPECTSTART!= makeList('. ') ==> 1. first 2. second 3. th...
Give a code snippet in #Jsish In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two...
christopher/rosetta-code
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#Scala
Scala
import scala.language.implicitConversions import java.io.File   object Rename0 { def main(args: Array[String]) { // The implicit causes every String to File mapping, implicit def file(s: String) = new File(s) // will be converted to new File(String) "myfile.txt" renameTo "anotherfile.txt" "/t...
Give a code snippet in #Scala Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the ri...
christopher/rosetta-code
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1...
#C
C
#include <stdio.h> #include <limits.h>   /* We go to some effort to handle overflow situations */   static unsigned long gcd_ui(unsigned long x, unsigned long y) { unsigned long t; if (y < x) { t = x; x = y; y = t; } while (y > 0) { t = y; y = x % y; x = t; /* y1 <- x0 % y0 ; x1 <- y0 */ } return x; } ...
Give a code snippet in #C This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Fortran
Fortran
MODULE qsort_mod   IMPLICIT NONE   TYPE group INTEGER :: order ! original order of unsorted data REAL :: VALUE ! values to be sorted by END TYPE group   CONTAINS   RECURSIVE SUBROUTINE QSort(a,na)   ! DUMMY ARGUMENTS INTEGER, INTENT(in) :: nA TYPE (group), DIMENSION(nA), INTENT(in...
Give a code snippet in #Fortran Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick ...
christopher/rosetta-code
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#Modula-2
Modula-2
MODULE Horner; FROM RealStr IMPORT RealToStr; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE Horner(coeff : ARRAY OF REAL; x : REAL) : REAL; VAR ans : REAL; i : CARDINAL; BEGIN ans := 0.0; FOR i:=HIGH(coeff) TO 0 BY -1 DO ans := (ans * x) + coeff[i]; END; RETURN ans END H...
Give a code snippet in #Modula-2 A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. T...
#Haskell
Haskell
import Data.List (scanl1, elemIndices, nub)   primes :: [Integer] primes = 2 : filter isPrime [3,5 ..]   isPrime :: Integer -> Bool isPrime = isPrime_ primes where isPrime_ :: [Integer] -> Integer -> Bool isPrime_ (p:ps) n | p * p > n = True | n `mod` p == 0 = False | otherwise = isPrime_ ps...
Give a code snippet in #Haskell The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off ...
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#zkl
zkl
"%09.3f".fmt(7.125) //-->"00007.125" "%09.3e".fmt(7.125) //-->"7.125e+00" "%09.3g".fmt(7.125) //-->"000007.12" "%09d".fmt(7.125) //-->"000000007" "%09,d".fmt(78901.125)//-->"00078,901"
Give a code snippet in #zkl Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/Set_puzzle
Set puzzle
Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: color, symbol, number and shading. there are...
#C.2B.2B
C++
  #include <time.h> #include <algorithm> #include <iostream> #include <iomanip> #include <vector> #include <string>   enum color { red, green, purple }; enum symbol { oval, squiggle, diamond }; enum number { one, two, three }; enum shading { solid, open, striped }; class card { public: card( col...
Give a code snippet in #C.2B.2B Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: color, symbol...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/PPM_conversion_through_a_pipe
Bitmap/PPM conversion through a pipe
Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page. There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpeg (package "netpbm" on Linux)...
#Wren
Wren
/* gcc -O3 -std=c11 -shared -o pipeconv.so -fPIC -I./include pipeconv.c */   #include <stdlib.h> #include <string.h> #include "dome.h"   static DOME_API_v0* core; static WREN_API_v0* wren;   static const char* source = "" "class PipeConv {\n" "foreign static convert(from, to) \n" "} \n";   void C_convert(WrenVM* v...
Give a code snippet in #Wren Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page. There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojp...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the...
#FreeBASIC
FreeBASIC
dim as string s, nxt   input "Enter string: ", s   if len(s)<2 then 'A string with one or zero characters passes by default print "All characters are the same." end end if   dim as ubyte i   for i = 1 to len(s)-1 nxt = mid(s, i+1, 1) if mid(s, i, 1)<>nxt then 'if any character differs from the prev...
Give a code snippet in #FreeBASIC Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display e...
christopher/rosetta-code
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1...
#Factor
Factor
  : fact ( n -- n-factorial ) dup 0 = [ drop 1 ] [ dup 1 - fact * ] if ;   : choose ( n k -- n-choose-k ) 2dup - [ fact ] tri@ * / ;   ! outputs 10 5 3 choose .   ! alternative using folds USE: math.ranges   ! (product [n..k+1] / product [n-k..1]) : choose-fold ( n k -- n-choose-k ) 2dup 1 + [a,b] product -...
Give a code snippet in #Factor This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n −...
christopher/rosetta-code
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effect...
#Shen
Shen
(define make-list [A|D] -> [cons (make-list A) (make-list D)] X -> X)   (defmacro info-macro [info Exp] -> [output "~A: ~A~%" (make-list Exp) Exp])   (info (* 5 6)) \\ outputs [* 5 6]: 30
Give a code snippet in #Shen Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" mea...
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have download...
#11l
11l
V words = File(‘unixdict.txt’).read().split("\n") V ordered = words.filter(word -> word == sorted(word).join(‘’)) V maxlen = max(ordered, key' w -> w.len).len V maxorderedwords = ordered.filter(word -> word.len == :maxlen) print(maxorderedwords.join(‘ ’))
Give a code snippet in #11l An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally ...
christopher/rosetta-code
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1 ...
#Ring
Ring
  load "guilib.ring" load "stdlib.ring"   size = 3 flip = newlist(size,size) board = newlist(size,size) colflip = list(size) rowflip = list(size)   new qapp { win1 = new qwidget() { setwindowtitle("Flipping bits game") setgeometry(465,115,800,600) l...
Give a code snippet in #Ring The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move...
christopher/rosetta-code
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#Common_Lisp
Common Lisp
  (in-package #:rgb-pixel-buffer)   (defun rgb-to-gray-image (rgb-image) (flet ((rgb-to-gray (rgb-value) (round (+ (* 0.2126 (rgb-pixel-red rgb-value)) (* 0.7152 (rgb-pixel-green rgb-value)) (* 0.0722 (rgb-pixel-blue rgb-value)))))) (let ((gray-image (make-array (array-dimensions rgb-image) :ele...
Give a code snippet in #Common_Lisp Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conve...
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...
#Java
Java
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.LongStream;   public class AliquotSequenceClassifications {   private static Long properDivsSum(long n) { return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0 && n != i).sum(); }   sta...
Give a code snippet in #Java 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 ...
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 ...
#Rust
Rust
  fn is_self_desc(xx: u64) -> bool { let s: String = xx.to_string(); let mut count_vec = vec![0; 10]; for c in s.chars() { count_vec[c.to_digit(10).unwrap() as usize] += 1; } for (i, c) in s.chars().enumerate() { if count_vec[i] != c.to_digit(10).unwrap() as usize { retur...
Give a code snippet in #Rust 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 dig...
christopher/rosetta-code
http://rosettacode.org/wiki/Bioinformatics/Sequence_mutation
Bioinformatics/Sequence mutation
Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, G, or T. (which has a chance o...
#11l
11l
UInt32 seed = 0 F nonrandom(n)  :seed = 1664525 * :seed + 1013904223 R Int(:seed >> 16) % n F nonrandom_choice(lst) R lst[nonrandom(lst.len)]   F basecount(dna) DefaultDict[Char, Int] d L(c) dna d[c]++ R sorted(d.items())   F seq_split(dna, n = 50) R (0 .< dna.len).step(n).map(i -> @dna[i .< i...
Give a code snippet in #11l Task Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: Choosing a random base position in the sequence. Mutate the sequence by doing one of either: Swap the base at that position by changing it to one of A, C, G...
christopher/rosetta-code
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. 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 haversine formula is an equation important in navigation, g...
#F.23
F#
open System   [<Measure>] type deg [<Measure>] type rad [<Measure>] type km   let haversine (θ: float<rad>) = 0.5 * (1.0 - Math.Cos(θ/1.0<rad>))   let radPerDeg = (Math.PI / 180.0) * 1.0<rad/deg>   type pos(latitude: float<deg>, longitude: float<deg>) = member this.φ = latitude * radPerDeg member this.ψ = long...
Give a code snippet in #F.23 This page uses content from Wikipedia. The original article was at Haversine formula. 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 haversine formula is an equat...
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 ...
#SETL
SETL
program ackermann;   (for m in [0..3]) print(+/ [rpad('' + ack(m, n), 4): n in [0..6]]); end;   proc ack(m, n); return {[0,n+1]}(m) ? ack(m-1, {[0,1]}(n) ? ack(m, n-1)); end proc;   end program;
Give a code snippet in #SETL 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/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Scheme
Scheme
(define dst (string-copy src))
Give a code snippet in #Scheme This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty ...
christopher/rosetta-code
http://rosettacode.org/wiki/Speech_synthesis
Speech synthesis
Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
#Sidef
Sidef
func text2speech(text, lang='en') { Sys.run("espeak -v #{lang} -w /dev/stdout #{text.escape} | aplay"); } text2speech("This is an example of speech synthesis.");
Give a code snippet in #Sidef Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Scala
Scala
object GnomeSort { def gnomeSort(a: Array[Int]): Unit = { var (i, j) = (1, 2) while ( i < a.length) if (a(i - 1) <= a(i)) { i = j; j += 1 } else { val tmp = a(i - 1) a(i - 1) = a(i) a({i -= 1; i + 1}) = tmp i = if (i == 0) {j += 1; j - 1} else i } } }
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/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...
#Pop11
Pop11
define number_to_base(n, base); radix_apply(n, '%p', sprintf, base); enddefine;
Give a code snippet in #Pop11 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/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...
#Raku
Raku
sub glyph ($_) { when * < 33 { (0x2400 + $_).chr } # display symbol names for invisible glyphs when 127 { '␡' } default { .chr } }   say '{|class="wikitable" style="text-align:center;background-color:hsl(39, 90%, 95%)"';   for (^128).rotor(16) -> @row { say '|-'; printf(q[|%d<br>0x%02X<br><bi...
Give a code snippet in #Raku 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/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#MATLAB_.2F_Octave
MATLAB / Octave
width = input('Array Width: '); height = input('Array Height: ');   array = zeros(width,height);   array(1,1) = 12;   disp(['Array element (1,1) = ' num2str(array(1,1))]);   clear array; % de-allocate (remove) array from workspace  
Give a code snippet in #MATLAB_.2F_Octave Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given b...
christopher/rosetta-code
http://rosettacode.org/wiki/Periodic_table
Periodic table
Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1...
#Phix
Phix
with javascript_semantics constant match_wp = false function prc(integer n) constant t = {0,2,10,18,36,54,86,118,119} integer row = abs(binary_search(n,t,true))-1, col = n-t[row] if col>1+(row>1) then col = 18-(t[row+1]-n) if match_wp then if col<=2 then return {row+...
Give a code snippet in #Phix Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 9 ...
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 ...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations string 0; \use zero-terminated strings, instead of MSb terminated   func StrLen(Str); \Return the number of characters in an ASCIIZ string char Str; int I; for I:= 0 to -1>>1-1 do if Str(I) = 0 then return I;   func RevStr(S); \...
Give a code snippet in #XPL0 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#CLU
CLU
start_up = proc () po: stream := stream$primary_output()    % To turn a character code into an integer, use char$c2i  % (but then to print it, it needs to be turned into a string first  % with int$unparse) stream$putl(po, int$unparse( char$c2i( 'a' ) ) ) % prints '97'    % To turn an integer into a...
Give a code snippet in #CLU Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conver...
christopher/rosetta-code
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. 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 haversine formula is an equation important in navigation, g...
#Teradata_Stored_Procedure
Teradata Stored Procedure
  # syntax: CALL SP_HAVERSINE(36.12,33.94,-86.67,-118.40,x);   CREATE PROCEDURE SP_HAVERSINE ( IN lat1 FLOAT, IN lat2 FLOAT, IN lon1 FLOAT, IN lon2 FLOAT, OUT distance FLOAT)   BEGIN DECLARE dLat FLOAT; DECLARE dLon FLOAT; DECLARE c FLOAT; DECLARE a FLOAT; DECLARE km FLOAT;   SET dLat = RAD...
Give a code snippet in #Teradata_Stored_Procedure This page uses content from Wikipedia. The original article was at Haversine formula. 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 haversin...
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...
#Lily
Lily
  while 1: print("SPAM")  
Give a code snippet in #Lily Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops...
christopher/rosetta-code
http://rosettacode.org/wiki/Synchronous_concurrency
Synchronous concurrency
The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th...
#C
C
#include <stdlib.h> /* malloc(), realloc(), free() */ #include <stdio.h> /* fopen(), fgetc(), fwrite(), printf() */   #include <libco.h> /* co_create(), co_switch() */   void fail(const char *message) { perror(message); exit(1); }   /* * These are global variables of this process. All cothreads of this * process wi...
Give a code snippet in #C The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different n...
christopher/rosetta-code
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt...
#MiniScript
MiniScript
alphabet = "abcdefghijklmnopqrstuvwxyz".split("") cipher = alphabet[0:] cipher.shuffle encode = {} decode = {} for i in alphabet.indexes encode[alphabet[i]] = cipher[i] decode[cipher[i]] = alphabet[i] encode[alphabet[i].upper] = cipher[i].upper decode[cipher[i].upper] = alphabet[i].upper end for   apply...
Give a code snippet in #MiniScript Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and th...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Stata
Stata
* Line comment: must be used at the beginning of a line (does not work in Mata)   // Line comment until the end of the line   /* Multiline comment   */
Give a code snippet in #Stata Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/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 ≤...
#Tcl
Tcl
scan [gets stdin] "%d %d" x y puts [expr {$x + $y}]
Give a code snippet in #Tcl 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Polyspiral
Polyspiral
A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the b...
#Julia
Julia
using Gtk, Graphics, Colors   const can = @GtkCanvas() const win = GtkWindow(can, "Polyspiral", 360, 360)   const drawiters = 72 const colorseq = [colorant"blue", colorant"red", colorant"green", colorant"black", colorant"gold"] const angleiters = [0, 0, 0] const angles = [75, 100, 135, 160]   Base.length(v::Vec2) = sqr...
Give a code snippet in #Julia A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. Task Animate a series of polyspirals, by drawing a complete spiral then incrementing the a...
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 ...
#PowerShell
PowerShell
$s = "asdf"
Give a code snippet in #PowerShell Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Euphoria
Euphoria
  include std/console.e include std/text.e include std/search.e include std/sequence.e   sequence board sequence players = {"X","O"}   function DisplayBoard() for i = 1 to 3 do for j = 1 to 3 do printf(1,"%s",board[i][j]) if j < 3 then printf(1,"%s","|") end if end for if i < 3 then puts(1,"\n--...
Give a code snippet in #Euphoria 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   MathWor...
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...
#Sidef
Sidef
for (var i = 2; i <= 8; i += 2) { say i }
Give a code snippet in #Sidef 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/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...
#Cubescript
Cubescript
  // No arguments myfunction   // All functions can take a variable number of arguments. // These can be accessed from within the function with the aliases: // $arg1, $arg2, $arg3... $numargs tells the amount of args passed. myfunction word "text string" 1 3.14   // Getting a function's return value retval = (myfunctio...
Give a code snippet in #Cubescript 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/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Set_lang
Set lang
set a 0 > Useless intialization - All lowercase variables have an initial value of 0 set b 66 > Simple variable assignment - ''b'' is now the ASCII value of 66, or the character 'B' [c=0] set c 5 > Conditional variable assignment - If ''c'' is 0, then set ''c'' to 5 set ? 6 > A "goto" command; Sett...
Give a code snippet in #Set_lang Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#Oberon-2
Oberon-2
  MODULE HOFuns; IMPORT NPCT:Tools, Out; TYPE Formatter = PROCEDURE (s: STRING; len: LONGINT): STRING; VAR words: ARRAY 8 OF STRING;   PROCEDURE PrintWords(w: ARRAY OF STRING; format: Formatter); VAR i: INTEGER; BEGIN i := 0; WHILE (i < LEN(words)) DO Out.Object(format(words[i],16)); ...
Give a code snippet in #Oberon-2 Task Pass a function     as an argument     to another function. Related task   First-class functions
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...
#Forth
Forth
: sum ( x_1 ... x_n n -- sum ) 1 ?do + loop ; 4 3 2 1 4 sum . \ 10
Give a code snippet in #Forth 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/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#360_Assembly
360 Assembly
* Align columns 12/04/2019 ALICOL CSECT USING ALICOL,R13 base register B 72(R15) skip savearea DC 17F'0' savearea SAVE (14,12) save previous context ST R13,4(R15) link backward ST...
Give a code snippet in #360_Assembly Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be eit...
christopher/rosetta-code
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation langu...
#Nanoquery
Nanoquery
class StdDev declare n declare sum declare sum2   def StdDev() n = 0 sum = 0 sum2 = 0 end   def sd(x) this.n += 1 this.sum += x this.sum2 += x*x   return sqrt(sum2/n - sum*sum/n/n) end end   testData = {2,4,4,4,5,5,7,9} sd = new(StdDev)   for x in testData println sd.sd(x) end
Give a code snippet in #Nanoquery Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the f...
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...
#Kotlin
Kotlin
import java.math.BigInteger   fun isqrt(x: BigInteger): BigInteger { if (x < BigInteger.ZERO) { throw IllegalArgumentException("Argument cannot be negative") } var q = BigInteger.ONE while (q <= x) { q = q.shiftLeft(2) } var z = x var r = BigInteger.ZERO while (q > BigInt...
Give a code snippet in #Kotlin 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 compute...
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...
#QB64
QB64
Dim n As Integer n = 1024 While n > 0 Print n n = n \ 2 Wend
Give a code snippet in #QB64 Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Fortran
Fortran
  program rosetta_random implicit none   integer, parameter :: rdp = kind(1.d0) real(rdp) :: num integer, allocatable :: seed(:) integer :: un,n, istat   call random_seed(size = n) allocate(seed(n))   ! Seed with the OS random number generator open(newunit=un, file="/dev/urandom", access="str...
Give a code snippet in #Fortran The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algori...
christopher/rosetta-code
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#8086_Assembly
8086 Assembly
puts: equ 9 cpu 8086 bits 16 org 100h section .text ;;; Generate the first 1200 elemets of the Stern-Brocot sequence mov cx,600 ; 2 elements generated per loop mov si,seq mov di,seq+2 lodsb mov ah,al ; AH = predecessor genseq: lodsb ; AL = considered member add ah,al ; AH = sum xchg ah,al ; Swap them (AL = ...
Give a code snippet in #8086_Assembly For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the consider...
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 ...
#Yabasic
Yabasic
// Rosetta Code problem: http://rosettacode.org/wiki/Singly-linked_list/Element_insertion & removal & traverse // by Galileo, 02/2022   FIL = 1 : DATO = 2 : LINK = 3 countNodes = 0 : Nodes = 10   dim list(Nodes, 3)     sub searchNode(node) local i, prevNode   for i = 1 to countNodes if i = node break ...
Give a code snippet in #Yabasic 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: Defin...
christopher/rosetta-code
http://rosettacode.org/wiki/Parallel_brute_force
Parallel brute force
Task Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes: 1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 3. 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f Your p...
#Modula-2
Modula-2
MODULE PBF; FROM FormatString IMPORT FormatString; FROM SHA256 IMPORT SHA256,Create,Destroy,HashBytes,Finalize,GetHash; FROM SYSTEM IMPORT ADR,ADDRESS,BYTE; FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar; FROM Threads IMPORT Thread,CreateThread,WaitForThreadTermination;   PROCEDURE PrintHexBytes(str : ARRAY OF...
Give a code snippet in #Modula-2 Task Find, through brute force, the five-letter passwords corresponding with the following SHA-256 hashes: 1. 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 2. 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 3. 74e1bb62f8dabb8125a58852b63bdf6eaef667...
christopher/rosetta-code
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#LFE
LFE
  (: jiffy encode (list 1 2 3 '"apple" 'true 3.14))  
Give a code snippet in #LFE Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
christopher/rosetta-code
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#Oforth
Oforth
swap
Give a code snippet in #Oforth Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides generici...
christopher/rosetta-code
http://rosettacode.org/wiki/GUI_component_interaction
GUI component interaction
Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check input from the user pop up dial...
#Oz
Oz
declare [QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']}   proc {Main} MaxValue = 1000 NumberWidget GUI = lr( numberentry(init:1 min:0 max:MaxValue handle:NumberWidget) button(text:"Increase" action:proc {$} OldVal = {N...
Give a code snippet in #Oz Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction of program logic with GUI components. Typically, the following is needed: put values into input fields under program control read and check inpu...
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...
#Raku
Raku
say 3 lcm 4; # infix say [lcm] 1..20; # reduction say ~(1..10 Xlcm 1..10) # cross
Give a code snippet in #Raku 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/Logical_operations
Logical operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Objeck
Objeck
  bundle Default { class Logic { function : Main(args : String[]) ~ Nil { a := true; b := false; IO.Console->GetInstance()->Print("a and b is: ")->PrintLine(a & b); IO.Console->GetInstance()->Print("a or b is: ")->PrintLine(a | b); IO.Console->GetInstance()->Print("not a is: ")->Prin...
Give a code snippet in #Objeck 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/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#PL.2FSQL
PL/SQL
DBMS_RANDOM.RANDOM --produces integers in [-2^^31, 2^^31). DBMS_RANDOM.VALUE --produces numbers in [0,1) with 38 digits of precision. DBMS_RANDOM.NORMAL --produces normal distributed numbers with a mean of 0 and a variance of 1
Give a code snippet in #PL.2FSQL The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algor...
christopher/rosetta-code
http://rosettacode.org/wiki/Bin_given_limits
Bin given limits
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] ...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   NSArray<NSNumber *> *bins(NSArray<NSNumber *> *limits, NSArray<NSNumber *> *data) { NSMutableArray<NSNumber *> *result = [[NSMutableArray alloc] initWithCapacity:[limits count] + 1]; for (NSInteger i = 0; i <= [limits count]; i++) { [result addObject:@0]; } for (NSNumber ...
Give a code snippet in #Objective-C You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many in...
christopher/rosetta-code
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#C.2B.2B
C++
#include <algorithm> // for std::swap #include <cstddef> #include <cassert>   // Matrix traits: This describes how a matrix is accessed. By // externalizing this information into a traits class, the same code // can be used both with native arrays and matrix classes. To use the // default implementation of the traits c...
Give a code snippet in #C.2B.2B Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is conveni...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's eval...
#APL
APL
5*3*2 1953125 (5*3)*2 15625 5*(3*2) 1953125
Give a code snippet in #APL This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show th...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#Nim
Nim
import times   var t = now() echo(t.format("yyyy-MM-dd")) echo(t.format("dddd',' MMMM d',' yyyy"))
Give a code snippet in #Nim This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_elements_below_main_diagonal_of_matrix
Sum of elements below main diagonal of matrix
Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
#BASIC
BASIC
arraybase 1 dim diag = {{ 1, 3, 7, 8,10}, { 2, 4,16,14, 4}, { 3, 1, 9,18,11}, {12,14,17,18,20}, { 7, 1, 3, 9, 5}} ind = diag[?,] sumDiag = 0   for x = 1 to diag[?,] for y = 1 to diag[,?]-ind sumDiag += diag[x, y] next y ind -= 1 next x   print "Sum of elements below main diagonal of matrix is "; sumDiag end
Give a code snippet in #BASIC Task Find and display the sum of elements that are below the main diagonal of a matrix. The matrix should be a square matrix. ───   Matrix to be used:   ─── [[1,3,7,8,10], [2,4,16,14,4], [3,1,9,18,11], [12,14,17,18,20], [7,1,3,9,5]]
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_pinstripe/Display
Colour pinstripe/Display
The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   blue,   magenta,   cyan,   yellow,   and  ...
#XPL0
XPL0
code ChIn=7, Point=41, SetVid=45; int X, Y, W, C; [SetVid($13); \set 320x200 graphics mode in 256 colors for Y:= 0 to 200-1 do \for all the scan lines... [W:= Y/50 + 1; \width of stripe = 1, 2, 3, 4 C:= 0; \set color to black so first pixel becomes b...
Give a code snippet in #XPL0 The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence,   or a sequence that includes: black,   red,   green,   blue,   mage...
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...
#AWK
AWK
BEGIN { s = "hello" print s " literal" s1 = s " literal" print s1 }
Give a code snippet in #AWK 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 liter...
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      ...
#Liberty_BASIC
Liberty BASIC
s$ = "s$ = : Print Left$(s$, 5) + chr$(34) + s$ + chr$(34) + Mid$(s$, 5)" : Print Left$(s$, 5) + chr$(34) + s$ + chr$(34) + Mid$(s$, 5)
Give a code snippet in #Liberty_BASIC 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 pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_occurrences_of_a_substring
Count occurrences of a substring
Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It should return an integer cou...
#Sidef
Sidef
say "the three truths".count("th"); say "ababababab".count("abab");
Give a code snippet in #Sidef Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. ...
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...
#AppleScript
AppleScript
on average(listOfNumbers) set len to (count listOfNumbers) if (len is 0) then return missing value   set sum to 0 repeat with thisNumber in listOfNumbers set sum to sum + thisNumber end repeat   return sum / len end average   average({2500, 2700, 2400, 2300, 2550, 2650, 2750, 2450, 2600,...
Give a code snippet in #AppleScript 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 a...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#Pascal
Pascal
  program project1; uses sysutils, classes, math;   const MaxWeight = 400; N = 21;   type TMaxArray = array[0..N, 0..MaxWeight] of integer;   TEquipment = record Description : string; Weight : integer; Value : integer; end;   TEquipmentList = array[1..N] of TEquipment;   var M:TMaxArray; ...
Give a code snippet in #Pascal A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will hav...
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...
#Vala
Vala
struct Fraction { public uint d; public uint n; }   void farey(uint n) { Fraction f1 = {0, 1}; Fraction f2 = {1, n}; print("0/1 1/%u ", n); while (f2.n > 1) { var k = (n + f1.n) / f2.n; var aux = f1; f1 = f2; f2 = {f2.d * k - aux.d, f2.n * k - aux.n}; print("%u/%u ", f2.d, f2.n); } p...
Give a code snippet in #Vala 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/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...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols   runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /* @see http://en.wikipedia.org/wiki/Word_wrap#Minimum_length   SpaceLeft := LineWidth for each Word in Text if (Width(Word) + Sp...
Give a code snippet in #NetRexx 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 pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Run-length_encoding
Run-length encoding
Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Fixed; use Ada.Strings.Fixed; procedure Test_Run_Length_Encoding is function Encode (Data : String) return String is begin if Data'Length = 0 then return ""; else declare Code  : constant Character := Data (Data'...
Give a code snippet in #Ada Run-length encoding You are encouraged to solve this task according to the task description, using any language you may know. Task Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a functi...
christopher/rosetta-code