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/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#XPL0
XPL0
include c:\cxpl\stdlib;   func Sum1; \Return sum the straightforward way int N, S; [S:= 0; for N:= 1 to 999 do if rem(N/3)=0 or rem(N/5)=0 then S:= S+N; return S; ];   func Sum2(D); \Return sum of sequence using N*(N+1)/2 int D; int Q; [Q:= (1000-1)/D; return Q*(Q+1)/2*D; ];   func Sum3(D); \Return sum ...
Give a code snippet in #XPL0 Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
christopher/rosetta-code
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced...
#REXX
REXX
/*REXX program truncates a file to a specified (and smaller) number of bytes. */ parse arg siz FID /*obtain required arguments from the CL*/ FID=strip(FID) /*elide FID leading/trailing blanks. */ if siz=='' then call ser "No trunca...
Give a code snippet in #REXX Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Julia
Julia
using Random, IterTools, Combinatorics   function SetGameTM(basic = true) drawsize = basic ? 9 : 12 setsneeded = div(drawsize, 2) setsof3 = Vector{Vector{NTuple{4, String}}}() draw = Vector{NTuple{4, String}}() deck = collect(Iterators.product(["red", "green", "purple"], ["one", "two", "three"], ...
Give a code snippet in #Julia 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/War_card_game
War card game
War Card Game Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional. References: Bicycle card company: War game site Wikipedia: War (card game) Related tasks: Playing cards Card shuffles Deal cards for FreeCell Poker hand_analyser Go Fish...
#Julia
Julia
# https://bicyclecards.com/how-to-play/war/   using Random   const SUITS = ["♣", "♦", "♥", "♠"] const FACES = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" ] const DECK = vec([f * s for s in SUITS, f in FACES]) const rdict = Dict(DECK[i] => div(i + 3, 4) for i in eachindex(DECK))   deal2(deck) = beg...
Give a code snippet in #Julia War Card Game Simulate the card game War. Use the Bicycle playing card manufacturer's rules. Show a game as played. User input is optional. References: Bicycle card company: War game site Wikipedia: War (card game) Related tasks: Playing cards Card shuffles Deal cards for FreeCel...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#Go
Go
package main   import "fmt"   func gss(s []int) ([]int, int) { var best, start, end, sum, sumStart int for i, x := range s { sum += x switch { case sum > best: best = sum start = sumStart end = i + 1 case sum < 0: sum = 0 ...
Give a code snippet in #Go Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are neg...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble 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 ...
#Simula
Simula
BEGIN   PROCEDURE BUBBLESORT(A); NAME A; INTEGER ARRAY A; BEGIN INTEGER LOW, HIGH, I; BOOLEAN SWAPPED;   PROCEDURE SWAP(I, J); INTEGER I, J; BEGIN INTEGER TEMP; TEMP := A(I); A(I) := A(J); A(J) := TEMP; END**OF**SWAP;   LOW := LOWERBOUND(A, 1); ...
Give a code snippet in #Simula Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#Ring
Ring
  load "stdlib.ring"   num = 0 limit = 22563490300366186081   see "working..." + nl see "the first 15 terms of the sequence are:" + nl   for n = 1 to 15 num = 0 for m = 1 to limit pnum = 0 for p = 1 to limit if (m % p = 0) pnum = pnum + 1 ok next ...
Give a code snippet in #Ring Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number ...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#XBS
XBS
const Chars:[string] = ["[","]"]; func GenerateString(Amount:number=4):string{ set Result:string = ""; <|(*1..Amount)=>Result+=Chars[math.random(0,?Chars-1)]; send Result; }   func IsBalanced(String:string):boolean{ set Pairs:number = 0; <|(*(0..(?String-1)))=>(String::at(_)=="[")?(Pairs<0)?=>send false,Pairs++,=>...
Give a code snippet in #XBS Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nes...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   argument 1 get "r" fopen var f drop 0 7 for f fgets number? if f fclose exitfor else nip nip endif endfor print /# show -1 if past eof #/
Give a code snippet in #Phixmonti Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store ...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_duplicate_files
Find duplicate files
In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion. Task Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with duplicate contents under the dire...
#Julia
Julia
using Printf, Nettle   function find_duplicates(path::String, minsize::Int = 0) filesdict = Dict{String,Array{NamedTuple}}()   for (root, dirs, files) in walkdir(path), fn in files filepath = joinpath(root, fn) filestats = stat(filepath)   filestats.size > minsize || continue   h...
Give a code snippet in #Julia In a large directory structure it is easy to inadvertently leave unnecessary copies of files around, which can use considerable disk space and create confusion. Task Create a program which, given a minimum size and a folder/directory, will find all files of at least size bytes with du...
christopher/rosetta-code
http://rosettacode.org/wiki/Regular_expressions
Regular expressions
Task   match a string against a regular expression   substitute part of a string using a regular expression
#ooRexx
ooRexx
/* Rexx */ /* Using the RxRegExp Regular Expression built-in utility class */   st1 = 'Fee, fie, foe, fum, I smell the blood of an Englishman' rx1 = '[Ff]?e' -- unlike most regex engines, RxRegExp uses '?' instead of '.' to match any single character sbx = 'foo'   myRE = .RegularExpression~new() myRE~parse(rx1, MINIMAL...
Give a code snippet in #ooRexx Task   match a string against a regular expression   substitute part of a string using a regular expression
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Fur...
#OCaml
OCaml
#load "nums.cma";; open Num;;   for candidate = 2 to 1 lsl 19 do let sum = ref (num_of_int 1 // num_of_int candidate) in for factor = 2 to truncate (sqrt (float candidate)) do if candidate mod factor = 0 then sum := !sum +/ num_of_int 1 // num_of_int factor +/ num_of_int 1 // num_of_int ...
Give a code snippet in #OCaml Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (...
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#Asymptote
Asymptote
time(); time("%a %b %d %H:%M:%S %Z %Y"); //are equivalent ways of returning the current time in the default format used by the UNIX date command.
Give a code snippet in #Asymptote Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_append
String append
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 |...
#Rust
Rust
  use std::ops::Add;   fn main(){ let hello = String::from("Hello world"); println!("{}", hello.add("!!!!")); }
Give a code snippet in #Rust Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations C...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Applesoft_BASIC
Applesoft BASIC
100 DATA"MY DOG HAS FLEAS" 110 DATA"MADAM, I'M ADAM." 120 DATA"1 ON 1" 130 DATA"IN GIRUM IMUS NOCTE ET CONSUMIMUR IGNI" 140 DATA"A man, a plan, a canal: Panama!" 150 DATA"KAYAK" 160 DATA"REDDER" 170 DATA"H" 180 DATA""   200 FOR L1 = 1 TO 9 210 READ W$ : GOSUB 300" IS PALINDROME? 220 PRINT CHR$(34); W$; CHR$(34); ...
Give a code snippet in #Applesoft_BASIC 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 (p...
christopher/rosetta-code
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define ...
#D
D
import std.math; import std.stdio;   int p(int l, int n) { int test = 0; double logv = log(2.0) / log(10.0); int factor = 1; int loop = l; while (loop > 10) { factor *= 10; loop /= 10; } while (n > 0) { int val;   test++; val = cast(int)(factor * pow(1...
Give a code snippet in #D (This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819...
christopher/rosetta-code
http://rosettacode.org/wiki/Inheritance/Multiple
Inheritance/Multiple
Multiple inheritance allows to specify that one class is a subclass of several other classes. Some languages allow multiple inheritance for arbitrary classes,   others restrict it to interfaces,   some don't allow it at all. Task Write two classes (or interfaces) Camera and MobilePhone,   then write a class Camer...
#Scala
Scala
trait Camera trait MobilePhone class CameraPhone extends Camera with MobilePhone
Give a code snippet in #Scala Multiple inheritance allows to specify that one class is a subclass of several other classes. Some languages allow multiple inheritance for arbitrary classes,   others restrict it to interfaces,   some don't allow it at all. Task Write two classes (or interfaces) Camera and MobilePh...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the...
#PARI.2FGP
PARI/GP
use Inline C => q{ char *copy; char * c_dup(char *orig) { return copy = strdup(orig); } void c_free() { free(copy); } }; print c_dup('Hello'), "\n"; c_free();
Give a code snippet in #PARI.2FGP Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content ...
christopher/rosetta-code
http://rosettacode.org/wiki/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
#PSQL
PSQL
EXECUTE BLOCK RETURNS(S VARCHAR(40)) AS BEGIN S = 'Hello world!'; SUSPEND; END
Give a code snippet in #PSQL 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  ...
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
#TI-83_BASIC
TI-83 BASIC
  :1→A  
Give a code snippet in #TI-83_BASIC 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/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 ...
#PureBasic
PureBasic
ConsoleError("Goodbye, World!")
Give a code snippet in #PureBasic 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort
Sorting algorithms/Radix sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Fortran
Fortran
    SUBROUTINE VARRADIX(A , Siz)   ! ! No Copyright is exerted due to considerable prior art in the Public Domain. ! This Fortran version by Peter Kelly ~ peter.kelly@acm.org ! ! Permission is hereby granted, free of charge, to any person obtaining ! a copy of this software and associated documentation file...
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/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) t...
#Liberty_BASIC
Liberty BASIC
  Dim m(1,1)   Call magicSquare 5 Call magicSquare 17   End   Sub magicSquare n ReDim m(n,n) inc = 1 count = 1 row = 1 col=(n+1)/2 While count <= n*n m(row,col) = count count = count + 1 If inc < n Then inc = inc + 1 row = row - 1 col =...
Give a code snippet in #Liberty_BASIC A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
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. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#PHP
PHP
<?php $queue = new SplQueue; echo $queue->isEmpty() ? 'true' : 'false', "\n"; // empty test - returns true // $queue->dequeue(); // would raise RuntimeException $queue->enqueue(1); $queue->enqueue(2); $queue->enqueue(3); echo $queue->dequeue(), "\n"; // returns 1 echo $q...
Give a code snippet in #PHP 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. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queue...
christopher/rosetta-code
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting 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 She...
#Go
Go
package main   import "fmt"   // If your numbers happen to be in the range of Unicode code points (0 to 0x10ffff), this function // satisfies the task: func lessRune(a, b []rune) bool { return string(a) < string(b) // see also bytes.Compare }   // Otherwise, the following function satisfies the task for all integer...
Give a code snippet in #Go sorting Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Qui...
christopher/rosetta-code
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Simple_FASTA is   Current: Character;   begin Get(Current); if Current /= '>' then raise Constraint_Error with "'>' expected"; end if; while not End_Of_File loop -- read name and string Put(Get_Line & ": "); -- read name and write directly to o...
Give a code snippet in #Ada In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta...
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 ...
#Kotlin
Kotlin
  tailrec fun A(m: Long, n: Long): Long { require(m >= 0L) { "m must not be negative" } require(n >= 0L) { "n must not be negative" } if (m == 0L) { return n + 1L } if (n == 0L) { return A(m - 1L, 1L) } return A(m - 1L, A(m, n - 1L)) }   inline fun<T> tryOrNull(block: () -> T...
Give a code snippet in #Kotlin 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/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#Locomotive_Basic
Locomotive Basic
print time print time/300;"s since last reboot"
Give a code snippet in #Locomotive_Basic Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Relate...
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...
#MATLAB
MATLAB
rref([1, 2, -1, -4; 2, 3, -1, -11; -2, 0, -3, 22])
Give a code snippet in #MATLAB 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 convenie...
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#J
J
1 2+3 4 4 6
Give a code snippet in #J Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Superellipse
Superellipse
A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a superellipse with n = 2.5, and a...
#Wren
Wren
import "graphics" for Canvas, Color, Point   class Game { static init() { Canvas.resize(500, 500) // draw 200 concentric superellipses with gradually decreasing 'n'. for (a in 200..1) { superEllipse(a/80, a) } }   static update() {}   static draw(alpha) {}   ...
Give a code snippet in #Wren A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a su...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Agena
Agena
# HQ9+ interpreter   # execute an HQ9+ program in the code string - code is not case sensitive hq9 := proc( code :: string ) is local hq9Accumulator := 0; # the HQ9+ accumulator local hq9Operations  := # table of HQ9+ operations and their implemntations [ "q" ~ proc() is print( code ) end ...
Give a code snippet in #Agena Task Implement a   HQ9+   interpreter or compiler.
christopher/rosetta-code
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#C
C
#include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h>   enum { LEFT, RIGHT, STAY };   typedef struct { int state1; int symbol1; int symbol2; int dir; int state2; } transition_t;   typedef struct tape_t tape_t; struct tape_t { int symbol; tape_t *left; ...
Give a code snippet in #C One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in ...
christopher/rosetta-code
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#Wortel
Wortel
@let { im ^(%^\@table ^(@+ =) @to)    !im 4 }
Give a code snippet in #Wortel Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Mad_Libs
Mad Libs
This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game where one player prompts another...
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var string: story is ""; var string: line is ""; var integer: pos1 is 0; var integer: pos2 is 1; var string: field is ""; begin writeln("Enter a story template, terminated by an empty line:"); repeat readln(line); if ...
Give a code snippet in #Seed7 This page uses content from Wikipedia. The original article was at Mad Libs. 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) Mad Libs is a phrasal template word game w...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_join
Hash join
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash join" algorithm, and demonstrate tha...
#Elixir
Elixir
defmodule Hash do def join(table1, index1, table2, index2) do h = Enum.group_by(table1, fn s -> elem(s, index1) end) Enum.flat_map(table2, fn r -> Enum.map(h[elem(r, index2)], fn s -> {s, r} end) end) end end   table1 = [{27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18...
Give a code snippet in #Elixir An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash join...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#PureBasic
PureBasic
If OpenConsole() Define s$, a, b, p1, p2, sum, max, dm=(?EndOfMyData-?MyData) Dim Seq.i(dm/SizeOf(Integer)) CopyMemory(?MyData,@seq(),dm)   For a=0 To ArraySize(seq()) sum=0 For b=a To ArraySize(seq()) sum+seq(b) If sum>max max=sum p1=a p2=b EndIf Next Nex...
Give a code snippet in #PureBasic Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements ...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#Clojure
Clojure
(spit "file.txt" "this is a string")
Give a code snippet in #Clojure Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
christopher/rosetta-code
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Hash["The quick brown fox jumped over the lazy dog's back","MD5","HexString"]
Give a code snippet in #Mathematica.2FWolfram_Language Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information o...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. 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 body...
#.D0.9C.D0.9A-61.2F52
МК-61/52
1 0 П0 ИП0 L0 03 С/П
Give a code snippet in #.D0.9C.D0.9A-61.2F52 Task Write a   for   loop which writes a countdown from   10   to   0. 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\di...
#ALGOL_68
ALGOL 68
# maps a real s in the range [ a1, a2 ] to the range [ b1, b2 ] # # there are no checks that s is in the range or that the ranges are valid # PROC map range = ( REAL s, a1, a2, b1, b2 )REAL: b1 + ( ( s - a1 ) * ( b2 - b1 ) ) / ( a2 - a1 );   # test the mapping # FOR i FROM 0 TO 10 DO print( ( whole( i...
Give a code snippet in #ALGOL_68 Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearl...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#Raku
Raku
use MyModule;
Give a code snippet in #Raku Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/21_game
21 game
21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the running total to reach exactly ...
#Pascal
Pascal
  program Game21;   {$APPTYPE CONSOLE}   {$R *.res}   uses System.SysUtils, System.StrUtils, // for IfThen Winapi.Windows; // for ClearScreen   const HARD_MODE = True;   var computerPlayer: string = 'Computer'; humanPlayer: string = 'Player 1';   // for change color ConOut: THandle; BufInfo: TConsole...
Give a code snippet in #Pascal 21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. 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 body...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program loopdownward64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstante...
Give a code snippet in #AArch64_Assembly Task Write a   for   loop which writes a countdown from   10   to   0. 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   L...
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...
#PL.2FSQL
PL/SQL
  SET serveroutput ON DECLARE n NUMBER := 1024; BEGIN WHILE n > 0 LOOP DBMS_OUTPUT.put_line(n); n := TRUNC(n / 2); END LOOP; END; /  
Give a code snippet in #PL.2FSQL 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/Down...
christopher/rosetta-code
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the follow...
#Elm
Elm
import Maybe exposing (withDefault) import List exposing (length, tail, reverse, concat, head, append, map3) import Html exposing (Html, div, h1, text) import String exposing (join) import Svg exposing (svg) import Svg.Attributes exposing (version, width, height, viewBox,cx,cy, fill, r) import Html.App exposing (progra...
Give a code snippet in #Elm Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current g...
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 ...
#Modula-2
Modula-2
MODULE ReverseStr; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar;   PROCEDURE WriteInt(n : INTEGER); VAR buf : ARRAY[0..15] OF CHAR; BEGIN FormatString("%i", buf, n); WriteString(buf) END WriteInt;   PROCEDURE ReverseStr(in : ARRAY OF CHAR; VAR out : ARRAY OF CHA...
Give a code snippet in #Modula-2 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 Em...
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
#Batch_File
Batch File
  @echo off setlocal enabledelayedexpansion :: Define arrays of days/months we'll need set daynames=Monday Tuesday Wednesday Thursday Friday Saturday Sunday set monthnames=January February March April May June July August September October November December :: Separate the output of the 'date /t' command (outputs in ...
Give a code snippet in #Batch_File 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/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#Ruby
Ruby
t = Time.now   # textual puts t # => 2013-12-27 18:00:23 +0900   # epoch time puts t.to_i # => 1388134823   # epoch time with fractional seconds puts t.to_f # => 1388134823.9801579   # epoch time as a rational (more precision): puts Time.now.to_r # 1424900671883862959/1000000000  
Give a code snippet in #Ruby Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   D...
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#Phix
Phix
-- demo\rosetta\Colour_bars.exw with javascript_semantics include pGUI.e constant colours = {CD_BLACK, CD_RED, CD_GREEN, CD_BLUE, CD_MAGENTA, CD_CYAN, CD_YELLOW, CD_WHITE} Ihandle dlg, canvas cdCanvas cdcanvas function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/) integer {width, height} = IupGetIntInt(c...
Give a code snippet in #Phix Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
christopher/rosetta-code
http://rosettacode.org/wiki/Input_loop
Input loop
Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
#x86_Assembly
x86 Assembly
#define SYS_WRITE $1 #define SYS_OPEN $2 #define SYS_CLOSE $3 #define SYS_FSTAT $5 #define SYS_MMAP $9 #define SYS_MUNMAP $11 #define SYS_EXIT $60   // From experiments: #define FSIZEOFF 48 #define STATSIZE 144   // From Linux source: #define RDONLY $00 #define PROT_READ $0x1 #define M...
Give a code snippet in #x86_Assembly Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Forth
Forth
also minos text-label ptr click-label Variable click# click# off : click-win ( -- ) screen self window new window with X" There have been no clicks yet" text-label new dup F bind click-label ^ S[ 1 click# +! click# @ 0 <# #S s" Number of clicks: " holds #> click-label assign ]S X" Click...
Give a code snippet in #Forth Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_object_at_a_given_address
Create an object at a given address
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 |...
#ARM_Assembly
ARM Assembly
mov r0,#0x00100000 ldr r1,testData str r1,[r0] ;store 0x12345678 at address $100000 bx lr ;return from subroutine   testData: .long 0x12345678 ;VASM uses .long for 32 bit and .word for 16 bit values, unlike most ARM assemblers.
Give a code snippet in #ARM_Assembly 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 Oper...
christopher/rosetta-code
http://rosettacode.org/wiki/Playing_cards
Playing cards
Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the current contents of a deck Each card mu...
#JavaScript
JavaScript
function Card(pip, suit) { this.pip = pip; this.suit = suit;   this.toString = function () { return this.pip + ' ' + this.suit; }; }   function Deck() { var pips = '2 3 4 5 6 7 8 9 10 Jack Queen King Ace'.split(' '); var suits = 'Clubs Hearts Spades Diamonds'.split(' '); this.deck =...
Give a code snippet in #JavaScript Task Create a data structure and the associated methods to define and manipulate a deck of   playing cards. The deck should contain 52 unique cards. The methods must include the ability to:   make a new deck   shuffle (randomize) the deck   deal from the deck   print the curr...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail 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 ...
#Eiffel
Eiffel
    class COCKTAIL_SORT [G -> COMPARABLE]   feature   cocktail_sort (ar: ARRAY [G]): ARRAY [G] -- Array sorted in ascending order. require ar_not_empty: ar.count >= 1 local not_swapped: BOOLEAN sol: ARRAY [G] i, j: INTEGER t: G do create Result.make_empty Result.deep_copy (ar) from ...
Give a code snippet in #Eiffel Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#RapidQ
RapidQ
  RANDOMIZE number = rnd(10) + 1 Print "I selected a number between 1 and 10, try to find it:" + chr$(10)   while Guess <> Number input "Your guess: "; Guess wend   print "You guessed right, well done !" input "Press enter to quit";a$  
Give a code snippet in #RapidQ Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environ...
#Factor
Factor
IN: scratchpad "\"Hello, World!\" print" ( -- ) eval Hello, World! IN: scratchpad 4 5 "+" ( a b -- c ) eval 9
Give a code snippet in #Factor Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applic...
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 ...
#Ruby
Ruby
Sedol_char = "0123456789BCDFGHJKLMNPQRSTVWXYZ" Sedolweight = [1,3,1,7,3,9]   def char2value(c) raise ArgumentError, "Invalid char #{c}" unless Sedol_char.include?(c) c.to_i(36) end   def checksum(sedol) raise ArgumentError, "Invalid length" unless sedol.size == Sedolweight.size sum = sedol.chars.zip(Sedolweight...
Give a code snippet in #Ruby 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl...
#Haskell
Haskell
import System.Environment (getArgs)   -- Pascal's triangle. pascal :: [[Integer]] pascal = [1] : map (\row -> 1 : zipWith (+) row (tail row) ++ [1]) pascal   -- The Catalan numbers from Pascal's triangle. This uses a method from -- http://www.cut-the-knot.org/arithmetic/algebra/CatalanInPascal.shtml -- (see "Grimaldi"...
Give a code snippet in #Haskell Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that ge...
christopher/rosetta-code
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#Lingo
Lingo
on testFunc () repeat with i = 1 to 1000000 x = sqrt(log(i)) end repeat end
Give a code snippet in #Lingo Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#JavaScript
JavaScript
function gcd(a,b) { a = Math.abs(a); b = Math.abs(b);   if (b > a) { var temp = a; a = b; b = temp; }   while (true) { a %= b; if (a === 0) { return b; } b %= a; if (b === 0) { return a; } } }
Give a code snippet in #JavaScript Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   gre...
christopher/rosetta-code
http://rosettacode.org/wiki/First-class_functions/Use_numbers_analogously
First-class functions/Use numbers analogously
In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a m...
#11l
11l
V (x, xi, y, yi) = (2.0, 0.5, 4.0, 0.25) V z = x + y V zi = 1.0 / (x + y) V multiplier = (n1, n2) -> (m -> @=n1 * @=n2 * m) V numlist = [x, y, z] V numlisti = [xi, yi, zi] print(zip(numlist, numlisti).map((n, inversen) -> multiplier(inversen, n)(.5)))
Give a code snippet in #11l In First-class functions, a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create...
christopher/rosetta-code
http://rosettacode.org/wiki/Set_consolidation
Set consolidation
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input sets if they share a common item...
#D
D
import std.stdio, std.algorithm, std.array;   dchar[][] consolidate(dchar[][] sets) @safe { foreach (set; sets) set.sort();   foreach (i, ref si; sets[0 .. $ - 1]) { if (si.empty) continue; foreach (ref sj; sets[i + 1 .. $]) if (!sj.empty && !si.setIntersection(sj...
Give a code snippet in #D Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input sets ...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#Plain_English
Plain English
The low number is 1.   The high number is 100.   To run: Start up. Play the guessing game. Wait for the escape key. Shut down.   To play the guessing game: Pick a secret number between the low number and the high number. Write "I chose a secret number between " then the low number then " and " then the high number then...
Give a code snippet in #Plain_English Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. R...
#LSL
LSL
vector vSCALE = <2.0, 3.0, 4.0>; default { state_entry() { llSetScale(vSCALE); } }
Give a code snippet in #LSL Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is a...
christopher/rosetta-code
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#TXR
TXR
@(next :env) @(collect) @VAR=@VAL @(end)
Give a code snippet in #TXR Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/Sleep
Sleep
Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread for the given amount of time. ...
#Ruby
Ruby
seconds = gets.to_f puts "Sleeping..." sleep(seconds) # number is in seconds ... but accepts fractions # Minimum resolution is system dependent. puts "Awake!"
Give a code snippet in #Ruby Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread ...
christopher/rosetta-code
http://rosettacode.org/wiki/CUSIP
CUSIP
This page uses content from Wikipedia. The original article was at CUSIP. 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) A   CUSIP   is a nine-character alphanumeric code that identifies a North A...
#Python
Python
#!/usr/bin/env python3   import math   def cusip_check(cusip): if len(cusip) != 9: raise ValueError('CUSIP must be 9 characters')   cusip = cusip.upper() total = 0 for i in range(8): c = cusip[i] if c.isdigit(): v = int(c) elif c.isalpha(): p = ord...
Give a code snippet in #Python This page uses content from Wikipedia. The original article was at CUSIP. 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) A   CUSIP   is a nine-character alphanumeri...
christopher/rosetta-code
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactl...
#Eiffel
Eiffel
  class APPLICATION   create make   feature   fang_check (original, fang1, fang2: INTEGER_64): BOOLEAN -- Are 'fang1' and 'fang2' correct fangs of the 'original' number? require original_positive: original > 0 fangs_positive: fang1 > 0 and fang2 > 0 local original_length: INTEGER fang, ori: STRING...
Give a code snippet in #Eiffel A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#AWK
AWK
  # syntax: GAWK -f POPULATION_COUNT.AWK # converted from VBSCRIPT BEGIN { nmax = 30 b = 3 n = 0 bb = 1 for (i=1; i<=nmax; i++) { list = list pop_count(bb) " " bb *= b } printf("%s^n: %s\n",b,list) for (j=0; j<=1; j++) { c = (j == 0) ? "evil" : "odious" i = n = 0 ...
Give a code snippet in #AWK Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count ...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack
Stack
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. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#LOLCODE
LOLCODE
HAI 2.3 HOW IZ I Init YR Stak Stak HAS A Length ITZ 0 IF U SAY SO   HOW IZ I Push YR Stak AN YR Value Stak HAS A SRS Stak'Z Length ITZ Value Stak'Z Length R SUM OF Stak'Z Length AN 1 IF U SAY SO   HOW IZ I Top YR Stak FOUND YR Stak'Z SRS DIFF OF Stak'Z Length AN 1 IF U SAY SO   HOW IZ I Pop YR Stak I HAS A T...
Give a code snippet in #LOLCODE 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. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Racket
Racket
#lang racket (collect-garbage) ; This function forces a garbage collection   (current-memory-use) ;Gives an estimate on the memory use based on the last garbage collection   (custodian-require-memory <limit-custodian> <amount> <stop-custodian>) ; Registers a check on ...
Give a code snippet in #Racket Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. ...
#Julia
Julia
for filename in readdir("/foo/bar") if endswith(filename, ".mp3") print(filename) end end
Give a code snippet in #Julia Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Soundex
Soundex
Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution There is a major issue in many of the ...
#UNIX_Shell
UNIX Shell
declare -A value=( [B]=1 [F]=1 [P]=1 [V]=1 [C]=2 [G]=2 [J]=2 [K]=2 [Q]=2 [S]=2 [X]=2 [Z]=2 [D]=3 [T]=3 [L]=4 [M]=5 [N]=5 [R]=6 )
Give a code snippet in #UNIX_Shell Soundex is an algorithm for creating indices for words based on their pronunciation. Task The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling   (from the   soundex   Wikipedia article). Caution Th...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections ...
#Oforth
Oforth
Object Class new: DNode(value, mutable prev, mutable next)
Give a code snippet in #Oforth Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: C...
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...
#Perl
Perl
#!/usr/bin/perl   use strict; use warnings; use Tk; use Tk::Dialog; use Tk::LabFrame;   my $value = 0;   my $mw = MainWindow->new; $mw->title( 'GUI component interaction' ); my $lf = $mw->LabFrame( -label => 'Value' )->pack(-fill => 'x',-expand => 1); $lf->Entry( -width => 10, -textvariable => \$value, -validate => '...
Give a code snippet in #Perl 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 in...
christopher/rosetta-code
http://rosettacode.org/wiki/Brilliant_numbers
Brilliant numbers
Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10. Brilliant numbers are useful in cryptography and when testing prime factoring algorithms. E.G. 3 × 3 (9) is a bri...
#ALGOL_68
ALGOL 68
BEGIN # Find Brilliant numbers - semi-primes whose two prime factors have # # the same number of digits # PR read "primes.incl.a68" PR # include prime utilities # INT max prime = 1 010; # maximum prime we will consider # ...
Give a code snippet in #ALGOL_68 Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10. Brilliant numbers are useful in cryptography and when testing prime factoring algor...
christopher/rosetta-code
http://rosettacode.org/wiki/Fivenum
Fivenum
Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the   R   programming language i...
#zkl
zkl
var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) fcn fiveNum(v){ // V is a GSL Vector, --> min, 1st qu, median, 3rd qu, max v.sort(); return(v.min(),v.quantile(0.25),v.median(),v.quantile(0.75),v.max()) }
Give a code snippet in #zkl Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#Phix
Phix
function is_perfect(integer n) return sum(factors(n,-1))=n end function for i=2 to 100000 do if is_perfect(i) then ?i end if end for
Give a code snippet in #Phix Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself)...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Rust
Rust
fn insertion_sort<T: std::cmp::Ord>(arr: &mut [T]) { for i in 1..arr.len() { let mut j = i; while j > 0 && arr[j] < arr[j-1] { arr.swap(j, j-1); j = j-1; } } }
Give a code snippet in #Rust Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#ALGOL_60
ALGOL 60
expression::= if conditional_expression then expression else expression K:=if X=Y then I else J
Give a code snippet in #ALGOL_60 Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Comm...
christopher/rosetta-code
http://rosettacode.org/wiki/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/sub...
#Common_Lisp
Common Lisp
(defun biased (n) (if (zerop (random n)) 0 1))   (defun unbiased (n) (loop with x do (if (/= (setf x (biased n)) (biased n)) (return x))))   (loop for n from 3 to 6 do (let ((u (loop repeat 10000 collect (unbiased n))) (b (loop repeat 10000 collect (biased n)))) (format t "~a: unbiased ~d bia...
Give a code snippet in #Common_Lisp P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number gene...
christopher/rosetta-code
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#F.23
F#
  // Move-to-front algorithm . Nigel Galloway: March 1st., 2021 let fN g=List.permute(fun n->match compare n g with 0->0 |1->n |_->n+1) let decode n=let rec fG n g=[|match n with n::t->yield List.item n g; yield! fG t (fN n g)|_->()|] in fG n ['a'..'z']|>System.String let encode n=let rec fG n g=[match n with n::t->let...
Give a code snippet in #F.23 Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful ...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack
Stack
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. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#ABAP
ABAP
  report z_stack.   interface stack. methods: push importing new_element type any returning value(new_stack) type ref to stack,   pop exporting top_element type any returning value(new_stack) type ref to stack,   empty returning ...
Give a code snippet in #ABAP 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. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is acc...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#APL
APL
'.',⍨¨ ','(≠⊆⊢)'abc,123,X' ⍝ [1] Do the split: ','(≠⊆⊢)'abc,123,X'; [2] append the periods: '.',⍨¨ abc. 123. X. ⍝ 3 strings (char vectors), each with a period at the end.  
Give a code snippet in #APL Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks rela...
christopher/rosetta-code
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial ...
#Sidef
Sidef
func binprime(p) { p >= 2 || return false for i in (1 .. p>>1) { (binomial(p, i) % p) && return false } return true }   func coef(n, e) { (e == 0) && return "#{n}" (n == 1) && (n = "") (e == 1) ? "#{n}x" : "#{n}x^#{e}" }   func binpoly(p) { join(" ", coef(1, p), ^p -> map {|i| ...
Give a code snippet in #Sidef The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Sidef
Sidef
var max = 12 var width = (max**2 -> len+1)   func fmt_row(*items) { items.map {|s| "%*s" % (width, s) }.join }   say fmt_row('x┃', (1..max)...) say "#{'━' * (width - 1)}╋#{'━' * (max * width)}"   { |i|  say fmt_row("#{i}┃", {|j| i <= j ? i*j : ''}.map(1..max)...) } << 1..max
Give a code snippet in #Sidef Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
christopher/rosetta-code
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n ...
#Quackery
Quackery
[ $ "bigrat.qky" loadfile ] now!   [ 1 & not ] is even ( n --> b )   [ nip 1 = ] is vint ( n/d --> b )   [ [ dup even while 1 >> again ] 1 = ] is powerof2 ( n --> b )   [ 0 swap [ dup even while dip 1+ ...
Give a code snippet in #Quackery FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an ini...
christopher/rosetta-code
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for ...
#Vala
Vala
stdout.printf ("UTF-8 encoded string. Let's go to a café!");
Give a code snippet in #Vala As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an...
#Pascal
Pascal
procedure dcr(step,dir:integer;length:real); begin; step:=step -1; length:= length/sqrt(2); if dir > 0 then begin if step > 0 then begin turnright(45); dcr(step,1,length); turnleft(90); dcr(step,0,length); turnright(45); end else begin turnrig...
Give a code snippet in #Pascal Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed b...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_pentagon
Sierpinski pentagon
Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4. See also Sierpinski pentagon
#VBA
VBA
Private Sub sierpinski(Order_ As Integer, Side As Double) Dim Circumradius As Double, Inradius As Double Dim Height As Double, Diagonal As Double, HeightDiagonal As Double Dim Pi As Double, p(5) As String, Shp As Shape Circumradius = Sqr(50 + 10 * Sqr(5)) / 10 Inradius = Sqr(25 + 10 * Sqr(5)) / 10 ...
Give a code snippet in #VBA Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4. See also Sierpinski pentagon
christopher/rosetta-code
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#Kotlin
Kotlin
// version 1.1.2   import java.util.Random   fun montyHall(games: Int) { var switchWins = 0 var stayWins = 0 val rnd = Random() (1..games).forEach { val doors = IntArray(3) // all zero (goats) by default doors[rnd.nextInt(3)] = 1 // put car in a random door val choice...
Give a code snippet in #Kotlin Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for th...
christopher/rosetta-code
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Pure
Pure
  using system;   printf "There are %d command line argumants\n" argc; puts "They are " $$ map (puts) argv;  
Give a code snippet in #Pure Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
christopher/rosetta-code
http://rosettacode.org/wiki/Statistics/Normal_distribution
Statistics/Normal distribution
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random number generator and create a ...
#PARI.2FGP
PARI/GP
rnormal()={ my(u1=random(1.),u2=random(1.); sqrt(-2*log(u1))*cos(2*Pi*u1) \\ Could easily be extended with a second normal at very little cost. }; mean(v)={ sum(i=1,#v,v[i])/#v }; stdev(v,mu="")={ if(mu=="",mu=mean(v)); sqrt(sum(i=1,#v,(v[i]-mu)^2))/#v }; histogram(v,bins=16,low=0,high=1)={ my(u=vector(bins)...
Give a code snippet in #PARI.2FGP The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform ra...
christopher/rosetta-code
http://rosettacode.org/wiki/Cramer%27s_rule
Cramer's rule
linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1...
#Phix
Phix
requires("0.8.4") with javascript_semantics constant inf = 1e300*1e300, nan = -(inf/inf) function det(sequence a) atom res = 1 a = deep_copy(a) integer l = length(a) for j=1 to l do integer i_max = j for i=j+1 to l do if a[i][j] > a[i_max][j] then ...
Give a code snippet in #Phix linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_...
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).
#PureBasic
PureBasic
OpenConsole() If CreateJSON(1) PB_Team_Members=SetJSONObject(JSONValue(1)) SetJSONString(AddJSONMember(PB_Team_Members,"PB_Team_Member_1"),"Frederic Laboureur") SetJSONString(AddJSONMember(PB_Team_Members,"PB_Team_Member_2"),"Andre Beer") SetJSONString(AddJSONMember(PB_Team_Members,"PB_Team_Member_3"),"Timo Har...
Give a code snippet in #PureBasic 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/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) ...
#Maple
Maple
seq(print(`if`(modp(n,3)=0,`if`(modp(n,15)=0,"FizzBuzz","Fizz"),`if`(modp(n,5)=0,"Buzz",n))),n=1..100):
Give a code snippet in #Maple 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Checkpoint_synchronization
Checkpoint synchronization
The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before st...
#D
D
import std.stdio; import std.parallelism: taskPool, defaultPoolThreads, totalCPUs;   void buildMechanism(uint nparts) { auto details = new uint[nparts]; foreach (i, ref detail; taskPool.parallel(details)) { writeln("Build detail ", i); detail = i; }   // This could be written more concis...
Give a code snippet in #D The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first mus...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#FutureBasic
FutureBasic
window 1, @"Roots of Unity", (0,0,1050,200)   long n, root double real, imag   for n = 2 to 7 print n;":" ; for root = 0 to n-1 real = cos( 2 * pi * root / n) imag = sin( 2 * pi * root / n) print using "-##.#####"; real;using "-##.#####"; imag; "i"; if root != n-1 then print ","; next print next...
Give a code snippet in #FutureBasic The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
christopher/rosetta-code
http://rosettacode.org/wiki/Topic_variable
Topic variable
Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate h...
#Scala
Scala
object TopicVar extends App { class SuperString(val org: String){ def it(): Unit = println(org) }   new SuperString("FvdB"){it()} new SuperString("FvdB"){println(org)}   Seq(1).foreach {println} Seq(2).foreach {println(_)} Seq(4).foreach { it => println(it)} Seq(8).foreach { it => println(it + it)} ...
Give a code snippet in #Scala Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic variable within the langua...
christopher/rosetta-code