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/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 ...
#Quackery
Quackery
' [ 2 3 5 ] smoothwith [ size 1000000 = ] dup 20 split drop echo cr dup 1690 peek echo cr -1 peek echo  
Give a code snippet in #Quackery 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 n...
christopher/rosetta-code
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a 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. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#J
J
  query=:3 :'0&#^:(y < #)''Here am I'''  
Give a code snippet in #J This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size...
christopher/rosetta-code
http://rosettacode.org/wiki/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#Arturo
Arturo
pi: 4*atan 1.0   radians: pi/4 degrees: 45.0   print "sine" print [sin radians, sin degrees*pi/180]   print "cosine" print [cos radians, cos degrees*pi/180]   print "tangent" print [tan radians, tan degrees*pi/180]   print "arcsine" print [asin sin radians, (asin sin radians)*180/pi]   print "arccosine" print [acos cos...
Give a code snippet in #Arturo Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that eval...
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
#CLU
CLU
% Wilson primality test wilson = proc (n: int) returns (bool) if n<2 then return (false) end fac_mod: int := 1 for i: int in int$from_to(2, n-1) do fac_mod := fac_mod * i // n end return (fac_mod + 1 = n) end wilson   % Print primes up to 100 using Wilson's theorem start_up = proc () ...
Give a code snippet in #CLU 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. Wi...
christopher/rosetta-code
http://rosettacode.org/wiki/Eertree
Eertree
An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for the string "eertree", then outp...
#zkl
zkl
class Node{ fcn init(length){ var edges=Dictionary(), # edges (or forward links). (char:Node) link=Void, # suffix link (backward links) sz =length; # node length. } } class Eertree{ fcn init(string=Void){ var nodes=List(), # two initial root nodes rto=Node(-1), # odd length r...
Give a code snippet in #zkl An eertree is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. The data structure has commonalities to both tries and suffix trees.   See links below. Task Construct an eertree for th...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Java
Java
public static String repeat(String str, int times) { StringBuilder sb = new StringBuilder(str.length() * times); for (int i = 0; i < times; i++) sb.append(str); return sb.toString(); }   public static void main(String[] args) { System.out.println(repeat("ha", 5)); }
Give a code snippet in #Java Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) =...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#APL
APL
  {⍕0~¨⍨(-⌽A)⌽↑,/0,¨⍉A∘.!A←0,⍳⍵}  
Give a code snippet in #APL Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#Nim
Nim
from math import sqrt   iterator primesUpto(limit: int): int = let sqrtLimit = int(sqrt(float64(limit))) var composites = newSeq[bool](limit + 1) for n in 2 .. sqrtLimit: # cull to square root of limit if not composites[n]: # if prime -> cull its composites for c in countup(n * n, limit, n): # start at ...
Give a code snippet in #Nim This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   alg...
christopher/rosetta-code
http://rosettacode.org/wiki/Kaprekar_numbers
Kaprekar numbers
A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ...
#Scala
Scala
object Kaprekar extends App {   def isKaprekar(n: Int, base: Int = 10):Option[Triple[String,String,String]] = { val check: Long => Option[Triple[String,String,String]] = n => { val split: Pair[String, Int] => Pair[String, String] = p => (p._1.slice(0,p._2),p._1.slice(p._2,p._1.size).padTo[Char,String](1,'0'...
Give a code snippet in #Scala A positive integer is a Kaprekar number if: It is   1     (unity) The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as...
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
#D
D
import std.stdio, std.math;   enum width = 1000, height = 1000; // Image dimension. enum length = 400; // Trunk size. enum scale = 6.0 / 10; // Branch scale relative to trunk.   void tree(in double x, in double y, in double length, in double angle) { if (length < 1) return; imm...
Give a code snippet in #D 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/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Nim
Nim
import strutils   # Repeat a char. echo repeat('a', 5) # -> "aaaaa".   # Repeat a string. echo repeat("ha", 5) # -> "hahahahaha".
Give a code snippet in #Nim Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) =>...
christopher/rosetta-code
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bit...
#Icon_and_Unicon
Icon and Unicon
procedure main(a) s := !a | "1223334444" write(H(s)) end   procedure H(s) P := table(0.0) every P[!s] +:= 1.0/*s every (h := 0.0) -:= P[c := key(P)] * log(P[c],2) return h end
Give a code snippet in #Icon_and_Unicon Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for...
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 ...
#PL.2FM
PL/M
100H: /* TEST FOR PRIMALITY BY TRIAL DIVISION */   DECLARE FALSE LITERALLY '0', TRUE LITERALLY '0FFH'; /* CP/M BDOS SYSTEM CALL */ BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END; PR$CHAR: PROCEDURE( C );...
Give a code snippet in #PL.2FM 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/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#Wren
Wren
import "/big" for BigInt import "/fmt" for Fmt   var vals = [1 << 31, 1234567, 333333, 987653, 2 * 3 * 5 * 7 * 11 * 13 * 17] for (val in vals) { Fmt.print("$10d -> $n", val, BigInt.primeFactors(val)) }
Give a code snippet in #Wren The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the p...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#Processing
Processing
void setup() { int deficient = 0, perfect = 0, abundant = 0; for (int i = 1; i <= 20000; i++) { int sum_divisors = propDivSum(i); if (sum_divisors < i) { deficient++; } else if (sum_divisors == i) { perfect++; } else { abundant++; } } println("Deficient numbers less than 20...
Give a code snippet in #Processing These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as defi...
christopher/rosetta-code
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#Octave
Octave
function r = horner(a, x) r = 0.0; for i = length(a):-1:1 r = r*x + a(i); endfor endfunction   horner([-19, 7, -4, 6], 3)
Give a code snippet in #Octave A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {...
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#Raku
Raku
my ($x,$y) = 1280, 720;   my @colors = map -> $r, $g, $b { Buf.new: |(($r, $g, $b) xx $x div 8) }, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 0, 255, 0, 255, 255, 255, 255, 0, 255, 255, 255;   my $img = open "colorbars.ppm", :w orelse die "Can't create colorba...
Give a code snippet in #Raku Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
christopher/rosetta-code
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#Bracmat
Bracmat
{ Calculate day of week in proleptic Gregorian calendar. Sunday == 0. } ( wday = year month day adjustment mm yy .  !arg:(?year,?month,?day) & div$(14+-1*!month,12):?adjustment & !month+12*!adjustment+-2:?mm & !year+-1*!adjustment:?yy & mod $ (  !day ...
Give a code snippet in #Bracmat A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years betwee...
christopher/rosetta-code
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string....
#m4
m4
divert(-1)   # Get a random number from 0 to one less than $1. # (Note that this is not a very good RNG. Also it writes a file.) # # Usage: randnum(N) (Produces a random integer in 0..N-1) # define(`randnum', `syscmd(`echo $RANDOM > __random_number__')eval(include(__random_number__) % ( $1 ))')   # The *target* spe...
Give a code snippet in #m4 Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its ar...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#Simula
Simula
BEGIN INTEGER U; U := ININT; BEGIN   TEXT PROCEDURE GENERATE(N); INTEGER N; BEGIN INTEGER R; TEXT T; T :- NOTEXT; WHILE N > 0 DO BEGIN R := RANDINT(1,2,U); T :- T & (IF R = 1 THEN "[" ELSE "]"); N...
Give a code snippet in #Simula Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-...
christopher/rosetta-code
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced...
#Clojure
Clojure
(defn truncate [file size] (with-open [chan (.getChannel (java.io.FileOutputStream. file true))] (.truncate chan size)))   (truncate "truncate_test.txt" 2)
Give a code snippet in #Clojure Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creat...
christopher/rosetta-code
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octa...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
EmitSound@Sound[SoundNote /@ {0, 2, 4, 5, 7, 9, 11, 12}]
Give a code snippet in #Mathematica.2FWolfram_Language Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#JavaScript
JavaScript
function binary_search_recursive(a, value, lo, hi) { if (hi < lo) { return null; }   var mid = Math.floor((lo + hi) / 2);   if (a[mid] > value) { return binary_search_recursive(a, value, lo, mid - 1); } if (a[mid] < value) { return binary_search_recursive(a, value, mid + 1, hi); } return mid; }
Give a code snippet in #JavaScript A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a sec...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. 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 information theory and computer science, the Levenshtein ...
#JavaScript
JavaScript
function levenshtein(a, b) { var t = [], u, i, j, m = a.length, n = b.length; if (!m) { return n; } if (!n) { return m; } for (j = 0; j <= n; j++) { t[j] = j; } for (i = 1; i <= m; i++) { for (u = [i], j = 1; j <= n; j++) { u[j] = a[i - 1] === b[j - 1] ? t[j - 1] : Math.min(t[j - 1], t[j], u[j - 1])...
Give a code snippet in #JavaScript This page uses content from Wikipedia. The original article was at Levenshtein distance. 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 information theory an...
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#PARI.2FGP
PARI/GP
chivec(residues, moduli)={ my(m=Mod(0,1)); for(i=1,#residues, m=chinese(Mod(residues[i],moduli[i]),m) ); lift(m) }; chivec([2,3,2], [3,5,7])
Give a code snippet in #PARI.2FGP Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\disp...
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...
#PureBasic
PureBasic
DataSection ;the list of words that will be added to the list words: Data.s "One", "Two", "Three", "Four", "Five", "Six", "EndOfData" EndDataSection     Procedure displayList(List x.s(), title$) ;display all elements from list of strings Print(title$) ForEach x() Print(x() + " ") Next PrintN("") E...
Give a code snippet in #PureBasic 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#Scala
Scala
/** This class implicitly includes a constructor which accepts an Int and * creates "val variable1: Int" with that value. */ class MyClass(val myMethod: Int) { // Acts like a getter, getter automatically generated. var variable2 = "asdf" // Another instance variable; a public var this time def this() = this(0) /...
Give a code snippet in #Scala In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the cla...
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#DM
DM
if (condition) // Do thing, DM uses indentation for control flow.   if (condition) // Do thing   else if (condition) // Do thing   else // Do thing  
Give a code snippet in #DM Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common con...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#Pascal
Pascal
Program CatalanNumbers(output);   function catalanNumber1(n: integer): double; begin if n = 0 then catalanNumber1 := 1.0 else catalanNumber1 := double(4 * n - 2) / double(n + 1) * catalanNumber1(n-1); end;   var number: integer;   begin writeln('Catalan Numbers'); writeln('Recursion with ...
Give a code snippet in #Pascal Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n ! ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#Fermat
Fermat
n:=1024; while n>2/3 do !!n;n:=n/2; od;
Give a code snippet in #Fermat Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downwa...
christopher/rosetta-code
http://rosettacode.org/wiki/Handle_a_signal
Handle a signal
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created so that the program behaves in a well-defi...
#Perl
Perl
  my $start = time; # seconds since epohc my $arlm=5; # every 5 seconds show how we're doing my $i;   $SIG{QUIT} = sub {print " Ran for ", time - $start, " seconds.\n"; die; }; $SIG{INT} = sub {print " Running for ", time - $start, " seconds.\n"; }; $SIG{ALRM} = sub {print " After $arlm seconds i= $i. Execu...
Give a code snippet in #Perl Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created so that the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X
Isqrt (integer square root) of X
Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your computer programming language,   assume...
#Go
Go
package main   import ( "fmt" "log" "math/big" )   var zero = big.NewInt(0) var one = big.NewInt(1)   func isqrt(x *big.Int) *big.Int { if x.Cmp(zero) < 0 { log.Fatal("Argument cannot be negative.") } q := big.NewInt(1) for q.Cmp(x) <= 0 { q.Lsh(q, 2) } z := new(big.I...
Give a code snippet in #Go Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your computer pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Pseudo-random_numbers/Middle-square_method
Pseudo-random numbers/Middle-square method
Middle-square_method Generator The Method To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number i...
#Haskell
Haskell
findPseudoRandom :: Int -> Int findPseudoRandom seed = let square = seed * seed squarestr = show square enlarged = replicate ( 12 - length squarestr ) '0' ++ squarestr in read $ take 6 $ drop 3 enlarged   solution :: [Int] solution = tail $ take 6 $ iterate findPseudoRandom 675248
Give a code snippet in #Haskell Middle-square_method Generator The Method To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the ...
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...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "getf.s7i";   const proc: main is func local var string: fileContent is ""; begin fileContent := getf("text.txt"); end func;
Give a code snippet in #Seed7 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 incre...
christopher/rosetta-code
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of...
#EchoLisp
EchoLisp
  (require 'hash) (require' amb)   ;; ;; Solver ;;   (define (dwelling-puzzle context names floors H) ;; each amb calls gives a floor to a name (for ((name names)) (hash-set H name (amb context floors))) ;; They live on different floors. (amb-require (distinct? (amb-choices context))) (constraints floors ...
Give a code snippet in #EchoLisp Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text ar...
christopher/rosetta-code
http://rosettacode.org/wiki/Mind_boggling_card_trick
Mind boggling card trick
Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the trick in a way that mimics th...
#J
J
  NB. A failed assertion looks like this assert 0 |assertion failure: assert | assert 0  
Give a code snippet in #J Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the tr...
christopher/rosetta-code
http://rosettacode.org/wiki/Play_recorded_sounds
Play recorded sounds
Load at least two prerecorded sounds, and demonstrate as many of these features as you can: playing them individually and simultaneously stopping before the end of the sound looping (preferably glitch-free) setting the volume of each sound stereo or 3D positional mixing performing other actions when marked times...
#PicoLisp
PicoLisp
(call 'sox "-m" "-v" "0.75" "a.wav" "-v" "0.25" "b.wav" "-d" "trim" 4 6 "repeat" 5 )
Give a code snippet in #PicoLisp Load at least two prerecorded sounds, and demonstrate as many of these features as you can: playing them individually and simultaneously stopping before the end of the sound looping (preferably glitch-free) setting the volume of each sound stereo or 3D positional mixing performi...
christopher/rosetta-code
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#Yabasic
Yabasic
// Rosetta Code problem: https://www.rosettacode.org/wiki/Menu // by Jjuanhdez, 06/2022   dim choose$(5) restore menudata for a = 0 to 5 : read choose$(a) : next a   print menu$(choose$()) end   sub menu$(m$()) clear screen repeat print color("green","black") at(0,0) "Menu selection" vc = 0 ...
Give a code snippet in #Yabasic Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the st...
christopher/rosetta-code
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#Haskell
Haskell
ack :: Int -> Int -> Int ack 0 n = succ n ack m 0 = ack (pred m) 1 ack m n = ack (pred m) (ack m (pred n))   main :: IO () main = mapM_ print $ uncurry ack <$> [(0, 0), (3, 4)]
Give a code snippet in #Haskell The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { ...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#Ursala
Ursala
#import nat   roman =   -+ 'IIII'%='IV'+ 'VIIII'%='IX'+ 'XXXX'%='XL'+ 'LXXXX'%='XC'+ 'CCCC'%='CD'+ 'DCCCC'%='CM', ~&plrDlSPSL/'MDCLXVI'+ iota*+ +^|(^|C/~&,\/division)@rlX=>~&iNC <1000,500,100,50,10,5>+-
Give a code snippet in #Ursala Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a va...
christopher/rosetta-code
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the defin...
#FreeBASIC
FreeBASIC
  #include "isprime.bas"   function nextprime( n as uinteger ) as uinteger 'finds the next prime after n, excluding n if it happens to be prime itself if n = 0 then return 2 if n < 3 then return n + 1 dim as integer q = n + 2 while not isprime(q) q+=2 wend return q end function   fun...
Give a code snippet in #FreeBASIC Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + pr...
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...
#Jsish
Jsish
#!/usr/bin/env jsish   /* Show ASCII table, -showAll true to include control codes */ function showASCIITable(args:array|string=void, conf:object=void) { var options = { // Rosetta Code, Show ASCII table rootdir :'', // Root directory. showAll : false // include control cod...
Give a code snippet in #Jsish Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack....
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with GNAT.Traceback; with GNAT.Traceback.Symbolic;   procedure Test_Stack_Trace is procedure Call_Stack is Trace  : GNAT.Traceback.Tracebacks_Array (1..1_000); Length : Natural; begin GNAT.Traceback.Call_Chain (Trace, Length); Put_Line (GNAT.Traceback.Sy...
Give a code snippet in #Ada Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the plat...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Def...
#Nim
Nim
type List[T] = object head, tail: Node[T]   Node[T] = ref TNode[T]   TNode[T] = object next, prev: Node[T] data: T   proc initList[T](): List[T] = discard   proc newNode[T](data: T): Node[T] = new(result) result.data = data   proc prepend[T](l: var List[T], n: Node[T]) = n.next = l.head if l.h...
Give a code snippet in #Nim Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Rem...
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#Quackery
Quackery
(cond ([(< 4 3) 'apple] ['bloggle 'pear] [else 'nectarine])
Give a code snippet in #Quackery Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable...
#360_Assembly
360 Assembly
* Loops/Increment loop index within loop body - 16/07/2018 LOOPILWB PROLOG SR R6,R6 i=0 ZAP N,=P'42' n=42 DO WHILE=(C,R6,LT,IMAX) do while(i<imax) BAL R14,ISPRIME call isprime(n) IF C,R0,EQ,=F'1' THEN if n is prime the...
Give a code snippet in #360_Assembly Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop...
christopher/rosetta-code
http://rosettacode.org/wiki/Elliptic_curve_arithmetic
Elliptic curve arithmetic
Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a nutshell, an elliptic curve is a...
#Tcl
Tcl
set C 7 set zero {x inf y inf} proc tcl::mathfunc::cuberoot n { # General power operator doesn't like negative, but its defined for root3 expr {$n>=0 ? $n**(1./3) : -((-$n)**(1./3))} } proc iszero p { dict with p {} return [expr {$x > 1e20 || $x<-1e20}] } proc negate p { dict set p y [expr {-[dict g...
Give a code snippet in #Tcl Elliptic curves   are sometimes used in   cryptography   as a way to perform   digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol. In a nut...
christopher/rosetta-code
http://rosettacode.org/wiki/Variable_declaration_reset
Variable declaration reset
A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may ...
#Perl
Perl
@s = <1 2 2 3 4 4 5>; for ($i = 0; $i < 7; $i++) { $curr = $s[$i]; if ($i > 1 and $curr == $prev) { print "$i\n" } $prev = $curr; }
Give a code snippet in #Perl A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_simple
Abbreviations, simple
The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. For this task, the following   command table   will be used: add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 ...
#Haskell
Haskell
import Data.List (find, isPrefixOf) import Data.Char (isDigit, toUpper) import Data.Maybe (maybe)   withExpansions :: [(String, Int)] -> String -> String withExpansions tbl s = unwords $ expanded tbl <$> words s   expanded :: [(String, Int)] -> String -> String expanded tbl k = maybe "*error" fst (expand k) where ...
Give a code snippet in #Haskell The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. For this task, the following   command table   will be used: add 1 alter 3 backup 2...
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...
#Logtalk
Logtalk
:- object(list).   :- public(permutation/2).   permutation(List, Permutation) :- same_length(List, Permutation), permutation2(List, Permutation).   permutation2([], []). permutation2(List, [Head| Tail]) :- select(Head, List, Remaining), permutation2(Remaining, Tail).   ...
Give a code snippet in #Logtalk 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   ge...
christopher/rosetta-code
http://rosettacode.org/wiki/String_comparison
String comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Rust
Rust
use std::ascii::AsciiExt; // for case insensitives only   fn main() { // only same types can be compared // String and String or &str and &str // exception: strict equality and inequality also work on &str and String let a: &str = "abc"; let b: String = "Bac".to_owned();   // Strings are coerced...
Give a code snippet in #Rust Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations C...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#ActionScript
ActionScript
function multiply(a:Number, b:Number):Number { return a * b; }
Give a code snippet in #ActionScript 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 di...
christopher/rosetta-code
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 ...
#Lua
Lua
function map(f, ...) local t = {} for k, v in ipairs(...) do t[#t+1] = f(v) end return t end   function timestwo(n) return n * 2 end   function squared(n) return n ^ 2 end   function partial(f, arg) return function(...) return f(arg, ...) end end   timestwo_s = partial(ma...
Give a code snippet in #Lua Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function....
christopher/rosetta-code
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously
Loop over multiple arrays simultaneously
Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example, loop over the arrays: ...
#FunL
FunL
import lists.zip3   for x <- zip3( ['a', 'b', 'c'], ['A', 'B', 'C'], [1, 2, 3] ) println( x.mkString() )
Give a code snippet in #FunL Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this examp...
christopher/rosetta-code
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers....
#Pascal
Pascal
program SmithNum; {$IFDEF FPC} {$MODE objFPC} //result and useful for x64 {$CODEALIGN PROC=64} {$ENDIF} uses sysutils; type tdigit = byte; tSum = LongInt; const base = 10; //maxDigitCnt *(base-1) <= High(tSum) //maxDigitCnt <= High(tSum) DIV (base-1); maxDigitCnt = 16;   StartPrimNo = 6; cseg...
Give a code snippet in #Pascal Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are...
christopher/rosetta-code
http://rosettacode.org/wiki/Synchronous_concurrency
Synchronous concurrency
The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th...
#Racket
Racket
  (define (reader) (for ([line (in-lines (open-input-file "input.txt"))]) (thread-send printer-thread line)) (thread-send printer-thread eof) (printf "Number of lines: ~a\n" (thread-receive)))   (define (printer) (thread-send reader-thread (for/sum ([line (in-producer thread-receive eof)]) ...
Give a code snippet in #Racket The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with differ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Forth
Forth
defer bubble-test ' > is bubble-test   : bubble { addr cnt -- } cnt 1 do addr cnt i - cells bounds do i 2@ bubble-test if i 2@ swap i 2! then cell +loop loop ;
Give a code snippet in #Forth Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick so...
christopher/rosetta-code
http://rosettacode.org/wiki/Color_of_a_screen_pixel
Color of a screen pixel
Task Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
#Go
Go
package main   import ( "fmt" "github.com/go-vgo/robotgo" )   func main() { // get position of mouse cursor x, y := robotgo.GetMousePos()   // get color of pixel at that position color := robotgo.GetPixelColor(x, y) fmt.Printf("Color of pixel at (%d, %d) is 0x%s\n", x, y, color) }
Give a code snippet in #Go Task Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
christopher/rosetta-code
http://rosettacode.org/wiki/Dutch_national_flag_problem
Dutch national flag problem
The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national fla...
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   // constants define order of colors in Dutch national flag const ( red = iota white blue nColors )   // zero object of type is valid red ball. type ball struct { color int }   // order of balls based on DNF func (b1 ball) lt(b2 ball) b...
Give a code snippet in #Go The Dutch national flag is composed of three coloured bands in the order:   red     (top)   then white,   and   lastly blue   (at the bottom). The problem posed by Edsger Dijkstra is: Given a number of red, blue and white balls in random order, arrange them in the order of the colou...
christopher/rosetta-code
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle
4-rings or 4-squares puzzle
4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the four large squares add up to t...
#C.2B.2B
C++
  //C++14/17 #include <algorithm>//std::for_each #include <iostream> //std::cout #include <numeric> //std::iota #include <vector> //std::vector, save solutions #include <list> //std::list, for fast erase   using std::begin, std::end, std::for_each;   //Generates all the valid solutions for the problem in the spe...
Give a code snippet in #C.2B.2B 4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of t...
christopher/rosetta-code
http://rosettacode.org/wiki/List_comprehensions
List comprehensions
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the use of map and filter functio...
#Python
Python
[(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
Give a code snippet in #Python A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and t...
christopher/rosetta-code
http://rosettacode.org/wiki/Summarize_and_say_sequence
Summarize and say sequence
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ... The terms generat...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   typedef struct rec_t rec_t; struct rec_t { int depth; rec_t * p[10]; };   rec_t root = {0, {0}};   #define USE_POOL_ALLOC #ifdef USE_POOL_ALLOC /* not all that big a deal */ rec_t *tail = 0, *head = 0; #define POOL_SIZE (1 << 20) inline rec_t *new_rec() { ...
Give a code snippet in #C There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 31131122...
christopher/rosetta-code
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (209...
#Tcl
Tcl
package require Tcl 8.5   proc vlqEncode number { if {$number < 0} {error "negative not supported"} while 1 { lappend digits [expr {$number & 0x7f}] if {[set number [expr {$number >> 7}]] == 0} break } set out [format %c [lindex $digits 0]] foreach digit [lrange $digits 1 end] { set out [format %...
Give a code snippet in #Tcl Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert th...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newbie
Hello world/Newbie
Task Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the Hello world/Text task. Assume the language-newbie is a programmer in another language. Assume the language-newbie is competent in install...
#Corescript
Corescript
import std.stdio;   void main() { writeln("Hello world!"); }
Give a code snippet in #Corescript Task Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the Hello world/Text task. Assume the language-newbie is a programmer in another language. Assume the lan...
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...
#Oforth
Oforth
12 isEven 12 isOdd
Give a code snippet in #Oforth 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. Div...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_nth_number_with_exactly_n_divisors
Sequence: nth number with exactly n divisors
Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number with exactly n divisors
#Julia
Julia
using Primes   function countdivisors(n) f = [one(n)] for (p, e) in factor(n) f = reduce(vcat, [f * p ^ j for j in 1:e], init = f) end length(f) end   function nthwithndivisors(N) parray = findall(primesmask(100 * N)) for i = 1:N if isprime(i) println("$i : ", BigInt(...
Give a code snippet in #Julia Calculate the sequence where each term an is the nth that has n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A073916 Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: smallest number...
christopher/rosetta-code
http://rosettacode.org/wiki/Optional_parameters
Optional parameters
Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicographic by default. column ...
#Ruby
Ruby
def table_sort(table, ordering=:<=>, column=0, reverse=false) # ...
Give a code snippet in #Ruby Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexi...
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#BBC_BASIC
BBC BASIC
REM Single-line IF ... THEN ... ELSE (ELSE clause is optional): IF condition% THEN statements ELSE statements   REM Multi-line IF ... ENDIF (ELSE clause is optional): IF condition% THEN statements ELSE statements ENDIF   REM CASE ... ENDCASE (OTHERWISE clause is...
Give a code snippet in #BBC_BASIC Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Com...
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 ...
#Arturo
Arturo
arr: [1 2 3 2 1 2 3 4 5 3 2 1]   print unique arr
Give a code snippet in #Arturo Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   ...
#C.23
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq;   namespace RosettaRecursiveDirectory { class Program { static IEnumerable<FileInfo> TraverseDirectory(string rootPath, Func<FileInfo, bool> Pattern) { var directoryStack = new Stack<DirectoryInfo>();...
Give a code snippet in #C.23 Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk ...
christopher/rosetta-code
http://rosettacode.org/wiki/Flipping_bits_game
Flipping bits game
The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move). In an inversion.   any  1 ...
#Ruby
Ruby
class FlipBoard def initialize(size) raise ArgumentError.new("Invalid board size: #{size}") if size < 2   @size = size @board = Array.new(size**2, 0)   randomize_board loop do @target = generate_target break unless solved? end   # these are used for validating user input @...
Give a code snippet in #Ruby The game Given an   N×N   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once   (as one move...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#Lambdatalk
Lambdatalk
  1) defining the function: {def func {lambda {:x} {+ {* 1 :x :x :x} {* -3 :x :x} {* 2 :x}}}} -> func   2) printing roots: {S.map {lambda {:x} {if {< {abs {func :x}} 0.0001} then {br}- a root found at :x else}} {S.serie -1 3 0.01}} -> - a root found at 7.528699885739343e-16 ...
Give a code snippet in #Lambdatalk Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
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
#Astro
Astro
print "Hello world!"
Give a code snippet in #Astro 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/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#GW-BASIC
GW-BASIC
10 LET a=1 20 IF a=2 THEN PRINT "This is a conditional statement" 30 IF a=1 THEN GOTO 50: REM a conditional jump 40 PRINT "This statement will be skipped" 50 PRINT ("Hello" AND (1=2)): REM This does NOT PRINT 100 PRINT "Endless loop" 110 GOTO 100:REM an unconditional jump
Give a code snippet in #GW-BASIC Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   constru...
christopher/rosetta-code
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#OCaml
OCaml
# let nums = [1;2;3;4;5;6;7;8;9;10];; val nums : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] # let sum = List.fold_left (+) 0 nums;; val sum : int = 55 # let product = List.fold_left ( * ) 1 nums;; val product : int = 3628800
Give a code snippet in #OCaml Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. ...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Ursala
Ursala
multiply = math..mul
Give a code snippet in #Ursala 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/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#11l
11l
F fib_iter(n) I n < 2 R n V fib_prev = 1 V fib = 1 L 2 .< n (fib_prev, fib) = (fib, fib + fib_prev) R fib   L(i) 1..20 print(fib_iter(i), end' ‘ ’) print()
Give a code snippet in #11l The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are g...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Brlcad
Brlcad
  # Comments in mget scripts are prefixed with a hash symbol ls # comments may appear at the end of a line  
Give a code snippet in #Brlcad Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Scheme
Scheme
(define (matrix-multiply matrix1 matrix2) (map (lambda (row) (apply map (lambda column (apply + (map * row column))) matrix2)) matrix1))
Give a code snippet in #Scheme Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#APL
APL
x y z←{⍵[⍋⍵]}x y z
Give a code snippet in #APL 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/Minesweeper_game
Minesweeper game
There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid...
#Wren
Wren
import "/dynamic" for Struct import "/fmt" for Fmt import "random" for Random import "/ioutil" for Input import "/str" for Str   var Cell = Struct.create("Cell", ["isMine", "display"])   var lMargin = 4 var grid = [] var mineCount = 0 var minesMarked = 0 var isGameOver = false var rand = Random.new()   var makeGrid = ...
Give a code snippet in #Wren There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordi...
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 ...
#PowerShell
PowerShell
function shuffle ($a) { $c = $a.Clone() # make copy to avoid clobbering $a 1..($c.Length - 1) | ForEach-Object { $i = Get-Random -Minimum $_ -Maximum $c.Length $c[$_-1],$c[$i] = $c[$i],$c[$_-1] $c[$_-1] # return newly-shuffled value } $c[-1] # last value }   function isSorted...
Give a code snippet in #PowerShell Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Qui...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#ARM_Assembly
ARM Assembly
.text .global _start _start: ldr r0, =example_numbers bl test_number   add r1, r0, #1 bl length add r0, r1, r0 bl test_number   add r1, r0, #1 bl length add r0, r1, r0 bl test_number   add r1, r0, #1 bl length add r0, r1, r0 bl test_number   mov r0, #0 mov...
Give a code snippet in #ARM_Assembly 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 o...
christopher/rosetta-code
http://rosettacode.org/wiki/Pancake_numbers
Pancake numbers
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size...
#Python
Python
"""Pancake numbers. Requires Python>=3.7.""" import time   from collections import deque from operator import itemgetter from typing import Tuple   Pancakes = Tuple[int, ...]     def flip(pancakes: Pancakes, position: int) -> Pancakes: """Flip the stack of pancakes at the given position.""" return tuple([*rever...
Give a code snippet in #Python Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are st...
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Liberty_BASIC
Liberty BASIC
nomainwin button #demo.btn, "Click Me", [btnClick], UL, 20, 50 statictext #demo.num, "There have been no clicks yet.", 20, 100, 240, 30 open "Rosetta Task: Simple windowed application" for window as #demo #demo "trapclose [quit]" nClicks = 0 wait   [quit] close #demo end   [btnClick] nClicks...
Give a code snippet in #Liberty_BASIC Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
christopher/rosetta-code
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#REXX
REXX
/*REXX program creates and displays any sized identity matrix (centered, with title).*/ do k=3 to 6 /* [↓] build and display a sq. matrix.*/ call ident_mat k /*build & display a KxK square matrix. */ end /*k*/ ...
Give a code snippet in #REXX Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Long_multiplication
Long multiplication
Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264   is: 18,446,744,073,709,551,61...
#Arturo
Arturo
print 2^64 * 2
Give a code snippet in #Arturo Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly...
#ALGOL_68
ALGOL 68
BEGIN   PROC count divisors = ( INT n )INT: BEGIN INT count := 0; FOR i WHILE i*i <= n DO IF n MOD i = 0 THEN count +:= IF i = n OVER i THEN 1 ELSE 2 FI FI OD; count END # count divisors # ;   I...
Give a code snippet in #ALGOL_68 Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors ...
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...
#Ring
Ring
  # Project : Show Ascii table   load "guilib.ring" load "stdlib.ring"   decarr = newlist(16,6) ascarr = newlist(16,6)   new qapp { win1 = new qwidget() { setwindowtitle("Show Ascii table") setgeometry(100,100,800,600) for n = 1 to 16 ...
Give a code snippet in #Ring Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I ...
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. ...
#Frink
Frink
for f = select[files["."], {|f1| f1.getName[] =~ %r/\.frink$/}] println[f.getName[]]
Give a code snippet in #Frink Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#BBC_BASIC
BBC BASIC
size% = 256   VDU 23,22,size%;size%;8,8,16,0 OFF   DIM coltab%(size%-1) FOR I% = 0 TO size%-1 coltab%(I%) = ((I% AND &FF) * &010101) EOR &FF0000 NEXT   GCOL 1 FOR I% = 0 TO size%-1 FOR J% = 0 TO size%-1 C% = coltab%(I% EOR J%) COLOUR 1,...
Give a code snippet in #BBC_BASIC Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
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...
#Quackery
Quackery
[ over take over take 2swap dip put put ] is exchange ( s s --> )
Give a code snippet in #Quackery 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 generi...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_manipulation
Date manipulation
Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
#jq
jq
"March 7 2009 7:30pm EST" | strptime("%B %d %Y %I:%M%p %Z") | .[3] += 12 | mktime | strftime("%B %d %Y %I:%M%p %Z")
Give a code snippet in #jq Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Ursa
Ursa
decl int n set n (int args<1>)   decl int i for (set i 1) (< i (+ (/ n 2) 1)) (inc i) if (= (mod n i) 0) out i " " console end if end for out n endl console
Give a code snippet in #Ursa Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations C...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_primorial_primes
Sequence of primorial primes
The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being a prime number itself. T...
#C
C
  #include <gmp.h>   int main(void) { mpz_t p, s; mpz_init_set_ui(p, 1); mpz_init_set_ui(s, 1);   for (int n = 1, i = 0; i < 20; n++) { mpz_nextprime(s, s); mpz_mul(p, p, s);   mpz_add_ui(p, p, 1); if (mpz_probab_prime_p(p, 25)) { mpz_sub_ui(p, p, 1); ...
Give a code snippet in #C The sequence of primorial primes is given as the increasing values of n where primorial(n) ± 1 is prime. Noting that the n'th primorial is defined as the multiplication of the smallest n primes, the sequence is of the number of primes, in order that when multiplied together is one-off being ...
christopher/rosetta-code
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this...
#PL.2FI
PL/I
(size, fofl): Convert_Decimal_To_Rational: procedure options (main); /* 14 January 2014, from Ada */   Real_To_Rational: procedure (R, Bound, Numerator, Denominator) recursive options (reorder); declare R float (18), Bound float, (Numerator, Denominator) fixed binary (31); declare Error float; ...
Give a code snippet in #PL.2FI This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It i...
christopher/rosetta-code
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Icon_and_Unicon
Icon and Unicon
procedure main(arglist)   if *envars = 0 then envars := ["HOME", "TRACE", "BLKSIZE","STRSIZE","COEXPSIZE","MSTKSIZE", "IPATH","LPATH","NOERRBUF"]   every v := !sort(envars) do write(v," = ",image(getenv(v))|"* not set *") end
Give a code snippet in #Icon_and_Unicon Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#OCaml
OCaml
let my_max = function [] -> invalid_arg "empty list" | x::xs -> List.fold_left max x xs
Give a code snippet in #OCaml Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f...
#Common_Lisp
Common Lisp
;; 't' usually means "true" in CL, but we need 't' here for time/temperature. (defconstant true 'cl:t) (shadow 't)     ;; Approximates y(t) in y'(t)=f(t,y) with y(a)=y0 and t=a..b and the step size h. (defun euler (f y0 a b h)   ;; Set the initial values and increments of the iteration variables. (do ((t a (+ t h)...
Give a code snippet in #Common_Lisp Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following ...
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
#MUMPS
MUMPS
Set X=$ZF(-1,"DIR")
Give a code snippet in #MUMPS Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code