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/Web_scraping
Web scraping
Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page. If possible,...
#Objeck
Objeck
  use Net; use IO; use Structure;   bundle Default { class Scrape { function : Main(args : String[]) ~ Nil { client := HttpClient->New(); lines := client->Get("http://tycho.usno.navy.mil/cgi-bin/timer.pl", 80);   i := 0; found := false; while(found <> true & i < lines->Size()) { ...
Give a code snippet in #Objeck Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this p...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var integer: number is 0; begin repeat incr(number); writeln(number) until number rem 6 = 0 end func;
Give a code snippet in #Seed7 Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/D...
christopher/rosetta-code
http://rosettacode.org/wiki/GUI/Maximum_window_dimensions
GUI/Maximum window dimensions
The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling. This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations an...
#Run_BASIC
Run BASIC
  html "<INPUT TYPE='HIDDEN' id='winHigh' name='winHigh' VALUE='";winHigh;"'></input>" html "<INPUT TYPE='HIDDEN' id='winWide' name='winWide' VALUE='";winWide;"'></input>"   html "<script> <!--   function winSize() { var myWide = 0, myHigh = 0; if( typeof( window.innerWidth ) == 'number' ) { //Non-IE myWide = window.i...
Give a code snippet in #Run_BASIC The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling. This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any ad...
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#Sidef
Sidef
class Accumulator(sum) { method add(num) { sum += num; } }   var x = Accumulator(1); x.add(5); Accumulator(3); say x.add(2.3); # prints: 8.3
Give a code snippet in #Sidef A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values pas...
christopher/rosetta-code
http://rosettacode.org/wiki/Metered_concurrency
Metered concurrency
The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active ...
#D
D
module meteredconcurrency ; import std.stdio ; import std.thread ; import std.c.time ;   class Semaphore { private int lockCnt, maxCnt ; this(int count) { maxCnt = lockCnt = count ;} void acquire() { if(lockCnt < 0 || maxCnt <= 0) throw new Exception("Negative Lock or Zero init. Lock") ; while(lockC...
Give a code snippet in #D The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, relea...
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#Ceylon
Ceylon
shared void run() { Integer|Float accumulator (variable Integer|Float n) (Integer|Float i) => switch (i) case (is Integer) (n = n.plusInteger(i)) case (is Float) (n = i + (switch(prev = n) case (is Flo...
Give a code snippet in #Ceylon A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values pa...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Ol
Ol
  (define (quicksort l ??) (if (null? l) '() (append (quicksort (filter (lambda (x) (?? (car l) x)) (cdr l)) ??) (list (car l)) (quicksort (filter (lambda (x) (not (?? (car l) x))) (cdr l)) ??))))   (print (quicksort (list 1 3 5 9 8 6 4 3 2) >)) (print (quicksort (iota ...
Give a code snippet in #Ol 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/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
#ALGOL-M
ALGOL-M
BEGIN WRITE( "Hello world!" ); END
Give a code snippet in #ALGOL-M 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/Negative_base_numbers
Negative base numbers
Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2] Task Encode the decimal number 10 as negabinary (expect 11110) Encode the decimal number 146 as negaternary...
#zkl
zkl
fcn toNBase(n,radix){ var [const] cs=[0..9].chain(["a".."z"]).pump(String); //"0123456789abcd..z" _assert_(-37 < radix < -1,"invalid radix"); digits:=List(); while(n){ reg r; n,r=n.divr(radix); // C compiler semantics if(r<0){ n+=1; r-=radix; } digits.append(r); } digits.reverse().p...
Give a code snippet in #zkl Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).[1][2] Task Encode the decimal number 10 as negabinary (expect 11110) Encode the deci...
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...
#Ring
Ring
  # Project : Cumulative standard deviation   decimals(6) sdsave = list(100) sd = "2,4,4,4,5,5,7,9" sumval = 0 sumsqs = 0   for num = 1 to 8 sd = substr(sd, ",", "") stddata = number(sd[num]) sumval = sumval + stddata sumsqs = sumsqs + pow(stddata,2) standdev = pow(((sumsqs / num) - pow((sumv...
Give a code snippet in #Ring 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 functi...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#SPL
SPL
t = ["abc","J̲o̲s̲é̲","møøse","𝔘𝔫𝔦𝔠𝔬𝔡𝔢"]   > i, 1..#.size(t,1)  ? i>1, #.output() #.output(#.quot,t[i],#.quot," contains")   p = #.split(t[i]) cn = #.size(p,1) s = #.str(cn,">3>")+" chars: " > j, 1..cn  ? j>1, s += ", " s += p[j] < #.output(s)   q = #.array(t[i]) bn = #.size(q,1) s = ...
Give a code snippet in #SPL Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme contai...
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
#Pony
Pony
var counter: I32 = 10 // mutable variable 'counter' with value 10 let temp: F64 = 36.6 // immutable variable 'temp' let str: String // immutable variable 'str' with no initial value str = "i am a string" // variables must be initialized before use let another_str = "i am another string" // type of variable 'anot...
Give a code snippet in #Pony 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/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#Ela
Ela
open monad io   loop m n | n < m = do loop' n 0 putStrLn "" loop m (n + 1) | else = do return () where loop' m n | n <= m = do putStr "*" loop' m (n + 1) | else = do return ()   _...
Give a code snippet in #Ela “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structure...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by...
#ALGOL-M
ALGOL-M
  BEGIN   INTEGER I, K, M, N, S, NPRIMES, DIVISIBLE, FALSE, TRUE;   COMMENT COMPUTE P MOD Q; INTEGER FUNCTION MOD (P, Q); INTEGER P, Q; BEGIN MOD := P - Q * (P / Q); END;   COMMENT MAIN PROGRAM BEGINS HERE;   WRITE ("HOW MANY PRIMES DO YOU WANT TO GENERATE?"); READ (NPRIMES); BEGIN INTEGER ARRAY P[1:NPRIMES]; ...
Give a code snippet in #ALGOL-M Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being ...
christopher/rosetta-code
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#Common_Lisp
Common Lisp
(defun sub-rand (state) (let ((x (last state)) (y (last state 25))) ;; I take "circular buffer" very seriously (until some guru ;; points out it's utterly wrong thing to do) (setf (cdr x) state) (lambda () (setf x (cdr x) y (cdr y) (car x) (mod (- (car x) (car y)) (expt 10 9))))))   ;; r...
Give a code snippet in #Common_Lisp A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\...
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...
#XBS
XBS
set x=1; set y=2; log("Before Swap"); log(x); log(y); swap x y; log("After Swap"); log(x); log(y);
Give a code snippet in #XBS 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....
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#8th
8th
  \ Adapted from the C version: : remap \ n1 -- n2 [0,2,4,6,8,1,3,5,7,9] swap caseof ;   : luhn \ s -- f 0 swap s:rev ( '0 n:- swap 2 n:mod if remap then n:+ ) s:each 10 n:mod not ;   : test-luhn \ s -- dup . space luhn if "OK" else "FAIL" then . cr ;   "49927398716" test-luhn "4992739871...
Give a code snippet in #8th The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of t...
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#6502_Assembly
6502 Assembly
  .lf evenodd6502.lst .cr 6502 .tf evenodd6502.obj,ap1 ;------------------------------------------------------ ; Even or Odd for the 6502 by barrym95838 2014.12.10 ; Thanks to sbprojects.com for a very nice assembler! ; The target for this assembly is an Apple II with ; mixed-case output ca...
Give a code snippet in #6502_Assembly Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is od...
christopher/rosetta-code
http://rosettacode.org/wiki/Almkvist-Giullera_formula_for_pi
Almkvist-Giullera formula for pi
The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 This formula can be used to calcul...
#Sidef
Sidef
func almkvist_giullera(n) { (32 * (14*n * (38*n + 9) + 9) * (6*n)!) / (3 * n!**6) }   func almkvist_giullera_pi(prec = 70) {   local Num!PREC = (4*(prec+1)).numify   var sum = 0 var target = -1   for n in (0..Inf) { sum += (almkvist_giullera(n) / (10**(6*n + 3))) var curr = (sum**-.5...
Give a code snippet in #Sidef The Almkvist-Giullera formula for calculating   1/π2   is based on the Calabi-Yau differential equations of order 4 and 5,   which were originally used to describe certain manifolds in string theory. The formula is: 1/π2 = (25/3) ∑0∞ ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 Thi...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-transitive_dice
Non-transitive dice
Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 defined sides is defined by the numb...
#Kotlin
Kotlin
fun fourFaceCombos(): List<Array<Int>> { val res = mutableListOf<Array<Int>>() val found = mutableSetOf<Int>() for (i in 1..4) { for (j in 1..4) { for (k in 1..4) { for (l in 1..4) { val c = arrayOf(i, j, k, l) c.sort() ...
Give a code snippet in #Kotlin Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 defi...
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 |...
#Seed7
Seed7
const proc: writeLogic (in boolean: a, in boolean: b) is func begin writeln("a and b is " <& a and b); writeln("a or b is " <& a or b); writeln("not a is " <& not a); end func;
Give a code snippet in #Seed7 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/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...
#Agda
Agda
factorial : ℕ → ℕ factorial zero = 1 factorial (suc n) = suc n * factorial n
Give a code snippet in #Agda Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
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 ...
#VBScript
VBScript
sub swap( byref a, byref b ) dim tmp tmp = a a = b b = tmp end sub   'knuth shuffle (I think) function shuffle( a ) dim i dim r randomize timer for i = lbound( a ) to ubound( a ) r = int( rnd * ( ubound( a ) + 1 ) ) if r <> i then swap a(i), a(r) end if next shuffle = a end function   function inOr...
Give a code snippet in #VBScript 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/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Delphi
Delphi
program AssociativeArrayIteration;   {$APPTYPE CONSOLE}   uses SysUtils, Generics.Collections;   var i: Integer; s: string; lDictionary: TDictionary<string, Integer>; lPair: TPair<string, Integer>; begin lDictionary := TDictionary<string, Integer>.Create; try lDictionary.Add('foo', 5); lDictionary.A...
Give a code snippet in #Delphi Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definitio...
#zkl
zkl
class Node{ fcn init(_value,_prev=Void,_next=Void) { var value=_value, prev=_prev, next=_next; } fcn toString{ value.toString() } fcn append(value){ // loops not allowed: create a new Node b,c := Node(value,self,next),next; next=b; if(c) c.prev=b; b } fcn delete{ if(...
Give a code snippet in #zkl Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 ...
#REXX
REXX
/*REXX program uses a circle sort algorithm to sort an array (or list) of numbers. */ parse arg x /*obtain optional arguments from the CL*/ if x='' | x="," then x= 6 7 8 9 2 5 3 4 1 /*Not specified? Then use the default.*/ call make_array 'before sort:' ...
Give a code snippet in #REXX 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/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...
#REXX
REXX
/*(below) returns a random integer between 100 & 200, inclusive.*/   y = random(100, 200)
Give a code snippet in #REXX 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Java
Java
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException;   public class ReadFile { public static void main(String[] args) throws IOException{ String fileContents = readEntireFile("./foo.txt"); }   private static String readEntireFile(String filename) throws IOException {...
Give a code snippet in #Java Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished increm...
christopher/rosetta-code
http://rosettacode.org/wiki/Topswops
Topswops
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is composed of reversing the first  ...
#11l
11l
V best = [0] * 16   F try_swaps(&deck, f, =s, d, n) I d > :best[n]  :best[n] = d   V i = 0 V k = 1 << s L s != 0 k >>= 1 s-- I deck[s] == -1 | deck[s] == s L.break i [|]= k I (i [&] f) == i & d + :best[s] <= :best[n] R d s++   V deck2 = copy(deck) ...
Give a code snippet in #11l Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is comp...
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 ...
#Kotlin
Kotlin
// version 1.1.2   val rand = java.util.Random()   fun normalStats(sampleSize: Int) { if (sampleSize < 1) return val r = DoubleArray(sampleSize) val h = IntArray(12) // all zero by default /* Generate 'sampleSize' normally distributed random numbers with mean 0.5 and SD 0.25 and calculate ...
Give a code snippet in #Kotlin 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 rando...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Shell "dir" Sleep
Give a code snippet in #FreeBASIC Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#R
R
> magic(5) [,1] [,2] [,3] [,4] [,5] [1,] 17 24 1 8 15 [2,] 23 5 7 14 16 [3,] 4 6 13 20 22 [4,] 10 12 19 21 3 [5,] 11 18 25 2 9
Give a code snippet in #R 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In ...
#11l
11l
F hamming(limit) V h = [1] * limit V (x2, x3, x5) = (2, 3, 5) V i = 0 V j = 0 V k = 0   L(n) 1 .< limit h[n] = min(x2, x3, x5) I x2 == h[n] i++ x2 = 2 * h[i] I x3 == h[n] j++ x3 = 3 * h[j] I x5 == h[n] k++ x5 = 5 * h[k] R...
Give a code snippet in #11l Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming number...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#F.C5.8Drmul.C3.A6
Fōrmulæ
# find primes using Wilson's theorem: # p is prime if ( ( p - 1 )! + 1 ) mod p = 0   isWilsonPrime := function( p ) local fModP, i; fModP := 1; for i in [ 2 .. p - 1 ] do fModP := fModP * i; fModP := fModP mod p; od; return fModP = p - 1; end; # isWilsonPrime   prime := []; for i in [ -4 .. 100 ] do ...
Give a code snippet in #F.C5.8Drmul.C3.A6 Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson'...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#COBOL
COBOL
PROGRAM-ID. increment-num-str.   DATA DIVISION. WORKING-STORAGE SECTION. 01 str PIC X(5) VALUE "12345". 01 num REDEFINES str PIC 9(5).   PROCEDURE DIVISION. DISPLAY str ADD 1 TO num DISPLAY str   ...
Give a code snippet in #COBOL Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#Ezhil
Ezhil
  ## இந்த நிரல் தொடர் கூட்டல் (Sum Of Series) என்ற வகையைச் சேர்ந்தது   ## இந்த நிரல் ஒன்று முதல் தரப்பட்ட எண் வரை 1/(எண் * எண்) எனக் கணக்கிட்டுக் கூட்டி விடை தரும்   நிரல்பாகம் தொடர்க்கூட்டல்(எண்1)   எண்2 = 0   @(எண்3 = 1, எண்3 <= எண்1, எண்3 = எண்3 + 1) ஆக   ## ஒவ்வோர் எண்ணின் வர்க்கத்தைக் கணக்கிட்டு, ஒன்றை அதன...
Give a code snippet in #Ezhil Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Plasma_effect
Plasma effect
The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid. Task Create a plasma effect. See also Computer Graphics Tutorial (lod...
#C
C
  #include<windows.h> #include<stdlib.h> #include<stdio.h> #include<time.h> #include<math.h>   #define pi M_PI   int main() { CONSOLE_SCREEN_BUFFER_INFO info; int cols, rows; time_t t; int i,j;   GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info); cols = info.srWindow.Right - info.srWindo...
Give a code snippet in #C The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid. Task Create a plasma effect. See also Comp...
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...
#Scala
Scala
import javax.swing.JFrame import java.awt.Graphics   class DragonCurve(depth: Int) extends JFrame(s"Dragon Curve (depth $depth)") {   setBounds(100, 100, 800, 600); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   val len = 400 / Math.pow(2, depth / 2.0); val startingAngle = -depth * (Math.PI / 4); val steps...
Give a code snippet in #Scala 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#Modula-2
Modula-2
PROCEDURE Multiply(a, b: INTEGER): INTEGER; BEGIN RETURN a * b END Multiply;
Give a code snippet in #Modula-2 A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distra...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#HicEst
HicEst
DO n = 1, 1E6 Euler = n^2 + n + 41 IF( Prime(Euler) == 0 ) WRITE(Messagebox) Euler, ' is NOT prime for n =', n ENDDO ! e.g. 1681 = 40^2 + 40 + 41 is NOT prime END   FUNCTION Prime(number) Prime = number == 2 IF( (number > 2) * MOD(number,2) ) THEN DO i = 3, numbe...
Give a code snippet in #HicEst Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loop...
christopher/rosetta-code
http://rosettacode.org/wiki/Zeckendorf_arithmetic
Zeckendorf arithmetic
This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operation functions. Addition Like bin...
#Elena
Elena
import extensions;   const dig = new string[]{"00","01","10"}; const dig1 = new string[]{"","1","10"};   sealed struct ZeckendorfNumber { int dVal; int dLen;   clone() = ZeckendorfNumber.newInternal(dVal,dLen);   cast n(string s) { int i := s.Length - 1; int q := 1;   ...
Give a code snippet in #Elena This task is a total immersion zeckendorf task; using decimal numbers will attract serious disapprobation. The task is to implement addition, subtraction, multiplication, and division using Zeckendorf number representation. Optionally provide decrement, increment and comparitive operatio...
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 ...
#Prolog
Prolog
%____________________________________________________________________ % Implements the American soundex algorithm % as described at https://en.wikipedia.org/wiki/Soundex % In SWI Prolog, a 'string' is specified in 'single quotes', % while a "list of codes" may be specified in "double quotes". % So, "abc" is equi...
Give a code snippet in #Prolog 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 ...
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 ...
#Kotlin
Kotlin
// version 1.1.2 // need to enable runtime assertions with JVM -ea option   import java.lang.management.ManagementFactory import java.lang.management.ThreadMXBean   fun countTo(x: Int) { println("Counting..."); (1..x).forEach {} println("Done!") }   fun main(args: Array<String>) { val counts = intArrayO...
Give a code snippet in #Kotlin 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 betwee...
christopher/rosetta-code
http://rosettacode.org/wiki/Retrieve_and_search_chat_history
Retrieve and search chat history
Task Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library. Details: The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r...
#Phix
Phix
include builtins\libcurl.e atom curl = NULL function download(string url) if curl=NULL then curl_global_init() curl = curl_easy_init() end if curl_easy_setopt(curl, CURLOPT_URL, url) object res = curl_easy_perform_ex(curl) if integer(res) then printf(1,"libcurl error %d (%s...
Give a code snippet in #Phix Task Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library. Details: The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Yabasic
Yabasic
input "ingrese un numero? " a input "ingrese otro numero? " b   print "suma ", a, " + ", b, " = ", (a + b) print "resta ", a, " - ", b, " = ", (a - b) print "producto ", a, " * ", b, " = ", (a * b) print "division ", a, " \ ", b, " = ", int(a / b) print "modulo ", a, " % ", b, " = ", mod(a, b) print "pote...
Give a code snippet in #Yabasic 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 Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Set
Set
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   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an...
#Prolog
Prolog
:- use_module(library(lists)).   set :- A = [2, 4, 1, 3], B = [5, 2, 3, 2], ( is_set(A) -> format('~w is a set~n', [A]) ; format('~w is not a set~n', [A])), ( is_set(B) -> format('~w is a set~n', [B]) ; format('~w is not a set~n', [B])),   % create a set from a list   list_to_set(B, BS), ( is_set(BS)...
Give a code snippet in #Prolog 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   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#FreeBASIC
FreeBASIC
' version 17-03-2017 ' compile with: fbc -s gui   Const As Double deg2rad = Atn(1) / 45 Dim Shared As Double scale = 0.76 Dim Shared As Double spread = 25 * deg2rad ' convert degree's to rad's   Sub branch(x1 As ULong, y1 As ULong, size As ULong, angle As Double, depth As ULong)   Dim As ULong x2, y2   x2 = x1 ...
Give a code snippet in #FreeBASIC Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
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...
#ERRE
ERRE
  PROGRAM EUCLIDE ! calculate G.C.D. between two integer numbers ! using Euclidean algorithm   !VAR J%,K%,MCD%,A%,B%   BEGIN PRINT(CHR$(12);"Input two numbers : ";)  !CHR$(147) in C-64 version INPUT(J%,K%) A%=J% B%=K% WHILE A%<>B% DO IF A%>B% THEN A%=A%-B% ELSE B%=B%-A% E...
Give a code snippet in #ERRE Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest ...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at uni...
#CoffeeScript
CoffeeScript
http = require 'http'   is_derangement = (word1, word2) -> for c, i in word1 return false if c == word2[i] true   show_longest_derangement = (word_lst) -> anagrams = {} max_len = 0   for word in word_lst continue if word.length < max_len key = word.split('').sort().join('') if anagrams[key] ...
Give a code snippet in #CoffeeScript Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols   surname = 'Unknown' -- default value surname['Fred'] = 'Bloggs' surname['Davy'] = 'Jones'   try = 'Fred' say surname[try] surname['Bert']   -- extract the keys loop fn over surname say fn.right(10) ':' surname[fn] end fn
Give a code snippet in #NetRexx Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections C...
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#NS-HUBASIC
NS-HUBASIC
10 INPUT "ENTER A NUMBER, AND I'LL DETECT IF IT'S A LEAP YEAR OR NOT. ",A 20 IF A-(A/100)*100=0 AND A-(A/400)*400<>0 THEN RESULT$="NOT " 30 PRINT "THAT'S "RESULT$"A LEAP YEAR."
Give a code snippet in #NS-HUBASIC Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   b...
#Limbo
Limbo
implement Epoch;   include "sys.m"; sys: Sys; include "draw.m"; include "daytime.m"; daytime: Daytime; Tm: import daytime;   Epoch: module { init: fn(nil: ref Draw->Context, nil: list of string); };   init(nil: ref Draw->Context, nil: list of string) { sys = load Sys Sys->PATH; daytime = load Daytime Daytime->PATH;...
Give a code snippet in #Limbo Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the s...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the...
#ALGOL_68
ALGOL 68
# RPN Expression evaluator - handles numbers and + - * / ^ # # the right-hand operand for ^ is converted to an integer #   # expression terminator # CHAR end of expression character = REPR 12;   # evaluates the specified rpn expression # PROC evaluate = ( STRING rpn expression )VOID: BEGIN   [ 256 ]REAL st...
Give a code snippet in #ALGOL_68 Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with 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.
#OCaml
OCaml
let () = let max = 12 in let fmax = float_of_int max in   let dgts = int_of_float (ceil (log10 (fmax *. fmax))) in let fmt = Printf.printf " %*d" dgts in let fmt2 = Printf.printf "%*s%c" dgts in   fmt2 "" 'x'; for i = 1 to max do fmt i done; print_string "\n\n";   for j = 1 to max do fmt j; fo...
Give a code snippet in #OCaml 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/Special_characters
Special characters
Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact...
#Raku
Raku
$ Item @ Positional  % Associative & Callable
Give a code snippet in #Raku Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pernicious_numbers
Pernicious numbers
A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,   and therefore 22   is a pe...
#Panda
Panda
fun prime(a) type integer->integer a where count{{a.factor}}==2 fun pernisc(a) type integer->integer a where sum{{a.radix:2 .char.integer}}.integer.prime   1..36.pernisc 888888877..888888888.pernisc
Give a code snippet in #Panda A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_common_subsequence
Longest common subsequence
Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of ...
#Seed7
Seed7
$ include "seed7_05.s7i";   const func string: lcs (in string: a, in string: b) is func result var string: lcs is ""; local var string: x is ""; var string: y is ""; begin if a <> "" and b <> "" then if a[length(a)] = b[length(b)] then lcs := lcs(a[.. pred(length(a))], b[.. pred(leng...
Give a code snippet in #Seed7 Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strin...
christopher/rosetta-code
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain sync...
#Oz
Oz
declare fun {Const X} fun {$ _} X end end   fun {Now} {Int.toFloat {Property.get 'time.total'}} / 1000.0 end   class Integrator from Time.repeat attr k:{Const 0.0} s:0.0 t1 k_t1 t2 k_t2   meth init(SampleIntervalMS) t1 := {Now} k_t1 := {@k @t...
Give a code snippet in #Oz In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such meth...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_syntax
Inverted syntax
Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the statement or code block: needumb...
#PARI.2FGP
PARI/GP
fi(f, condition)=if(condition,f());   if(raining, print("Umbrella needed")) fi(->print("Umbrella needed"), raining)
Give a code snippet in #PARI.2FGP Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#AutoHotkey
AutoHotkey
; --> Prompt the user to select the file being read   FileSelectFile, File, 1, %A_ScriptDir%, Select the (text) file to read, Documents (*.txt) ; Could of course be set to support other filetypes If Errorlevel ; If no file selected ExitApp   ; --> Main loop: Input (File), Output (Text)   Loop { FileReadLine, Line, %Fi...
Give a code snippet in #AutoHotkey Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#Tcl
Tcl
package require Tcl 8.6   # make the creation of coroutines without procedures simpler proc coro {name arguments body args} { coroutine $name apply [list $arguments $body] {*}$args } # Wrap the feeding of values in and out of a generator proc coloop {var body} { set val [info coroutine] upvar 1 $var v w...
Give a code snippet in #Tcl A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passe...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Logo
Logo
make "s "|My string| print butfirst :s print butlast :s print butfirst butlast :s
Give a code snippet in #Logo The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If...
christopher/rosetta-code
http://rosettacode.org/wiki/Set
Set
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   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an...
#Lua
Lua
function emptySet() return { } end function insert(set, item) set[item] = true end function remove(set, item) set[item] = nil end function member(set, item) return set[item] end function size(set) local result = 0 for _ in pairs(set) do result = result + 1 end return result end function fromTable(tbl)...
Give a code snippet in #Lua 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   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set cre...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#ARM_Assembly
ARM Assembly
ProgramStart: mov sp,#0x03000000 ;Init Stack Pointer   mov r4,#0x04000000 ;DISPCNT -LCD Control mov r2,#0x403 ;4= Layer 2 on / 3= ScreenMode 3 str r2,[r4] ;hardware specific routine, activates Game Boy's bitmap mode   mov r0,#0x61 ;ASCII "a" mov r2,#ramarea mov r1,#...
Give a code snippet in #ARM_Assembly Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#Erlang
Erlang
  -module(assoc). -compile([export_all]).   test_create() -> D = dict:new(), D1 = dict:store(foo,1,D), D2 = dict:store(bar,2,D1), print_vals(D2), print_vals(dict:store(foo,3,D2)).   print_vals(D) -> lists:foreach(fun (K) -> io:format("~p: ~b~n",[K,dict:fetch(K,D)]) ...
Give a code snippet in #Erlang Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition,...
christopher/rosetta-code
http://rosettacode.org/wiki/Interactive_programming_(repl)
Interactive programming (repl)
Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. Task Show how to start this...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
$ math
Give a code snippet in #Mathematica_.2F_Wolfram_Language Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hilbert_curve
Hilbert curve
Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
#Python
Python
'''Hilbert curve'''   from itertools import (chain, islice)     # hilbertCurve :: Int -> SVG String def hilbertCurve(n): '''An SVG string representing a Hilbert curve of degree n. ''' w = 1024 return svgFromPoints(w)( hilbertPoints(w)( hilbertTree(n) ) )     # hilb...
Give a code snippet in #Python Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
christopher/rosetta-code
http://rosettacode.org/wiki/Abstract_type
Abstract type
Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations and/or components. Abstract ...
#BASIC
BASIC
INSTALL @lib$+"CLASSLIB"   REM Declare a class with no implementation: DIM abstract{method} PROC_class(abstract{})   REM Inherit from the abstract class: DIM derived{member%} PROC_inherit(derived{}, abstract{}) PROC_class(derived{})   REM Provide an implementation f...
Give a code snippet in #BASIC Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters
Determine if a string has all unique 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 unique   indicate if or which character is duplicated and where   display each string and its length   (as the strings are being ...
#jq
jq
# Emit null if there is no duplicate, else [c, [ix1, ix2]] def firstDuplicate: label $out | foreach explode[] as $i ({ix: -1}; .ix += 1 | .ix as $ix | .iu = ([$i] | implode) | .[.iu] += [ $ix] ; if .[.iu]|length == 2 then [.iu, .[.iu]], break $out else empty end ) // null ;
Give a code snippet in #jq 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 unique   indicate if or which character is duplicated and where   display each string and its length ...
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 ≤...
#C.2B.2B
C++
// Standard input-output streams #include <iostream> using namespace std; int main() { int a, b; cin >> a >> b; cout << a + b << endl; }
Give a code snippet in #C.2B.2B 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, separa...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle n...
#Lua
Lua
function qsolve(a, b, c) if b < 0 then return qsolve(-a, -b, -c) end val = b + (b^2 - 4*a*c)^(1/2) --this never exhibits instability if b > 0 return -val / (2 * a), -2 * c / val --2c / val is the same as the "unstable" second root end   for i = 1, 12 do print(qsolve(1, 0-10^i, 1)) end
Give a code snippet in #Lua This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_proper_divisor_of_n
Largest proper divisor of n
Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
#Cowgol
Cowgol
include "cowgol.coh";   sub print3(n: uint8) is print_char(' '); if n>9 then print_char('0' + n/10); else print_char(' '); end if; print_char('0' + n%10); end sub;   sub lpd(n: uint8): (r: uint8) is if n <= 1 then r := 1; else r := n - 1; while r > 0 l...
Give a code snippet in #Cowgol Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
christopher/rosetta-code
http://rosettacode.org/wiki/Atomic_updates
Atomic updates
Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the t...
#Common_Lisp
Common Lisp
(ql:quickload '(:alexandria :stmx :bordeaux-threads))   (defpackage :atomic-updates (:use :cl))   (in-package :atomic-updates)   (defvar *buckets* nil) (defvar *running* nil)   (defun distribute (ratio a b) "Atomically redistribute the values of buckets A and B by RATIO." (stmx:atomic (let* ((sum (+ (stmx:$ a)...
Give a code snippet in #Common_Lisp Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Undefined_values
Undefined values
#C.23
C#
string foo = null;
Give a code snippet in #C.23
christopher/rosetta-code
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\inft...
#MATLAB
MATLAB
>> h = [-8,-9,-3,-1,-6,7]; >> g = [24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7]; >> f = [-3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1]; >> deconv(g,f)   ans =   -8.0000 -9.0000 -3.0000 -1.0000 -6.0000 7.0000   >> deconv(g,h)   ans =   -3 -6 -1 8 -6 3 -1 -9 ...
Give a code snippet in #MATLAB The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\d...
christopher/rosetta-code
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime is a prime number p such th...
#Racket
Racket
#lang typed/racket (require math/number-theory)   (: wieferich-prime? (-> Positive-Integer Boolean))   (define (wieferich-prime? p) (and (prime? p) (divides? (* p p) (sub1 (expt 2 (sub1 p))))))   (module+ main (define wieferich-primes<5000 (for/list : (Listof Integer) ((p (sequence-filter wieferich-prime...
Give a code snippet in #Racket This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich pri...
christopher/rosetta-code
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
Seven-sided dice from five-sided dice
Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the function created in   Simple R...
#Groovy
Groovy
random = new Random()   int rand5() { random.nextInt(5) + 1 }   int rand7From5() { def raw = 25 while (raw > 21) { raw = 5*(rand5() - 1) + rand5() } (raw % 7) + 1 }
Give a code snippet in #Groovy Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using th...
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...
#Eiffel
Eiffel
  class APPLICATION   create make   feature {NONE}   make do test := <<2, 5, 1>> permute (test, 1) end   test: ARRAY [INTEGER]   permute (a: ARRAY [INTEGER]; k: INTEGER) -- All permutations of 'a'. require count_positive: a.count > 0 k_valid_index: k > 0 local t: INTEGER do if k = a....
Give a code snippet in #Eiffel 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   gen...
christopher/rosetta-code
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives ...
#Java
Java
package org.rosettacode.zebra;   import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set;   public class Zebra {   private static final int[] orders = {1, 2, 3, 4, 5}; private static final String[] nations = {"English", "Danish", "German...
Give a code snippet in #Java Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five hou...
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      ...
#Rust
Rust
fn main() { let x = "fn main() {\n let x = "; let y = "print!(\"{}{:?};\n let y = {:?};\n {}\", x, x, y, y)\n}\n"; print!("{}{:?}; let y = {:?}; {}", x, x, y, y) }
Give a code snippet in #Rust A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive
Verify distribution uniformity/Naive
This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) producing random integers. The number of times ...
#Euler_Math_Toolbox
Euler Math Toolbox
  >function checkrandom (frand$, n:index, delta:positive real) ... $ v=zeros(1,n); $ loop 1 to n; v{#}=frand$(); end; $ K=max(v); $ fr=getfrequencies(v,1:K); $ return max(fr/n-1/K)<delta/sqrt(n); $ endfunction >function dice () := intrandom(1,1,6); >checkrandom("dice",1000000,1) 1 >wd = 0|((1:6)+[-0.01,0.01,0,0,...
Give a code snippet in #Euler_Math_Toolbox This task is an adjunct to Seven-sided dice from five-sided dice. Task Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. The function should take as arguments: The function (or object) prod...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score...
#Pascal
Pascal
Program GuessIt(input, output);   var done, ok: boolean; guess, upp, low: integer; res: char;   begin writeln ('Choose a number between 0 and 1000.'); write ('Press Enter and I will start to guess the number.'); readln; upp := 1000; low := 0; repeat ok := false; guess := ( (...
Give a code snippet in #Pascal Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The...
christopher/rosetta-code
http://rosettacode.org/wiki/N-smooth_numbers
N-smooth numbers
n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of two. 5-smooth   numbers are...
#D
D
import std.algorithm; import std.bigint; import std.exception; import std.range; import std.stdio;   BigInt[] primes; int[] smallPrimes;   bool isPrime(BigInt value) { if (value < 2) return false;   if (value % 2 == 0) return value == 2; if (value % 3 == 0) return value == 3;   if (value % 5 == 0) retur...
Give a code snippet in #D n-smooth   numbers are positive integers which have no prime factors > n. The   n   (when using it in the expression)   n-smooth   is always prime, there are   no   9-smooth numbers. 1   (unity)   is always included in n-smooth numbers. 2-smooth   numbers are non-negative powers of t...
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...
#Groovy
Groovy
class ShowAsciiTable { static void main(String[] args) { for (int i = 32; i <= 127; i++) { if (i == 32 || i == 127) { String s = i == 32 ? "Spc" : "Del" printf("%3d: %s ", i, s) } else { printf("%3d: %c ", i, i) } ...
Give a code snippet in #Groovy 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 ...
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...
#OxygenBasic
OxygenBasic
   % Title "Cuboid 2x3x4" '% Animated  % PlaceCentral uses ConsoleG   sub main ======== cls 0.0, 0.2, 0.7 shading scale 3 pushstate GoldMaterial.act static float ang=45 rotateX ang rotateY ang scale 2,3,4 go cube popstate end sub   EndScript  
Give a code snippet in #OxygenBasic 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 project...
christopher/rosetta-code
http://rosettacode.org/wiki/General_FizzBuzz
General FizzBuzz
Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along with the corresponding word to be ...
#Modula-2
Modula-2
MODULE GeneralFizzBuzz; FROM Conversions IMPORT StrToInt; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar;   TYPE Word = ARRAY[0..63] OF CHAR;   PROCEDURE WriteInt(i : INTEGER); VAR buf : Word; BEGIN FormatString("%i", buf, i); WriteString(buf); END WriteInt;  ...
Give a code snippet in #Modula-2 Task Write a generalized version of FizzBuzz that works for any list of factors, along with their words. This is basically a "fizzbuzz" implementation where the user supplies the parameters. The user will enter the max number, then they will enter the factors to be calculated along ...
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...
#Nim
Nim
import random, sequtils, strformat   type randProc = proc: range[0..1]   randomize()   proc randN(n: Positive): randProc = result = proc: range[0..1] = ord(rand(n) == 0)   proc unbiased(biased: randProc): range[0..1] = result = biased() var that = biased() while result == that: result = biased() that = ...
Give a code snippet in #Nim 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...
christopher/rosetta-code
http://rosettacode.org/wiki/15_puzzle_solver
15 puzzle solver
Your task is to write a program that finds a solution in the fewest moves possible single moves to a random Fifteen Puzzle Game. For this task you will be using the following puzzle: 15 14 1 6 9 11 4 12 0 10 7 3 13 8 5 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 The output must show the moves' dir...
#Forth
Forth
  #! /usr/bin/gforth   cell 8 <> [if] s" 64-bit system required" exception throw [then]   \ In the stack comments below, \ "h" stands for the hole position (0..15), \ "s" for a 64-bit integer representing a board state, \ "t" a tile value (0..15, 0 is the hole), \ "b" for a bit offset of a position within a state, \ "m...
Give a code snippet in #Forth Your task is to write a program that finds a solution in the fewest moves possible single moves to a random Fifteen Puzzle Game. For this task you will be using the following puzzle: 15 14 1 6 9 11 4 12 0 10 7 3 13 8 5 2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0 The ...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Continuous
Knapsack problem/Continuous
A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the item has a reduced price after...
#PicoLisp
PicoLisp
(scl 2)   (de *Items ("beef" 3.8 36.0) ("pork" 5.4 43.0) ("ham" 3.6 90.0) ("greaves" 2.4 45.0) ("flitch" 4.0 30.0) ("brawn" 2.5 56.0) ("welt" 3.7 67.0) ("salami" 3.0 95.0) ("sausage" 5.9 98.0) )   (let K (make (let Weight 0 (for I (by '((L) (*/ (caddr L) -1.0 (cadr L))) sort...
Give a code snippet in #PicoLisp A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   ...
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...
#Sidef
Sidef
var arr = [100, 1_000, 10_000, 20]; say Math.gcd(arr...);
Give a code snippet in #Sidef Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#Gambas
Gambas
Public Sub Main()   Print Multiply(56, 4.66)   End   Public Sub Multiply(f1 As Float, f2 As Float) As Float   Return f1 * f2   End
Give a code snippet in #Gambas A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#Commodore_BASIC
Commodore BASIC
1 rem 24 game 2 rem for rosetta code 10 rem use appropriate basic base address 11 bh=08:bl=01: rem $0801 commodore 64 12 rem bh=16:bl=01: rem $1001 commodore +4 13 rem bh=18:bl=01: rem $1201 commodore vic-20 (35k ram) 14 rem bh=04:bl=01: rem $0401 commodore pet 15 rem bh=28:bl=01: rem $1c01 commodore 128 (bank 0)   35 ...
Give a code snippet in #Commodore_BASIC The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of tho...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#Factor
Factor
append
Give a code snippet in #Factor Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Unbounded
Knapsack problem/Unbounded
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25   'weights' in total;   and tha...
#zkl
zkl
panacea:=T(3000, 0.3, 0.025); // (value,weight,volume) ichor  :=T(1800, 0.2, 0.015); gold  :=T(2500, 2.0, 0.002); sack  :=T( 0, 25.0, 0.250); const VAL=0, W=1, VOL=2;   maxes:=T(panacea,ichor,gold) .apply('wrap(t){ (sack[W]/t[W]).min(sack[VOL]/t[VOL]).toInt().walker() }); best:=Utils.Helpers.cprod3(maxes.xp...
Give a code snippet in #zkl A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Peripheral_drift_illusion
Peripheral drift illusion
Task Generate and display a Peripheral Drift Illusion The image appears to be moving even though it is perfectly static. Provide a link to show the output, either by running the code online or a screenshot uploaded to a suitable image host. References Codepen demo.
#Perl
Perl
use strict; use warnings;   my $svg = <<'EOD'; <svg xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="1200" height="825"> <rect width="100%" height="100%" fill="#d3d004" /> <defs> <g id="block"> <polygon po...
Give a code snippet in #Perl Task Generate and display a Peripheral Drift Illusion The image appears to be moving even though it is perfectly static. Provide a link to show the output, either by running the code online or a screenshot uploaded to a suitable image host. References Codepen demo.
christopher/rosetta-code
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#Run_BASIC
Run BASIC
dim plane(100,100) x = 50: y = 50: minY = 100   while (x>0) and (x<100) and (y>0) and (y<100) if plane(x,y) then nxt = nxt - 1 if nxt < 1 then nxt = 4 else nxt = nxt + 1 if nxt > 4 then nxt = 1 end if   x = x + (nxt = 2) - (nxt = 4) y = y + (nxt = 3) - (nxt = 1) plane(x,y) = (plane...
Give a code snippet in #Run_BASIC Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with...
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#PHP
PHP
$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd'); $unique_list = array_unique($list);
Give a code snippet in #PHP 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/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#MAXScript
MAXScript
dosCommand "pause"
Give a code snippet in #MAXScript Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The...
#PHP
PHP
<?php /** * @author Elad Yosifon * @desc HTML Table - normal style */ $cols = array('', 'X', 'Y', 'Z'); $rows = 3;   $html = '<html><body><table><colgroup>'; foreach($cols as $col) { $html .= '<col style="text-align: left;" />'; } unset($col); $html .= '</colgroup><thead><tr>';   foreach($cols as $col) { $html .= ...
Give a code snippet in #PHP Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with ...
christopher/rosetta-code
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#Go
Go
package main   import ( "fmt" "strconv" "strings" )   // types needed to implement general purpose sets are element and set   // element is an interface, allowing different kinds of elements to be // implemented and stored in sets. type elem interface { // an element must be distinguishable from other e...
Give a code snippet in #Go A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a ...
christopher/rosetta-code