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/Old_lady_swallowed_a_fly
Old lady swallowed a fly
Task Present a program which emits the lyrics to the song   I Knew an Old Lady Who Swallowed a Fly,   taking advantage of the repetitive structure of the song's lyrics. This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output. Other tasks related to st...
#Scratch
Scratch
$ include "seed7_05.s7i";   const array array string: verses is [] ( [] ("fly", "I don't know why she swallowed the fly."), [] ("spider", "That wriggled and jiggled and tickled inside her."), [] ("bird", "Quite absurd. To swallow a bird."), [] ("cat", "Fancy that. To swallow a cat."), [] ("dog", "Wh...
Give a code snippet in #Scratch Task Present a program which emits the lyrics to the song   I Knew an Old Lady Who Swallowed a Fly,   taking advantage of the repetitive structure of the song's lyrics. This song has multiple versions with slightly different lyrics, so all these programs might not emit identical outp...
christopher/rosetta-code
http://rosettacode.org/wiki/Naming_conventions
Naming conventions
Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes, suffixes, and the use of upper...
#Python
Python
#lang racket render-game-state send-message-to-client traverse-forest
Give a code snippet in #Python Many languages have naming conventions regarding the identifiers used in the language, its libraries, and programs written in the language. Such conventions, which may be classified as de facto or de jure depending on how they are enforced, often take the form of rules regarding prefixes...
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...
#Haskell
Haskell
import Data.Set (Set, member, insert, empty) import Data.List (group, sort)   step :: String -> String step = concatMap (\list -> show (length list) ++ [head list]) . group . sort   findCycle :: (Ord a) => [a] -> [a] findCycle = aux empty where aux set (x : xs) | x `member` set = [] | otherwise = x : aux (insert x...
Give a code snippet in #Haskell 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, 31...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection 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 ...
#uBasic.2F4tH
uBasic/4tH
PRINT "Selection sort:" n = FUNC (_InitArray) PROC _ShowArray (n) PROC _Selectionsort (n) PROC _ShowArray (n) PRINT   END     _Selectionsort PARAM (1) ' Selection sort LOCAL (3)   FOR b@ = 0 TO a@-1 c@ = b@   FOR d@ = b@ TO a@-1 IF @(d@) < @(c@) THEN c@ = d@ NEXT   IF b@ ...
Give a code snippet in #uBasic.2F4tH 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 | Q...
christopher/rosetta-code
http://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers
Increasing gaps between consecutive Niven numbers
Note:   Niven   numbers are also called   Harshad   numbers.   They are also called    multidigital   numbers. Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisible with no remainder. Task   find the gap (differen...
#Go
Go
package main   import "fmt"   type is func() uint64   func newSum() is { var ms is ms = func() uint64 { ms = newSum() return ms() } var msd, d uint64 return func() uint64 { if d < 9 { d++ } else { d = 0 msd = ms() } ...
Give a code snippet in #Go Note:   Niven   numbers are also called   Harshad   numbers.   They are also called    multidigital   numbers. Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisible with no remainder. Tas...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#Nanoquery
Nanoquery
import Nanoquery.Util   // a function to check if a year is a leap year def isLeapYear(year) if (year % 100 = 0) return (year % 400 = 0) else return (year % 4 = 0) end end   // a function to format 1-digit numbers as "0x" def form(num) if (num > 9) return str(num) else return "0" + str(num) end end   // g...
Give a code snippet in #Nanoquery Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 ...
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 ...
#ALGOL_68
ALGOL 68
BEGIN []INT s = ( 1, 2, 2, 3, 4, 4, 5 ); FOR i FROM LWB s TO UPB s DO INT curr := s[ i ], prev; IF IF i > LWB s THEN curr = prev ELSE FALSE FI THEN print( ( i, newline ) ) FI; prev := curr OD END
Give a code snippet in #ALGOL_68 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,...
christopher/rosetta-code
http://rosettacode.org/wiki/Image_convolution
Image convolution
One class of image digital filters is described by a rectangular matrix of real coefficients called kernel convoluted in a sliding window of image pixels. Usually the kernel is square K k l {\displaystyle K_{kl}} , where k, l are in the range -R,-R+1,..,R-1,R. W=2R+1 is the kernel width. The filter determine...
#Octave
Octave
function [r, g, b] = rgbconv2(a, c) r = im2uint8(mat2gray(conv2(a(:,:,1), c))); g = im2uint8(mat2gray(conv2(a(:,:,2), c))); b = im2uint8(mat2gray(conv2(a(:,:,3), c))); endfunction   im = jpgread("Lenna100.jpg"); emboss = [-2, -1, 0; -1, 1, 1; 0, 1, 2 ]; sobel = [-1., -2., -1.; 0., 0., 0.; ...
Give a code snippet in #Octave One class of image digital filters is described by a rectangular matrix of real coefficients called kernel convoluted in a sliding window of image pixels. Usually the kernel is square K k l {\displaystyle K_{kl}} , where k, l are in the range -R,-R+1,..,R-1,R. W=2R+1 is the ke...
christopher/rosetta-code
http://rosettacode.org/wiki/Teacup_rim_text
Teacup rim text
On a set of coasters we have, there's a picture of a teacup.   On the rim of the teacup the word   TEA   appears a number of times separated by bullet characters   (•). It occurred to me that if the bullet were removed and the words run together,   you could start at any letter and still end up with a meaningful three...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[Teacuppable] TeacuppableHelper[set_List] := Module[{f, s}, f = First[set]; s = StringRotateLeft[f, #] & /@ Range[Length[set]]; Sort[s] == Sort[set] ] Teacuppable[set_List] := Module[{ss, l}, l = StringLength[First[set]]; ss = Subsets[set, {l}]; Select[ss, TeacuppableHelper] ] s = Import["http:/...
Give a code snippet in #Mathematica.2FWolfram_Language On a set of coasters we have, there's a picture of a teacup.   On the rim of the teacup the word   TEA   appears a number of times separated by bullet characters   (•). It occurred to me that if the bullet were removed and the words run together,   you could star...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Read_a_PPM_file
Bitmap/Read a PPM file
Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color image to grayscale one.
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Function Bitmap { If match("NN") then { Read x as long, y as long } else.if Match("N") Then { \\ is a file? Read f if not Eof(f) then { Line Input #f, p3$ ...
Give a code snippet in #M2000_Interpreter Using the data storage type defined on this page for raster images, read an image from a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.) Task: Use write ppm file solution and grayscale image solution with this one in order to convert a color ima...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Wortel
Wortel
@sum [1 2 3 4] ; returns 10 @prod [1 2 3 4] ; returns 24
Give a code snippet in #Wortel Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Factor
Factor
( scratchpad ) { "a" "b" "c" "d" "e" "f" } random . "a"
Give a code snippet in #Factor Demonstrate how to pick a random element from a list.
christopher/rosetta-code
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#AppleScript
AppleScript
on run script on |λ|(x) script on |λ|(y) script on |λ|(z) if y ≠ z and 1 ≤ z and z ≤ 7 then {{x, y, z} as string} else ...
Give a code snippet in #AppleScript There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be uniq...
christopher/rosetta-code
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#Icon_and_Unicon
Icon and Unicon
# Creation of collections: s := "abccd" # string, an ordered collection of characters, immutable c := 'abcd' # cset, an unordered collection of characters, immutable S := set() # set, an unordered collection of...
Give a code snippet in #Icon_and_Unicon This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at uni...
#JavaScript
JavaScript
#!/usr/bin/env js   function main() { var wordList = read('unixdict.txt').split(/\s+/); var anagrams = findAnagrams(wordList); var derangedAnagrams = findDerangedAnagrams(anagrams); var longestPair = findLongestDerangedPair(derangedAnagrams); print(longestPair.join(' '));   }   function findLongestD...
Give a code snippet in #JavaScript Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Bounded
Knapsack problem/Bounded
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature.   So he needs some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg weight in his knapsack, because th...
#C.2B.2B
C++
#include <iostream> #include <vector> #include <algorithm> #include <stdexcept> #include <memory> #include <sys/time.h>   using std::cout; using std::endl;   class StopTimer { public: StopTimer(): begin_(getUsec()) {} unsigned long long getTime() const { return getUsec() - begin_; } private: static unsigned...
Give a code snippet in #C.2B.2B A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature.   So he needs some items during the trip.   Food, clothing, etc.   He has a good knapsack for carrying the things, but he knows that he can carry only 4 kg w...
christopher/rosetta-code
http://rosettacode.org/wiki/Odd_word_problem
Odd word problem
Task Write a program that solves the odd word problem with the restrictions given below. Description You are promised an input stream consisting of English letters and punctuations. It is guaranteed that: the words (sequence of consecutive letters) are delimited by one and only one punctuation, the stream will...
#Phix
Phix
with javascript_semantics string s = "what,is,the;meaning,of:life." --string s = "we,are;not,in,kansas;any,more." integer i = 0 function getchar() i += 1 return s[i] end function function wrod(integer rev) integer ch = getchar(), nch -- integer ch = getc(0), nch if not find(ch," .,:;!?") then ...
Give a code snippet in #Phix Task Write a program that solves the odd word problem with the restrictions given below. Description You are promised an input stream consisting of English letters and punctuations. It is guaranteed that: the words (sequence of consecutive letters) are delimited by one and only one...
christopher/rosetta-code
http://rosettacode.org/wiki/Tau_number
Tau number
A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau function
#Haskell
Haskell
tau :: Integral a => a -> a tau n | n <= 0 = error "Not a positive integer" tau n = go 0 (1, 1) where yo i = (i, i * i) go r (i, ii) | n < ii = r | n == ii = r + 1 | 0 == mod n i = go (r + 2) (yo $ i + 1) | otherwise = go r (yo $ i + 1)   isTau :: Integral a => a -> Bool isTa...
Give a code snippet in #Haskell A Tau number is a positive integer divisible by the count of its positive divisors. Task Show the first   100   Tau numbers. The numbers shall be generated during run-time (i.e. the code may not contain string literals, sets/arrays of integers, or alike). Related task  Tau functi...
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 ...
#SPAD
SPAD
  NNI ==> NonNegativeInteger   A:(NNI,NNI) -> NNI   A(m,n) == m=0 => n+1 m>0 and n=0 => A(m-1,1) m>0 and n>0 => A(m-1,A(m,n-1))   -- Example matrix [[A(i,j) for i in 0..3] for j in 0..3]  
Give a code snippet in #SPAD 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/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#Ruby
Ruby
Some object-oriented languages won't let you subclass the "basic" data types like integers. Other languages implement those data types as classes, so you can subclass them, no questions asked. Ruby implements numbers as classes (Integer, with its concrete subclasses Fixnum and Bignum), and you can subclass those classe...
Give a code snippet in #Ruby Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
christopher/rosetta-code
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#JavaScript
JavaScript
  function test() { let n = 0 for(let i = 0; i < 1000000; i++){ n += i } }   let start = new Date().valueOf() test() let end = new Date().valueOf()   console.log('test() took ' + ((end - start) / 1000) + ' seconds') // test() took 0.001 seconds  
Give a code snippet in #JavaScript Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time be...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#Javascript.2FNodeJS
Javascript/NodeJS
node -p -e "Boolean(process.stdout.isTTY)" true
Give a code snippet in #Javascript.2FNodeJS Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
christopher/rosetta-code
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture
Euler's sum of powers conjecture
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power, except for the trivial case...
#SenseTalk
SenseTalk
findEulerSumOfPowers to findEulerSumOfPowers set MAX_NUMBER to 250 set possibleValues to 1..MAX_NUMBER set possible5thPowers to each item of possibleValues to the power of 5 repeat for x0 in 1..250 repeat for x1 in 1..x0 repeat for x2 in 1..x1 repeat for x3 in 1..x2 ...
Give a code snippet in #SenseTalk There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth pow...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle n...
#Forth
Forth
: quadratic ( fa fb fc -- r1 r2 ) frot frot ( c a b ) fover 3 fpick f* -4e f* fover fdup f* f+ ( c a b det ) fdup f0< if abort" imaginary roots" then fsqrt fover f0< if fnegate then f+ fnegate ( c a b-det ) 2e f/ fover f/ ( c a r1 ) frot frot f/ fover f/ ;
Give a code snippet in #Forth This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your ...
christopher/rosetta-code
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform
Burrows–Wheeler transform
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Burrows–Wheeler transform (BWT, also called block-s...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   namespace BurrowsWheeler { class Program { const char STX = (char)0x02; const char ETX = (char)0x03;   private static void Rotate(ref char[] a) { char t = a.Last(); for (int i = a.Length - 1; i > 0; ...
Give a code snippet in #C.23 This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Burrows–Wheeler trans...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ...
#11l
11l
F mean_angle(angles) V x = sum(angles.map(a -> cos(radians(a)))) / angles.len V y = sum(angles.map(a -> sin(radians(a)))) / angles.len R degrees(atan2(y, x))   print(mean_angle([350, 10])) print(mean_angle([90, 180, 270, 360])) print(mean_angle([10, 20, 30]))
Give a code snippet in #11l When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first readin...
christopher/rosetta-code
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#Seed7
Seed7
$ include "seed7_05.s7i";   enable_output(set of string);   const proc: main is func local var set of string: aSet is {"iron", "copper"}; begin writeln(aSet); incl(aSet, "silver"); writeln(aSet); end func;
Give a code snippet in #Seed7 This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Cr...
christopher/rosetta-code
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#Ring
Ring
  load "guilib.ring" load "stdlib.ring"   new qapp { win1 = new qwidget() { setwindowtitle("drawing using qpainter") setgeometry(100,100,500,500) label1 = new qlabel(win1) { setgeometry(10,10,400,400) ...
Give a code snippet in #Ring Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection
Factorial base numbers indexing permutations of a collection
You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers. The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0....
#Factor
Factor
USING: assocs io kernel literals math math.factorials math.parser math.ranges prettyprint qw random sequences splitting ; RENAME: factoradic math.combinatorics.private => _factoradic RENAME: rotate sequences.extras => _rotate IN: rosetta-code.factorial-permutations   CONSTANT: shoe $[ qw{ A K Q J 10 9 8 7 6 5 4 3 2...
Give a code snippet in #Factor You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers. The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0,...
christopher/rosetta-code
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial ...
#Objeck
Objeck
class AksTest { @c : static : Int[];   function : Main(args : String[]) ~ Nil { @c := Int->New[100];   for(n := 0; n < 10; n++;) { Coef(n); "(x-1)^ {$n} = "->Print(); Show(n); '\n'->Print(); };   "\nPrimes:"->PrintLine(); for(n := 2; n <= 63; n++;) { if(IsPrime(n)) ...
Give a code snippet in #Objeck The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#F.23
F#
for i in 2..2..8 do printf "%d, " i printfn "done"
Give a code snippet in #F.23 Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Incr...
christopher/rosetta-code
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#V
V
[4 3 2 1] 5 swap cons =[5 4 3 2 1]
Give a code snippet in #V This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create...
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_lines_from_a_file
Remove lines from a file
Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th...
#Racket
Racket
  #lang racket (define (remove-lines file from num) (define lines (file->lines file)) (define-values [pfx rest] (split-at lines (sub1 from))) (display-lines-to-file (append pfx (drop rest num)) file #:exists 'replace))  
Give a code snippet in #Racket Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to re...
christopher/rosetta-code
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#Scala
Scala
object SudokuSolver extends App {   class Solver {   var solution = new Array[Int](81) //listOfFields toArray   val fp2m: Int => Tuple2[Int,Int] = pos => Pair(pos/9+1,pos%9+1) //get row, col from array position val setAll = (1 to 9) toSet //all possibilities   val arrayGroups = new Array[List[List[I...
Give a code snippet in #Scala Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#Rust
Rust
  extern crate rug;   use rug::Integer; use rug::ops::Pow;   fn main() { for i in [3, 20, 100, 1_000].iter() { let ten = Integer::from(10); let mut limit = Integer::from(Integer::from(&ten.pow(*i as u32)) - 1); let mut aux_3_1 = &limit.mod_u(3u32); let mut aux_3_2 = Integer::from(&li...
Give a code snippet in #Rust Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Fortran
Fortran
program Knuth_Shuffle implicit none   integer, parameter :: reps = 1000000 integer :: i, n integer, dimension(10) :: a, bins = 0, initial = (/ (n, n=1,10) /)   do i = 1, reps a = initial call Shuffle(a) where (a == initial) bins = bins + 1 ! skew tester end do write(*, "(10(i8))") bins ! print...
Give a code snippet in #Fortran The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from ...
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
#Dao
Dao
io.writeln( 'Hello world!' )
Give a code snippet in #Dao 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/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Elena
Elena
import system'routines; import extensions; import extensions'routines; import extensions'text;   extension bottleOp { bottleDescription() = self.toPrintable() + (self != 1).iif(" bottles"," bottle");   bottleEnumerator() = new Variable(self).doWith:(n) { ^ new Enumerator { ...
Give a code snippet in #Elena Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_time_of_day
Averages/Mean time of day
Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of Averages/Mean angle compute ...
#Fortran
Fortran
  program mean_time_of_day implicit none integer(kind=4), parameter :: dp = kind(0.0d0)   type time_t integer(kind=4) :: hours, minutes, seconds end type   character(len=8), dimension(4), parameter :: times = & (/ '23:00:17', '23:40:20', '00:12:45', '00:17:19' /) real(kind=dp), dimension(size(times)...
Give a code snippet in #Fortran Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the idea...
christopher/rosetta-code
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on thei...
#Tcl
Tcl
proc findCircles {p1 p2 r} { lassign $p1 x1 y1 lassign $p2 x2 y2 # Special case: coincident & zero size if {$x1 == $x2 && $y1 == $y2 && $r == 0.0} { return [list [list $x1 $y1 0.0]] } if {$r <= 0.0} { error "radius must be positive for sane results" } if {$x1 == $x2 && $y1 == $y2} { e...
Give a code snippet in #Tcl Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of c...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Lasso
Lasso
define stderr(s::string) => { file_stderr->writeBytes(#s->asBytes) }   stderr('Goodbye, World!')
Give a code snippet in #Lasso Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out"...
christopher/rosetta-code
http://rosettacode.org/wiki/String_matching
String matching
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 |...
#AutoIt
AutoIt
$string1 = "arduinoardblobard" $string2 = "ard"   ; == Determining if the first string starts with second string If StringLeft($string1, StringLen($string2)) = $string2 Then ConsoleWrite("1st string starts with 2nd string." & @CRLF) Else ConsoleWrite("1st string does'nt starts with 2nd string." & @CRLF) EndIf   ; == ...
Give a code snippet in #AutoIt Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code
http://rosettacode.org/wiki/Long_literals,_with_continuations
Long literals, with continuations
This task is about writing a computer program that has long literals   (character literals that may require specifying the words/tokens on more than one (source) line,   either with continuations or some other method, such as abutments or concatenations   (or some other mechanisms). The literal is to be in the form ...
#Crystal
Crystal
require "time"   last_revision = Time.utc year: 2021, month: 2, day: 25   # the `%w()` literal creates an array from a whitespace-delimited string literal # it's equivalent to %(string literal).split # https://crystal-lang.org/reference/syntax_and_semantics/literals/string.html element_list : Array(String) = %w( hydrog...
Give a code snippet in #Crystal This task is about writing a computer program that has long literals   (character literals that may require specifying the words/tokens on more than one (source) line,   either with continuations or some other method, such as abutments or concatenations   (or some other mechanisms). ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to chec...
#Java
Java
public class Pangram { public static boolean isPangram(String test){ for (char a = 'A'; a <= 'Z'; a++) if ((test.indexOf(a) < 0) && (test.indexOf((char)(a + 32)) < 0)) return false; return true; }   public static void main(String[] args){ System.out.printl...
Give a code snippet in #Java Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Writ...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#Julia
Julia
stack = Int[] # [] @show push!(stack, 1) # [1] @show push!(stack, 2) # [1, 2] @show push!(stack, 3) # [1, 2, 3] @show pop!(stack) # 3 @show length(stack) # 2 @show empty!(stack) # [] @show isempty(stack) # true
Give a code snippet in #Julia Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is ac...
christopher/rosetta-code
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
maxit = 13; maxitj = 10; a1 = 1.0; a2 = 0.0; d1 = 3.2; a = 0.0; Table[ a = a1 + (a1 - a2)/d1; Do[ x = 0.0; y = 0.0; Do[ y = 1.0 - 2.0 y x; x = a - x x; , {k, 1, 2^i} ]; a = a - x/y , {j, maxitj} ]; d = (a1 - a2)/(a - a1); d1 = d; a2 = a1; a1 = a; {i, d} , {i, 2...
Give a code snippet in #Mathematica.2FWolfram_Language Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
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.)
#Intercal
Intercal
PLEASE NOTE This is a comment
Give a code snippet in #Intercal 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/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
PrecisionDigits = 85; AGMean[a_, b_] := FixedPoint[{ Tr@#/2, Sqrt[Times@@#] }&, N[{a,b}, PrecisionDigits]]〚1〛
Give a code snippet in #Mathematica.2FWolfram_Language This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#SenseTalk
SenseTalk
set the remoteWorkInterval to .001 -- optional repeat forever repeat forever set description to "Enter a 4 digit number" & newline & "- zero's excluded" & newline & "- each digit should be unique" & newline Ask "Enter a Number" title "Bulls & Cows (Player)" message description put it into num if num is "" A...
Give a code snippet in #SenseTalk Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only t...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#jq
jq
jq -n —-arg s 'Goodbye, World!' '$s | stderr | empty'
Give a code snippet in #jq Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#BBC_BASIC
BBC BASIC
DEF PROC_ShakerSort(Size%)   Start%=2 End%=Size% Direction%=1 LastChange%=1 REPEAT FOR J% = Start% TO End% STEP Direction% IF data%(J%-1) > data%(J%) THEN SWAP data%(J%-1),data%(J%) LastChange% = J% ENDIF NEXT J% End% = Start% Start% = LastChange% - Direction% Direction% = Direction% * -...
Give a code snippet in #BBC_BASIC 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 | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#Groovy
Groovy
rnd = new Random() result = (1..1000).inject([]) { r, i -> r << rnd.nextGaussian() }
Give a code snippet in #Groovy Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Relate...
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 ...
#PicoLisp
PicoLisp
(de levenshtein (A B) (let D (cons (range 0 (length A)) (mapcar '((I) (cons I (copy A))) (range 1 (length B)) ) ) (for (J . Y) B (for (I . X) A (set (nth D (inc J) (inc I)) (if (= X Y) (get D J ...
Give a code snippet in #PicoLisp 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Swift
Swift
import Foundation import Numerics import QDBMP   public typealias Color = (red: UInt8, green: UInt8, blue: UInt8)   public class BitmapDrawer { public let imageHeight: Int public let imageWidth: Int   var grid: [[Color?]]   private let bmp: OpaquePointer   public init(height: Int, width: Int) { self.image...
Give a code snippet in #Swift Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Scheme
Scheme
(define (me-errors xx exception) (if (even? xx) xx (exception)))   ;example that does nothing special on exception (call/cc (lambda (exception) (me-errors 222 exception) (display "I guess everything is alright")))   ;example that laments oddness on exception (call/cc (lambda (all-ok) ;used t...
Give a code snippet in #Scheme Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exception...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Heapsort
Sorting algorithms/Heapsort
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 ...
#Racket
Racket
  #lang racket (require (only-in srfi/43 vector-swap!))   (define (heap-sort! xs) (define (ref i) (vector-ref xs i)) (define (swap! i j) (vector-swap! xs i j)) (define size (vector-length xs))   (define (sift-down! r end) (define c (+ (* 2 r) 1)) (define c+1 (+ c 1)) (when (<= c end) (define c...
Give a code snippet in #Racket 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/Compiler/AST_interpreter
Compiler/AST interpreter
An AST interpreter interprets an Abstract Syntax Tree (AST) produced by a Syntax Analyzer. Task[edit] Take the AST output from the Syntax analyzer task, and interpret it as appropriate. Refer to the Syntax analyzer task for details of the AST. Loading the AST from the syntax analyzer is as simple as (pseudo code) de...
#zkl
zkl
const{ var _n=-1; var[proxy]N=fcn{ _n+=1 }; } // enumerator const FETCH=N, STORE=N, PUSH=N, ADD=N, SUB=N, MUL=N, DIV=N, MOD=N, LT=N, GT=N, LE=N, GE=N, EQ=N, NE=N, AND=N, OR=N, NEG=N, NOT=N, JMP=N, JZ=N, PRTC=N, PRTS=N, PRTI=N, HALT=N; const nd_String=N, nd_Sequence=N, nd_If...
Give a code snippet in #zkl An AST interpreter interprets an Abstract Syntax Tree (AST) produced by a Syntax Analyzer. Task[edit] Take the AST output from the Syntax analyzer task, and interpret it as appropriate. Refer to the Syntax analyzer task for details of the AST. Loading the AST from the syntax analyzer is a...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_factors
Count in factors
Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would be shown as   2 × 3 {\di...
#Octave
Octave
for (n = 1:20) printf ("%i: ", n) printf ("%i ", factor (n)) printf ("\n") endfor
Give a code snippet in #Octave Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it woul...
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
#Sidef
Sidef
func f(n {.is_prime}) { n.prime**(n-1) }   func f(n) { n.th { .sigma0 == n } }   say 20.of { f(_+1) }
Give a code snippet in #Sidef 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/Password_generator
Password generator
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above ch...
#Arturo
Arturo
lowercase: `a`..`z` uppercase: `A`..`Z` digits: `0`..`9` other: map split "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" => [to :char]   any: lowercase ++ uppercase ++ digits ++ other   generate: function [length][ if length < 4 [ print (color #red "ERROR: ") ++ "password length too short" exit ]   chars...
Give a code snippet in #Arturo Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-....
christopher/rosetta-code
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#REBOL
REBOL
rebol [ Title: "Basic Animation" URL: http://rosettacode.org/wiki/Basic_Animation ]   message: "Hello World! " how: 1   roll: func [ "Shifts a text string right or left by one character." text [string!] "Text to shift." direction [integer!] "Direction to shift -- right: 1, left: -1." /local h t ][ either direct...
Give a code snippet in #REBOL Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task de...
christopher/rosetta-code
http://rosettacode.org/wiki/Rate_counter
Rate counter
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish these goals: Run N seconds worth...
#Kotlin
Kotlin
// version 1.1.3   typealias Func<T> = (T) -> T   fun cube(n: Int) = n * n * n   fun <T> benchmark(n: Int, func: Func<T>, arg: T): LongArray { val times = LongArray(n) for (i in 0 until n) { val m = System.nanoTime() func(arg) times[i] = System.nanoTime() - m } return times } ...
Give a code snippet in #Kotlin Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish th...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Racket
Racket
  #lang racket (for/sum ([x #(3 1 4 1 5 9)]) (* x x))  
Give a code snippet in #Racket Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_easy
Abbreviations, easy
This task is an easier (to code) variant of the Rosetta Code task:   Abbreviations, simple. For this task, the following   command table   will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find ...
#Ruby
Ruby
#!/usr/bin/env ruby   cmd_table = File.read(ARGV[0]).split user_str = File.read(ARGV[1]).split   user_str.each do |abbr| candidate = cmd_table.find do |cmd| cmd.count('A-Z') <= abbr.length && abbr.casecmp(cmd[0...abbr.length]).zero? end   print candidate.nil? ? '*error*' : candidate.upcase   print ' ' end  ...
Give a code snippet in #Ruby This task is an easier (to code) variant of the Rosetta Code task:   Abbreviations, simple. For this task, the following   command table   will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlic...
christopher/rosetta-code
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. 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 algebra, polynomial long division is an algorithm for d...
#Wren
Wren
import "/dynamic" for Tuple   var Solution = Tuple.create("Solution", ["quotient", "remainder"])   var polyDegree = Fn.new { |p| for (i in p.count-1..0) if (p[i] != 0) return i return -2.pow(31) }   var polyShiftRight = Fn.new { |p, places| if (places <= 0) return p var pd = polyDegree.call(p) if (p...
Give a code snippet in #Wren This page uses content from Wikipedia. The original article was at Polynomial long division. 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 algebra, polynomial long ...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Count_examples
Rosetta Code/Count examples
task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'll need to use the Media Wiki AP...
#Nim
Nim
import httpclient, strutils, xmltree, xmlparser, cgi   proc count(s, sub: string): int = var i = 0 while true: i = s.find(sub, i) if i < 0: break inc i inc result   const mainSite = "http://www.rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=...
Give a code snippet in #Nim task Essentially, count the number of occurrences of =={{header| on each task page. Output: 100 doors: 20 examples. 99 Bottles of Beer: 29 examples. Abstract type: 10 examples. Total: X examples. For a full output, updated periodically, see Rosetta Code/Count examples/Full list. You'll ...
christopher/rosetta-code
http://rosettacode.org/wiki/File_size_distribution
File size distribution
Task Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy. My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may no...
#Haskell
Haskell
{-# LANGUAGE LambdaCase #-}   import Control.Concurrent (forkIO, setNumCapabilities) import Control.Concurrent.Chan (Chan, newChan, readChan, writeChan, writeList2Chan) import Control.Exception (IOException, catch) import...
Give a code snippet in #Haskell Task Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy. My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even...
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.)
#Simula
Simula
COMMENT This is a comment for Simula 67;
Give a code snippet in #Simula 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/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#AutoHotkey
AutoHotkey
#NoEnv ; Set the floating-point precision SetFormat, Float, 0.15 ; Super-global variables for function objects Global F, G ; User-defined functions Cube(X) { Return X ** 3 } CubeRoot(X) { Return X ** (1/3) } ; Function arrays, Sin/ASin and Cos/ACos are built-in FuncArray1 := [Func("Sin"), Func("Cos"), Func("Cub...
Give a code snippet in #AutoHotkey A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to ot...
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 ...
#Wart
Wart
def (dedup l) let exists (table) collect+each x l unless exists.x yield x exists.x <- 1
Give a code snippet in #Wart Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Objeck
Objeck
  bundle Default { class ReadFile { function : Main(args : String[]) ~ Nil { f := IO.FileReader->New("in.txt"); if(f->IsOpen()) { string := f->ReadString(); while(f->IsEOF() = false) { string->PrintLine(); string := f->ReadString(); }; f->Close(); ...
Give a code snippet in #Objeck Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Modula-2
Modula-2
  MODULE ReverseWords;   FROM STextIO IMPORT WriteString, WriteLn; FROM Strings IMPORT Assign, Concat, Append;   CONST NL = CHR(10); Sp = ' '; Txt = "---------- Ice and Fire -----------" + NL + NL + "fire, in end will world the say Some" + NL + "ice. in say Some" + NL + "desire of tasted I've ...
Give a code snippet in #Modula-2 Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by s...
christopher/rosetta-code
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   ...
#C.2B.2B
C++
#include <iomanip> #include <iostream>   bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; ...
Give a code snippet in #C.2B.2B Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entr...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#Clojure
Clojure
user=> 2r1001 9 user=> 8r64 52 user=> 064 52 user=> 16r4b 75 user=> 0x4b 75 user=>
Give a code snippet in #Clojure Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should ...
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...
#68000_Assembly
68000 Assembly
EXG D0,D1 ;swap the contents of D0 and D1 EXG A0,A1 ;swap the contents of A0 and A1
Give a code snippet in #68000_Assembly 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Lasso
Lasso
define isLeapYear(y::integer) => { #y % 400 == 0 ? return true #y % 100 == 0 ? return false #y % 4 == 0 ? return true return false }   with test in array(2012,2016,1933,1900,1999,2000) do => {^ isLeapYear(#test) '\r' ^}
Give a code snippet in #Lasso Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for ...
#Common_Lisp
Common Lisp
  (defvar ♥♦♣♠ "♥♦♣♠") (defun ✈ () "a plane unicode function")  
Give a code snippet in #Common_Lisp As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepa...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Write_a_PPM_file
Bitmap/Write a PPM file
Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
#Phix
Phix
-- demo\rosetta\Bitmap_write_ppm.exw constant dimx = 512, dimy = 512 constant fn = open("first.ppm","wb") -- b - binary mode sequence color printf(fn, "P6\n%d %d\n255\n", {dimx,dimy}) for y=0 to dimy-1 do for x=0 to dimx-1 do color = {remainder(x,256), -- red remainder(y,256), -- green ...
Give a code snippet in #Phix Using the data storage type defined on this page for raster images, write the image to a PPM file (binary P6 prefered). (Read the definition of PPM file on Wikipedia.)
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 |...
#Scheme
Scheme
  ;; Comparing two strings for exact equality (string=? "hello" "hello")   ;; Comparing two strings for inequality (not (string=? "hello" "Hello"))   ;; Checking if the first string is lexically ordered before the second (string<? "bar" "foo")   ;; Checking if the first string is lexically ordered after the second (st...
Give a code snippet in #Scheme Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code
http://rosettacode.org/wiki/Resistor_mesh
Resistor mesh
Task Given   10×10   grid nodes   (as shown in the image)   interconnected by   1Ω   resistors as shown, find the resistance between points   A   and   B. See also   (humor, nerd sniping)   xkcd.com cartoon
#Euler_Math_Toolbox
Euler Math Toolbox
  >load incidence; >{u,r}=solvePotentialX(makeRectangleX(10,10),12,68); r, 1.60899124173  
Give a code snippet in #Euler_Math_Toolbox Task Given   10×10   grid nodes   (as shown in the image)   interconnected by   1Ω   resistors as shown, find the resistance between points   A   and   B. See also   (humor, nerd sniping)   xkcd.com cartoon
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
local :open-doors [ rep 101 false ]   for i range 1 100: local :j i while <= j 100: set-to open-doors j not open-doors! j set :j + j i   !print\ "Open doors: " for i range 1 100: if open-doors! i: !print\( to-str i " " )
Give a code snippet in #D.C3.A9j.C3.A0_Vu There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2...
christopher/rosetta-code
http://rosettacode.org/wiki/Playfair_cipher
Playfair cipher
Playfair cipher You are encouraged to solve this task according to the task description, using any language you may know. Task Implement a Playfair cipher for encryption and decryption. The user must be able to choose   J  =  I     or   no   Q   in the alphabet. The output of the encrypted and decrypted message ...
#Julia
Julia
function playfair(key, txt, isencode=true, from = "J", to = "") to = (to == "" && from == "J") ? "I" : to   function canonical(s, dup_toX=true) s = replace(replace(uppercase(s), from => to), r"[^A-Z]" => "") a, dupcount = [c for c in s], 0 for i in 1:2:length(a)-1 if s[i] == ...
Give a code snippet in #Julia Playfair cipher You are encouraged to solve this task according to the task description, using any language you may know. Task Implement a Playfair cipher for encryption and decryption. The user must be able to choose   J  =  I     or   no   Q   in the alphabet. The output of the e...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#Maxima
Maxima
load("c:/.../source.mac")$   /* or if source.mac is in Maxima search path (see ??file_search_maxima), simply */ load(source)$
Give a code snippet in #Maxima Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#Quackery
Quackery
[ over 3 < if [ 1 - ] dup 4 / over + over 100 / - swap 400 / + swap 1 - [ table 0 3 2 5 0 3 5 1 4 6 2 4 ] + + 7 mod ] is dayofweek ( day month year --> weekday )   [ dup 400 mod 0 = iff [ drop true ] done dup 100 mod 0 = iff [ drop false ] ...
Give a code snippet in #Quackery Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2...
christopher/rosetta-code
http://rosettacode.org/wiki/Pig_the_dice_game
Pig the dice game
The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to their score for that turn and th...
#Eiffel
Eiffel
  class PLAYER create set_name feature set_name(n:STRING) do name := n.twin set_points(0) end   strategy(cur_points:INTEGER) local current_points, thrown:INTEGER do io.put_string ("You currently have " +points.out+". %NDo you want to save your points? Press y or n.%N") io.read_line if io.l...
Give a code snippet in #Eiffel The   game of Pig   is a multiplayer game played with a single six-sided die.   The object of the game is to reach   100   points or more.   Play is taken in turns.   On each person's turn that person has the option of either: Rolling the dice:   where a roll of two to six is added to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1...
#AppleScript
AppleScript
set n to 5 set k to 3   on calculateFactorial(val) set partial_factorial to 1 as integer repeat with i from 1 to val set factorial to i * partial_factorial set partial_factorial to factorial end repeat return factorial end calculateFactorial   set n_factorial to calculateFactorial(n) set k_factorial to calculat...
Give a code snippet in #AppleScript This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#J
J
NB. knight moves for each square of a (y,y) board kmoves=: monad define t=. (>,{;~i.y) +"1/ _2]\2 1 2 _1 1 2 1 _2 _1 2 _1 _2 _2 1 _2 _1 (*./"1 t e. i.y) <@#"1 y#.t )   ktourw=: monad define M=. >kmoves y p=. k=. 0 b=. 1 $~ *:y for. i.<:*:y do. b=. 0 k}b p=. p,k=. ((i.<./) +/"1 b{~j{M){j=. ({&b # ]) k{M end....
Give a code snippet in #J Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; tha...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#MAXScript
MAXScript
  rand = random 1 10 clearListener() while true do ( userval = getKBValue prompt:"Enter an integer between 1 and 10: " if userval == rand do (format "\nWell guessed!\n"; exit) format "\nChoose another value\n" )  
Give a code snippet in #MAXScript Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Deluge
Deluge
if (input.Field == "Hello World") { sVar = "good"; } else if (input.Field == "Bye World") { sVar = "bad"; } else { sVar = "neutral"; }
Give a code snippet in #Deluge 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...
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 ...
#Sidef
Sidef
func in_order(a) { return true if (a.len <= 1); var first = a[0]; a.ft(1).all { |elem| first <= elem  ? do { first = elem; true } : false } }   func bogosort(a) { a.shuffle! while !in_order(a); return a; }   var arr = 5.of{ 100.rand.int }; say "Before: #{arr}"; say "After: #{bogosort(arr)}";
Give a code snippet in #Sidef 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/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Arturo
Arturo
result: new []   queens: function [n, i, a, b, c][ if? i < n [ loop 1..n 'j [ if all? @[ not? contains? a j not? contains? b i+j not? contains? c i-j ] -> queens n, i+1, a ++ @[j], b ++ @[i+j], c ++ @[i-j]   ] ...
Give a code snippet in #Arturo Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's ...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_definition
Singly-linked list/Element definition
singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, Lis...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program defList.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ READ, 3 .equ WRITE, 4   .equ NBELEMENTS, 100 @ list size   /***************************...
Give a code snippet in #ARM_Assembly singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Elem...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337346448646612254452369009474497523...
#Nim
Nim
import bigints   proc powmod(b, e, m: BigInt): BigInt = assert e >= 0 var e = e var b = b result = initBigInt(1) while e > 0: if e mod 2 == 1: result = (result * b) mod m e = e div 2 b = (b.pow 2) mod m   var a = initBigInt("29883481620585741369158914214988194663201633129269524237910230788...
Give a code snippet in #Nim Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 2351399303373464...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#Ursala
Ursala
#import flo #import nat   #cast %e   total = plus:-0 div/*1. sqr* float*t iota 1001
Give a code snippet in #Ursala Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = ...
christopher/rosetta-code
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#Forth
Forth
: AMOUNT 1000 ;   variable mertens AMOUNT cells allot : M 1- cells mertens + ; \ 1-indexed array   : make-mertens 1 1 M ! 2 begin dup AMOUNT <= while 1 over M ! 2 begin over over >= while over over / M @ 2 pick M @ swap - 2 pick M ! 1+ repeat drop 1+ repeat drop ;   : print...
Give a code snippet in #Forth The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbiu...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#Delphi
Delphi
def combinations(m, range) { return if (m <=> 0) { [[]] } else { def combGenerator { to iterate(f) { for i in range { for suffix in combinations(m.previous(), range & (int > i)) { f(null, [i] + suffix) } } } } } }
Give a code snippet in #Delphi Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations [SetVid($112); \set 640x480 graphics in 24-bit color Move(10, 20); \set start of line segment Line(600, 400, $123456);\draw line segment, red=$12, green=$34, blue=$56 if ChIn(1) then []; \wait for keystroke while viewing graphic screen SetVid...
Give a code snippet in #XPL0 Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#VBScript
VBScript
  WScript.Echo DotProduct("1,3,-5","4,-2,-1")   Function DotProduct(vector1,vector2) arrv1 = Split(vector1,",") arrv2 = Split(vector2,",") If UBound(arrv1) <> UBound(arrv2) Then WScript.Echo "The vectors are not of the same length." Exit Function End If DotProduct = 0 For i = 0 To UBound(arrv1) DotProduct =...
Give a code snippet in #VBScript Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2,...
christopher/rosetta-code
http://rosettacode.org/wiki/EKG_sequence_convergence
EKG sequence convergence
The sequence is from the natural numbers and is defined by: a(1) = 1; a(2) = Start = 2; for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used. The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed)....
#11l
11l
F ekg(n, limit) Set[Int] values assert(n >= 2) V r = [(1, 1), (2, n)] values.add(n) V i = 3 V prev = n L i <= limit V val = 2 L I val !C values & gcd(val, prev) != 1 values.add(val) r [+]= (i, val) prev = val L.break val+...
Give a code snippet in #11l The sequence is from the natural numbers and is defined by: a(1) = 1; a(2) = Start = 2; for n > 2, a(n) shares at least one prime factor with a(n-1) and is the smallest such natural number not already used. The sequence is called the EKG sequence (after its visual similarity to an ele...
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagorean_quadruples
Pythagorean quadruples
One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclusive),   for all values of   ...
#Perl
Perl
my $N = 2200; push @sq, $_**2 for 0 .. $N; my @not = (0) x $N; @not[0] = 1;     for my $d (1 .. $N) { my $last = 0; for my $a (reverse ceiling($d/3) .. $d) { for my $b (1 .. ceiling($a/2)) { my $ab = $sq[$a] + $sq[$b]; last if $ab > $sq[$d]; my $x = sqrt($sq[$d] - $ab...
Give a code snippet in #Perl One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (incl...
christopher/rosetta-code