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/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#HicEst
HicEst
WINDOW(WINdowhandle=handle, Width=80, Height=-400, X=1, Y=1/2, TItle="Rosetta Window_creation Example") ! window units: as pixels < 0, as relative window size 0...1, ascurrent character sizes > 1   WRITE(WINdowhandle=handle) '... some output ...'
Give a code snippet in #HicEst Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
christopher/rosetta-code
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#R
R
  price_fraction <- function(x) { stopifnot(all(x >= 0 & x <= 1)) breaks <- seq(0.06, 1.01, 0.05) values <- c(.1, .18, .26, .32, .38, .44, .5, .54, .58, .62, .66, .7, .74, .78, .82, .86, .9, .94, .98, 1) indices <- sapply(x, function(x) which(x < breaks)[1]) values[indices] }   #Example usage: price_fraction(...
Give a code snippet in #R A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1....
christopher/rosetta-code
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   wher...
#Icon_and_Unicon
Icon and Unicon
  class Quaternion(a, b, c, d)   method norm () return sqrt (a*a + b*b + c*c + d*d) end   method negative () return Quaternion(-a, -b, -c, -d) end   method conjugate () return Quaternion(a, -b, -c, -d) end   method add (n) if type(n) == "Quaternion__state" then return Quaternion(a+...
Give a code snippet in #Icon_and_Unicon Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a compl...
christopher/rosetta-code
http://rosettacode.org/wiki/Extensible_prime_generator
Extensible prime generator
Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In thi...
#Haskell
Haskell
#!/usr/bin/env runghc   import Data.List import Data.Numbers.Primes import System.IO   firstNPrimes :: Integer -> [Integer] firstNPrimes n = genericTake n primes   primesBetweenInclusive :: Integer -> Integer -> [Integer] primesBetweenInclusive lo hi = dropWhile (< lo) $ takeWhile (<= hi) primes   nthPrime :: Integer...
Give a code snippet in #Haskell Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#M2000_Interpreter
M2000 Interpreter
  Module CheckAll { Module CheckVectorType { Dim Keys$(4), Values(4) Keys$(0):= "one","two","three","four" Values(0):=1,2,3,4 Inventory Dict For i=0 to 3 { Append Dict, Keys$(i):=Values(i) } Print Dict("one")+Dic...
Give a code snippet in #M2000_Interpreter Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
christopher/rosetta-code
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#Haskell
Haskell
import Control.Monad (forM_) import Data.List (intercalate, mapAccumR) import System.Environment (getArgs) import Text.Printf (printf) import Text.Read (readMaybe)   reduceBy :: Integral a => a -> [a] -> [a] n `reduceBy` xs = n' : ys where (n', ys) = mapAccumR quotRem n xs   -- Duration/label pairs. durLabs :: [(Intege...
Give a code snippet in #Haskell Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#Rascal
Rascal
import Prelude;   list[str] OrderedRep(str word){ return sort([word[i] | i <- [0..size(word)-1]]); } public list[set[str]] anagram(){ allwords = readFileLines(|http://wiki.puzzlers.org/pub/wordlists/unixdict.txt|); AnagramMap = invert((word : OrderedRep(word) | word <- allwords)); longest = max([size(group) | grou...
Give a code snippet in #Rascal When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in ...
christopher/rosetta-code
http://rosettacode.org/wiki/Test_integerness
Test integerness
Mathematically, the integers Z are included in the rational numbers Q, which are included in the real numbers R, which can be generalized to the complex numbers C. This means that each of those larger sets, and the data types used to represent them, include some integers. Task[edit] Given a rational, real, or co...
#Fortran
Fortran
MODULE ZERMELO !Approach the foundations of mathematics. CONTAINS LOGICAL FUNCTION ISINTEGRAL(X) !A whole number? REAL*8 X !Alas, this is not really a REAL number. INTEGER*8 N !Largest available. IF (ISNAN(X)) THEN !Avoid some sillyness. ISINTEGRAL = .FALSE. ...
Give a code snippet in #Fortran Mathematically, the integers Z are included in the rational numbers Q, which are included in the real numbers R, which can be generalized to the complex numbers C. This means that each of those larger sets, and the data types used to represent them, include some integers. Task[ed...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
Find largest left truncatable prime in a given base
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2. Let's consider what happens in...
#Ruby
Ruby
  # Compute the largest left truncatable prime # # Nigel_Galloway # September 15th., 2012. # require 'prime' BASE = 3 MAX = 500 stems = Prime.each(BASE-1).to_a (1..MAX-1).each {|i| print "#{stems.length} " t = [] b = BASE ** i stems.each {|z| (1..BASE-1).each {|n| c = n*b+z t.push(c) if c.prim...
Give a code snippet in #Ruby A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Voronoi_diagram
Voronoi diagram
A Voronoi diagram is a diagram consisting of a number of sites. Each Voronoi site s also has a Voronoi cell consisting of all points closest to s. Task Demonstrate how to generate and display a Voroni diagram. See algo K-means++ clustering.
#.D0.9C.D0.9A-61.2F52
МК-61/52
0 П4 0 П5 ИП0 1 - x^2 ИП1 1 - x^2 + КвКор П3 9 П6 КИП6 П8 {x} 2 10^x * П9 [x] ИП5 - x^2 ИП9 {x} 2 10^x * ИП4 - x^2 + КвКор П9 ИП3 - x<0 47 ИП9 П3 ИП6 П7 ИП6 ИП2 - 9 - x>=0 17 КИП7 [x] С/П КИП5 ИП5 ИП1 - x>=0 04 КИП4 ИП4 ИП0 - x>=0 02
Give a code snippet in #.D0.9C.D0.9A-61.2F52 A Voronoi diagram is a diagram consisting of a number of sites. Each Voronoi site s also has a Voronoi cell consisting of all points closest to s. Task Demonstrate how to generate and display a Voroni diagram. See algo K-means++ clustering.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort
Sorting algorithms/Merge 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 ...
#Kotlin
Kotlin
fun mergeSort(list: List<Int>): List<Int> { if (list.size <= 1) { return list }   val left = mutableListOf<Int>() val right = mutableListOf<Int>()   val middle = list.size / 2 list.forEachIndexed { index, number -> if (index < middle) { left.add(number) } else...
Give a code snippet in #Kotlin 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/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The...
#Nanoquery
Nanoquery
import Nanoquery.Util   random = new(Random)   println "<table>"   // generate header println "<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>"   // generate five rows for i in range(1, 5) println "<tr><td style=\"font-weight: bold;\">" + i + "</td>" println "<td>" + int($random.getInt(8999) + 1000) + "</td>" print...
Give a code snippet in #Nanoquery Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Purity
Purity
  data Fib1 = FoldNat < const (Cons One (Cons One Empty)), (uncurry Cons) . ((uncurry Add) . (Head, Head . Tail), id) >  
Give a code snippet in #Purity The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions ar...
christopher/rosetta-code
http://rosettacode.org/wiki/Colorful_numbers
Colorful numbers
A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique. E.G. 24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840 Every product is unique. 2346 ...
#C
C
#include <locale.h> #include <stdbool.h> #include <stdio.h> #include <time.h>   bool colorful(int n) { // A colorful number cannot be greater than 98765432. if (n < 0 || n > 98765432) return false; int digit_count[10] = {}; int digits[8] = {}; int num_digits = 0; for (int m = n; m > 0; m...
Give a code snippet in #C A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique. E.G. 24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840 Every ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#QB64
QB64
FOR c = 1 TO 5 FOR n = 1 TO c PRINT "*"; NEXT PRINT NEXT
Give a code snippet in #QB64 “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structur...
christopher/rosetta-code
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#HicEst
HicEst
REAL :: msec=10, Lrod=1, dBob=0.03, g=9.81, Theta(2), dTheta(2) BobMargins = ALIAS(ls, rs, ts, bs) ! box margins to draw the bob     Theta = (1, 0) ! initial angle and velocity start_t = TIME()   DO i = 1, 1E100 ! "forever" end_t = TIME() ! to integrate in real-time sections: DIFFEQ(Callback="pen...
Give a code snippet in #HicEst One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local var integer: i is 0; begin writeln("Program path: " <& path(PROGRAM)); writeln("Program directory: " <& dir(PROGRAM)); writeln("Program file: " <& file(PROGRAM)); end func;
Give a code snippet in #Seed7 The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script ...
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
#OCaml
OCaml
let () = print_endline ( if Unix.isatty Unix.stdout then "Output goes to tty." else "Output doesn't go to tty." )
Give a code snippet in #OCaml 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/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#TI-89_BASIC
TI-89 BASIC
Local i 1024 → i While i > 0 Disp i intDiv(i, 2) → i EndWhile
Give a code snippet in #TI-89_BASIC Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/D...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequ...
#Wren
Wren
import "/fmt" for Conv   var i = 0 while (true) { System.print(Conv.oct(i)) i = i + 1 }
Give a code snippet in #Wren Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#E
E
var level := 41 var prob := 0.5001   def step() { def success := entropy.nextDouble() < prob level += success.pick(1, -1) return success }
Give a code snippet in #E From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#TSE_SAL
TSE SAL
  INTEGER PROC FNMathGetSumAPlusBI( INTEGER A, INTEGER B ) RETURN( A + B ) END // PROC Main() STRING s1[255] = "3" STRING s2[255] = "2" IF ( NOT ( Ask( "math: get: sum: a: plus: a (choose a number between -1000 and 1000) = ", s1, _EDIT_HISTORY_ ) ) AND ( Length( s1 ) > 0 ) ) RETURN() ENDIF IF ( NOT ( Ask( "math: g...
Give a code snippet in #TSE_SAL A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separa...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell
Terminal control/Ringing the terminal bell
Task Make the terminal running the program ring its "bell". On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal.   It is usua...
#Java
Java
public class Bell{ public static void main(String[] args){ java.awt.Toolkit.getDefaultToolkit().beep();   //or   System.out.println((char)7); } }
Give a code snippet in #Java Task Make the terminal running the program ring its "bell". On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell wit...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I befo...
#Delphi
Delphi
  showmessage( length(['a','b','c']).ToString );  
Give a code snippet in #Delphi Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter freq...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#LIL
LIL
# Arithmetic/Integer, in LIL write "Enter two numbers separated by space: " if {[canread]} {set line [readline]} print   set a [index $line 0] set b [index $line 1] print "A is $a"", B is $b" print "Sum A + B is [expr $a + $b]" print "Difference A - B is [expr $a - $b]" print "Product A *...
Give a code snippet in #LIL 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 Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Cyclops_numbers
Cyclops numbers
A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology. Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10. There are many different ...
#Factor
Factor
USING: accessors formatting grouping io kernel lists lists.lazy math math.functions math.primes prettyprint sequences tools.memory.private tools.time ;       ! ==========={[ Cyclops data type and operations ]}=============   TUPLE: cyclops left right n max ;   : <cyclops> ( -- cyclops ) 1 1 1 9 cyclops boa ;   : >cyclo...
Give a code snippet in #Factor A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology. Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in bas...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl...
#360_Assembly
360 Assembly
CATALAN CSECT USING CATALAN,R13,R12 SAVEAREA B STM-SAVEAREA(R15) DC 17F'0' DC CL8'CATALAN' STM STM R14,R12,12(R13) ST R13,4(R15) ST R15,8(R13) LR R13,R15 LA R12,4095(R13) LA R12,1(...
Give a code snippet in #360_Assembly Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle th...
christopher/rosetta-code
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas
The Twelve Days of Christmas
Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations: Metrics Array length Stri...
#dc
dc
0   d [first] r :n d [A partridge in a pear tree.] r :g 1 +   d [second] r :n d [Two turtle doves and] r :g 1 +   d [third] r :n d [Three French hens,] r :g 1 +   d [fourth] r :n d [Four calling birds,] r...
Give a code snippet in #dc Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations: ...
christopher/rosetta-code
http://rosettacode.org/wiki/Metered_concurrency
Metered concurrency
The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active ...
#J
J
metcon=: {{ sleep=: 6!:3 task=: {{ 11 T. lock NB. wait sleep 2 echo 'Task ',y,&":' has the semaphore' 13 T. lock NB. release }} lock=: 10 T. 0 0&T.@'' each i.0>.4-1 T.'' NB. ensure at least four threads > task t.''"0 i.10 NB. dispatch and wait for 10 tasks...
Give a code snippet in #J The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, relea...
christopher/rosetta-code
http://rosettacode.org/wiki/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#Seed7
Seed7
const float: Infinity is 1.0 / 0.0;
Give a code snippet in #Seed7 Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise,...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. Exec-Hq9.   DATA DIVISION. LOCAL-STORAGE SECTION. 78 Code-Length VALUE 256.   01 i PIC 999. 01 accumulator PIC 999.   01 bottles PIC 999.   LINKAGE SECTION. 01 hq9-code PIC X(Code-Length).   ...
Give a code snippet in #COBOL Task Implement a   HQ9+   interpreter or compiler.
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/String
Literals/String
Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Here document Other tasks r...
#GAP
GAP
IsChar('a'); # true IsString("abc"); # true IsString('a'); # false IsChar("a"); # false
Give a code snippet in #GAP Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   H...
christopher/rosetta-code
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#REXX
REXX
/*REXX program demonstrates a method for catamorphism for some simple functions. */ @list= 1 2 3 4 5 6 7 8 9 10 say 'list:' fold(@list, "list") say ' sum:' fold(@list, "+" ) say 'prod:' fold(@list, "*...
Give a code snippet in #REXX Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming langu...
#Klingphix
Klingphix
include ..\Utilitys.tlhy   33 [ ( "decimal: " swap " bin: " over 8 itob reverse ) lprint nl ] for   "End " input
Give a code snippet in #Klingphix Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion
Singly-linked list/Element insertion
Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Trav...
#360_Assembly
360 Assembly
* Singly-linked list - Insert after 01/02/2017 LISTSINA CSECT USING LISTSINA,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " <- ST R15,8(R13)...
Give a code snippet in #360_Assembly Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element de...
christopher/rosetta-code
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the la...
#Tcl
Tcl
set deepCopy [string range ${valueToCopy}x 0 end-1]
Give a code snippet in #Tcl Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this faci...
christopher/rosetta-code
http://rosettacode.org/wiki/Fast_Fourier_transform
Fast Fourier transform
Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude   (i.e.:   sqrt(re2 + im2)...
#Common_Lisp
Common Lisp
  (defun fft (a &key (inverse nil) &aux (n (length a))) "Perform the FFT recursively on input vector A. Vector A must have length N of power of 2." (declare (type boolean inverse) (type (integer 1) n)) (if (= n 1) a (let* ((n/2 (/ n 2)) (2iπ/n (complex 0 (/ (* 2 pi) n (if in...
Give a code snippet in #Common_Lisp Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the...
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 ...
#Pascal
Pascal
Program RemoveDuplicates;   const iArray: array[1..7] of integer = (1, 2, 2, 3, 4, 5, 5);   var rArray: array[1..7] of integer; i, pos, last: integer; newNumber: boolean;   begin rArray[1] := iArray[1]; last := 1; pos := 1; while pos < high(iArray) do begin inc(pos); newNumber := true; for...
Give a code snippet in #Pascal 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/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#Raku
Raku
sub bentley-clever($seed) { constant $mod = 1_000_000_000; my @seeds = ($seed % $mod, 1, (* - *) % $mod ... *)[^55]; my @state = @seeds[ 34, (* + 34 ) % 55 ... 0 ];   sub subrand() { push @state, (my $x = (@state.shift - @state[*-24]) % $mod); $x; }   subrand for 55 .. 219;   ...
Give a code snippet in #Raku A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Dyalect
Dyalect
func digits(num, bas = 10) { while num != 0 { let (n, digit) = (num / bas, num % bas) num = n yield digit } }   func Iterator.Sum(acc = 0) { for x in this { acc += x } return acc }   func sumOfDigits(num, bas = 10) => digits(num, bas).Sum()   for e in [ (num: 1, ...
Give a code snippet in #Dyalect Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
christopher/rosetta-code
http://rosettacode.org/wiki/Map_range
Map range
Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly mapped to a value   t {\di...
#Axiom
Axiom
)abbrev package TESTP TestPackage TestPackage(R:Field) : with mapRange: (Segment(R), Segment(R)) -> (R->R) == add mapRange(fromRange, toRange) == (a1,a2,b1,b2) := (lo fromRange,hi fromRange,lo toRange,hi toRange) (x:R):R +-> b1+(x-a1)*(b2-b1)/(a2-a1)
Give a code snippet in #Axiom Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly m...
christopher/rosetta-code
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#XPL0
XPL0
int Seq(1001), Back, N, M, Term;   func New; \Return 'true' if last term is new to sequence [for Back:= N-2 downto 1 do if Seq(Back) = Seq(N-1) then return false; return true; ];   func VanEck; \Return term of Van Eck sequence [Seq(N):= if New then 0 else N-Back-1; N:= N+1; return Seq(N-1); ];   [N:= 1...
Give a code snippet in #XPL0 The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured ...
christopher/rosetta-code
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The follow...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
graycode[n_]:=BitXor[n,BitShiftRight[n]] graydecode[n_]:=Fold[BitXor,0,FixedPointList[BitShiftRight,n]]
Give a code snippet in #Mathematica_.2F_Wolfram_Language Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not n...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell 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 ...
#Ruby
Ruby
class Array def shellsort! inc = length / 2 while inc != 0 inc.step(length-1) do |i| el = self[i] while i >= inc and self[i - inc] > el self[i] = self[i - inc] i -= inc end self[i] = el end inc = (inc == 2 ? 1 : (inc * 5.0 / 11).to_i) e...
Give a code snippet in #Ruby 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/Infinity
Infinity
Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity.   Otherwise, return the largest possible po...
#F.C5.8Drmul.C3.A6
Fōrmulæ
# Floating point infinity inf := FLOAT_INT(1) / FLOAT_INT(0);   IS_FLOAT(inf); #true;   # GAP has also a formal ''infinity'' value infinity in Cyclotomics; # true
Give a code snippet in #F.C5.8Drmul.C3.A6 Task Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity. ...
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...
#PowerShell
PowerShell
  function last-dayofweek { param( [Int][ValidatePattern("[1-9][0-9][0-9][0-9]")]$year, [String][validateset('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')]$dayofweek ) $date = (Get-Date -Year $year -Month 1 -Day 1) while($date.DayOfWeek -ne $dayofweek) {$date = $date....
Give a code snippet in #PowerShell 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/Secure_temporary_file
Secure temporary file
Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" criteria). The function shou...
#Nim
Nim
import std/[os, tempfiles]   let (file, path) = createTempFile(prefix = "", suffix = "") echo path, " created." file.writeLine("This is a secure temporary file.") file.close() for line in path.lines: echo line removeFile(path)
Give a code snippet in #Nim Task Create a temporary file, securely and exclusively (opening it such that there are no possible race conditions). It's fine assuming local filesystem semantics (NFS or other networking filesystems can have signficantly more complicated semantics for satisfying the "no race conditions" ...
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#ERRE
ERRE
  PROGRAM RETURN_VALUES   PROCEDURE SUM_DIFF(A,B->C,D) C=A+B D=A-B END PROCEDURE   BEGIN SUM_DIFF(5,3->SUM,DIFF) PRINT("Sum is";SUM) PRINT("Difference is";DIFF) END PROGRAM  
Give a code snippet in #ERRE Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Ruby
Ruby
given = %w{ ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB }   all = given[0].chars.permutation.collect(&:join)   puts "missing: #{all - given}"
Give a code snippet in #Ruby ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB ...
christopher/rosetta-code
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an ob...
#Swift
Swift
let maybeInt: Int? = nil
Give a code snippet in #Swift Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your langu...
christopher/rosetta-code
http://rosettacode.org/wiki/Same_fringe
Same fringe
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is allowed here, but many compu...
#Go
Go
package main   import "fmt"   type node struct { int left, right *node }   // function returns a channel that yields the leaves of the tree. // the channel is closed after all leaves are received. func leaves(t *node) chan int { ch := make(chan int) // recursive function to walk tree. var f func(*no...
Give a code snippet in #Go Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#J
J
multiply=: *
Give a code snippet in #J A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I befo...
#Zig
Zig
const std = @import("std");   pub fn main() !void { // left hand side type can be ommitted const fruit: [2][]const u8 = [_][]const u8{ "apples", "oranges" }; const stdout_wr = std.io.getStdOut().writer(); // slices and arrays have an len field try stdout_wr.print("fruit.len = {d}\n", .{fruit.len}); ...
Give a code snippet in #Zig Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequen...
christopher/rosetta-code
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#AppleScript
AppleScript
set fiveWeekendMonths to {} set noFiveWeekendYears to {}   set someDate to current date set day of someDate to 1   repeat with someYear from 1900 to 2100 set year of someDate to someYear set foundOne to false repeat with someMonth in {January, March, May, July, ¬ August, October, Decem...
Give a code snippet in #AppleScript The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Gambas
Gambas
Public Sub Main() Dim siCount As Short Dim siCounti As Short = 1 Dim siCountj As Short = 2 Dim siToSort As Short[] = [249, 28, 111, 36, 171, 98, 29, 448, 44, 147, 154, 46, 102, 183, 24]   Print "To sort: - "; GoSub Display   While siCounti < siToSort.Count If siToSort[siCounti - 1] <= siToSort[siCounti] Then siCo...
Give a code snippet in #Gambas 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/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed positi...
#Tcl
Tcl
oo::class create RandomGenerator { superclass ElementaryAutomaton variable s constructor {stateLength} { next 30 set s [split 1[string repeat 0 $stateLength] ""] }   method rand {} { set bits {} while {[llength $bits] < 8} { lappend bits [lindex $s 0] set s [my evolve $s] } return [s...
Give a code snippet in #Tcl Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting succ...
christopher/rosetta-code
http://rosettacode.org/wiki/Chaocipher
Chaocipher
Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. ...
#Kotlin
Kotlin
// Version 1.2.40   enum class Mode { ENCRYPT, DECRYPT }   object Chao { private val lAlphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" private val rAlphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC"   fun exec(text: String, mode: Mode, showSteps: Boolean = false): String { var left = lAlphabet var right = rAlp...
Give a code snippet in #Kotlin Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and ther...
christopher/rosetta-code
http://rosettacode.org/wiki/Mian-Chowla_sequence
Mian-Chowla sequence
The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ai + aj is distinct, fo...
#Kotlin
Kotlin
// Version 1.3.21   fun mianChowla(n: Int): List<Int> { val mc = MutableList(n) { 0 } mc[0] = 1 val hs = HashSet<Int>(n * (n + 1) / 2) hs.add(2) val hsx = mutableListOf<Int>() for (i in 1 until n) { hsx.clear() var j = mc[i - 1] outer@ while (true) { j++ ...
Give a code snippet in #Kotlin The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwi...
christopher/rosetta-code
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#C.2B.2B
C++
  #include <windows.h> #include <string> #include <complex>   const int BMP_SIZE = 600, ITERATIONS = 512; const long double FCT = 2.85, hFCT = FCT / 2.0;   class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); ...
Give a code snippet in #C.2B.2B Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Phixmonti
Phixmonti
1 2 5 -5 -9.5 3.14159 stklen tolist len swap sum swap / print
Give a code snippet in #Phixmonti Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an ...
christopher/rosetta-code
http://rosettacode.org/wiki/Diversity_prediction_theorem
Diversity prediction theorem
The   wisdom of the crowd   is the collective opinion of a group of individuals rather than that of a single expert. Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise,   an explanation that assumes independence of the i...
#Haskell
Haskell
mean :: (Fractional a, Foldable t) => t a -> a mean lst = sum lst / fromIntegral (length lst)   meanSq :: Fractional c => c -> [c] -> c meanSq x = mean . map (\y -> (x-y)^^2)   diversityPrediction x estimates = do putStrLn $ "TrueValue:\t" ++ show x putStrLn $ "CrowdEstimates:\t" ++ show estimates let avg = me...
Give a code snippet in #Haskell The   wisdom of the crowd   is the collective opinion of a group of individuals rather than that of a single expert. Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise,   an explanation t...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_squares_of_doubly_even_order
Magic squares of doubly even order
A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a size that is a multiple of four   (e...
#FreeBASIC
FreeBASIC
' version 18-03-2016 ' compile with: fbc -s console ' doubly even magic square 4, 8, 12, 16...   Sub Err_msg(msg As String) Print msg Beep : Sleep 5000, 1 : Exit Sub End Sub   Sub de_magicsq(n As UInteger, filename As String = "")   ' filename <> "" then save square in a file ' filename can contain dire...
Give a code snippet in #FreeBASIC A magic square is an   N×N  square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column,   and   both diagonals are equal to the same sum   (which is called the magic number or magic constant). A magic square of doubly even order has a s...
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#AutoHotkey
AutoHotkey
addsub(x, y) { return [x + y, x - y] }
Give a code snippet in #AutoHotkey Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#Quackery
Quackery
[ say "SPAM" cr again ]
Give a code snippet in #Quackery Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   L...
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. ...
#zkl
zkl
File.glob("*.zkl") //--> list of matches
Give a code snippet in #zkl Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, no...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#ALGOL_68
ALGOL 68
PRIO MINLWB = 8, MAXUPB = 8; OP MINLWB = ([]INT a,b)INT: (LWB a<LWB b|LWB a|LWB b), MAXUPB = ([]INT a,b)INT: (UPB a>UPB b|UPB a|UPB b);   OP + = ([]INT a,b)[]INT:( [a MINLWB b:a MAXUPB b]INT out; FOR i FROM LWB out TO UPB out DO out[i]:= 0 OD; out[LWB a:UPB a] := a; FOR i FROM LWB b TO UPB b DO out[i]+:= b[i] OD...
Give a code snippet in #ALGOL_68 Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is eit...
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use
Text processing/Max licenses in use
A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a checkout event when a copy of the ...
#PicoLisp
PicoLisp
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l   (zero Count MaxCount)   (in (opt) (while (split (line) " ") (case (pack (cadr (setq Line @))) (IN (dec 'Count) ) (OUT (let Time (cadddr Line) (cond ((> (inc 'Count) MaxCount) ...
Give a code snippet in #PicoLisp A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a met...
#Lua
Lua
local function isprime(n) if n < 2 then return false end if n % 2 == 0 then return n==2 end if n % 3 == 0 then return n==3 end local f, limit = 5, math.sqrt(n) while (f <= limit) do if n % f == 0 then return false end; f=f+2 if n % f == 0 then return false end; f=f+4 end return true end   local fu...
Give a code snippet in #Lua A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investi...
christopher/rosetta-code
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#Tcl
Tcl
package require struct::prioqueue   set pq [struct::prioqueue] foreach {priority task} { 3 "Clear drains" 4 "Feed cat" 5 "Make tea" 1 "Solve RC tasks" 2 "Tax return" } { # Insert into the priority queue $pq put $task $priority } # Drain the queue, in priority-sorted order while {[$pq size]} ...
Give a code snippet in #Tcl A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priori...
christopher/rosetta-code
http://rosettacode.org/wiki/2048
2048
Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some move more than others.   Two ...
#BASIC
BASIC
  SCREEN 13 PALETTE 1, pColor(35, 33, 31) PALETTE 2, pColor(46, 46, 51) PALETTE 3, pColor(59, 56, 50) PALETTE 4, pColor(61, 44, 30) PALETTE 5, pColor(61, 37, 25) PALETTE 6, pColor(62, 31, 24) PALETTE 7, pColor(62, 24, 15) PALETTE 8, pColor(59, 52, 29) PALETTE 9, pColor(59, 51, 24) PALETTE 10, pColor(59, 50, 20) PALETTE...
Give a code snippet in #BASIC Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some ...
christopher/rosetta-code
http://rosettacode.org/wiki/I_before_E_except_after_C
I before E except after C
The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually:   "I before E when not pre...
#Tcl
Tcl
package require http   variable PLAUSIBILITY_RATIO 2.0 proc plausible {description x y} { variable PLAUSIBILITY_RATIO puts " Checking plausibility of: $description" if {$x > $PLAUSIBILITY_RATIO * $y} { set conclusion "PLAUSIBLE" set fmt "As we have counts of %i vs %i words, a ratio of %.1f times" set re...
Give a code snippet in #Tcl The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually:...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Nim
Nim
stdout.write "Goodbye, World!"
Give a code snippet in #Nim Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standar...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#NewLISP
NewLISP
; median.lsp ; oofoe 2012-01-25   (define (median lst) (sort lst) ; Sorts in place. (if (empty? lst) nil (letn ((n (length lst)) (h (/ (- n 1) 2))) (if (zero? (mod n 2)) (div (add (lst h) (lst (+ h 1))) 2) (lst h)) )))     (define (test lst) (printl...
Give a code snippet in #NewLISP Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle value...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#PureBasic
PureBasic
Procedure.s Generate(N) For i=1 To N sample$+"[]" Next For i=Len(sample$)-1 To 2 Step -1 r=Random(i-1)+1 If r<>i a.c=PeekC(@sample$+r*SizeOf(Character)) b.c=PeekC(@sample$+i*SizeOf(Character)) PokeC(@sample$+r*SizeOf(Character), b) PokeC(@sample$+i*SizeOf(Character), a) En...
Give a code snippet in #PureBasic Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which m...
christopher/rosetta-code
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#smart_BASIC
smart BASIC
/*Boxing The Compass by rbytes December 2017*/ GET SCREEN SIZE sw,sh OPTION BASE 1 DIM point$(32,5) FOR i=1 TO 32 FOR j=1 TO 5 READ point$(i,j) NEXT j NEXT i html$= "<table border=1>" html$&= "<TR><TD align=right></td><td>Boxing The Compass</td><td>Abbr</td><td>Min</td><td>Med</td><td>Max</td></tr>" FOR i =1 TO 32 h...
Give a code snippet in #smart_BASIC There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print ...
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 ...
#Delphi
Delphi
program TestShakerSort;   {$APPTYPE CONSOLE}   {.$DEFINE DYNARRAY} // remove '.' to compile with dynamic array   type TItem = Integer; // declare ordinal type for array item {$IFDEF DYNARRAY} TArray = array of TItem; // dynamic array {$ELSE} TArray = array[0..15] of TItem; // static array {$ENDIF}  ...
Give a code snippet in #Delphi 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/Singleton
Singleton
A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
#Eiffel
Eiffel
class SINGLETON create {SINGLETON_ACCESS} default_create feature -- singleton features go here end
Give a code snippet in #Eiffel A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort
Sorting algorithms/Shell 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 ...
#ooRexx
ooRexx
/* Rexx */ -- --- Main -------------------------------------------------------------------- call demo return exit   -- ----------------------------------------------------------------------------- -- Shell sort implementation -- ----------------------------------------------------------------------------- ::routine sh...
Give a code snippet in #ooRexx 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/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#Simula
Simula
BEGIN       CLASS EXPR; BEGIN     REAL PROCEDURE POP; BEGIN IF STACKPOS > 0 THEN BEGIN STACKPOS := STACKPOS - 1; POP := STACK(STACKPOS); END; END POP;     PROCEDURE PUSH(NEWTOP); REAL NEWTOP; BEGIN STACK(STACKPOS) := NEWTOP; ...
Give a code snippet in #Simula task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Traversal
Singly-linked list/Traversal
Traverse from the beginning of a singly-linked list to the end. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked ...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program afficheList.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 Traverse from the beginning of a singly-linked list to the end. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: ...
christopher/rosetta-code
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#C.23
C#
  public partial class Form1 : Form { public Form1() { InitializeComponent(); Paint += Form1_Paint; }   private void Form1_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; g.SmoothingMode = System.Drawing.Dr...
Give a code snippet in #C.23 One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
christopher/rosetta-code
http://rosettacode.org/wiki/Interactive_programming_(repl)
Interactive programming (repl)
Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. Task Show how to start this...
#Logo
Logo
$ <i>logo</i> Welcome to Berkeley Logo version 5.6 ? <i>to f :prefix :suffix :separator</i> > <i>output (word :prefix :separator :separator :suffix)</i> > <i>end</i> f defined ? <i>show f "Rosetta "Code ":</i> Rosetta::Code ?
Give a code snippet in #Logo Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#PureBasic
PureBasic
If OpenConsole() Define argc=CountProgramParameters() If argc>=(SizeOf(Integer)*8) Or argc<1 PrintN("Set out of range.") End 1 Else Define i, j, text$ Define.q bset=1<<argc Print("{") For i=0 To bset-1 ; check all binary combinations If Not i: text$= "{" Else  : text$=", {...
Give a code snippet in #PureBasic A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. G...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/RPN_to_infix_conversion
Parsing/RPN to infix conversion
Parsing/RPN to infix conversion You are encouraged to solve this task according to the task description, using any language you may know. Task Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates the equivalent expression in infix notation....
#M2000_Interpreter
M2000 Interpreter
  Module Rpn_2_Infix { Rem Form 80,60 function rpn_to_infix$(a$) { def m=0 inventory precendence="-":=2,"+":=2,"*":=3,"/":=3,"^":=4 dim token$() token$()=piece$(a$," ") l=len(token$()) dim type(l)=0, right(l)=0, infix$(l) infix=-1 for i=0 to l-1 if exist(precendence, token$(i)) then type(i)=...
Give a code snippet in #M2000_Interpreter Parsing/RPN to infix conversion You are encouraged to solve this task according to the task description, using any language you may know. Task Create a program that takes an RPN representation of an expression formatted as a space separated sequence of tokens and generates t...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle
Pascal's triangle/Puzzle
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Pyramid_of_Numbers is   B_X, B_Y, B_Z : Integer := 0; -- Unknown variables   type Block_Value is record Known  : Integer := 0; X, Y, Z : Integer := 0; end record; X : constant Block_Value := (0, 1, 0, 0); Y : constant Block_Value := (0, 0, 1, 0)...
Give a code snippet in #Ada This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at...
christopher/rosetta-code
http://rosettacode.org/wiki/Show_the_epoch
Show the epoch
Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the scenes by the implementers),   b...
#Clojure
Clojure
(println (java.util.Date. 0))
Give a code snippet in #Clojure Task Choose popular date libraries used by your language and show the   epoch   those libraries use. A demonstration is preferable   (e.g. setting the internal representation of the date to 0 ms/ns/etc.,   or another way that will still show the epoch even if it is changed behind the...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#J
J
perms=: A.&i.~ !
Give a code snippet in #J Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generati...
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.
#Raku
Raku
class Pixel { has UInt ($.R, $.G, $.B) } class Bitmap { has UInt ($.width, $.height); has Pixel @!data;   method fill(Pixel $p) { @!data = $p.clone xx ($!width*$!height) } method pixel( $i where ^$!width, $j where ^$!height --> Pixel ) is rw { @!data[$i + $j * $!width] }   method ...
Give a code snippet in #Raku 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/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ...
#Clojure
Clojure
  (def neg-inf (/ -1.0 0.0)) ; Also Double/NEGATIVE_INFINITY (def inf (/ 1.0 0.0)) ; Also Double/POSITIVE_INFINITY (def nan (/ 0.0 0.0)) ; Also Double/NaN (def neg-zero (/ -2.0 Double/POSITIVE_INFINITY)) ; Also -0.0 (println " Negative inf: " neg-inf) (println " Positive inf: " inf) (println " N...
Give a code snippet in #Clojure The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your languag...
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 ...
#M4
M4
divert(-1) define(`set',`define(`$1[$2]',`$3')') define(`get',`defn(`$1[$2]')') define(`setrange',`ifelse(`$3',`',$2,`define($1[$2],$3)`'setrange($1, incr($2),shift(shift(shift($@))))')') define(`for', `ifelse($#,0,``$0'', `ifelse(eval($2<=$3),1, `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')'...
Give a code snippet in #M4 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 ...
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 ...
#Scala
Scala
object Levenshtein0 extends App {   def distance(s1: String, s2: String): Int = { val dist = Array.tabulate(s2.length + 1, s1.length + 1) { (j, i) => if (j == 0) i else if (i == 0) j else 0 }   @inline def minimum(i: Int*): Int = i.min   for {j <- dist.indices.tail i <- dist(0).indices.tail} ...
Give a code snippet in #Scala 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 com...
christopher/rosetta-code
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#Scala
Scala
myLabel -> ... :myLabel
Give a code snippet in #Scala Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom t...
christopher/rosetta-code
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> char *split(char *str); int main(int argc,char **argv) { char input[13]="gHHH5YY++///\\"; printf("%s\n",split(input)); } char *split(char *str) { char last=*str,*result=malloc(3*strlen(str)),*counter=result; for (char *c=str;*c;c++) { if (*c!=last) { s...
Give a code snippet in #C Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The sa...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTPS/Authenticated
HTTPS/Authenticated
The goal of this task is to demonstrate HTTPS requests with authentication. Implementations of this task should not use client certificates for this: that is the subject of another task.
#Tcl
Tcl
package require http package require tls http::register https 443 ::tls::socket   # Generate the authentication set user theUser set pass thePassword dict set auth Authenticate "Basic [binary encode base64 ${user}:${pass}]"   # Make a secure authenticated connection set token [http::geturl https://secure.example.com/ -...
Give a code snippet in #Tcl The goal of this task is to demonstrate HTTPS requests with authentication. Implementations of this task should not use client certificates for this: that is the subject of another task.
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#Erlang
Erlang
is_prime(N) when N == 2 -> true; is_prime(N) when N < 2 orelse N rem 2 == 0 -> false; is_prime(N) -> is_prime(N,3).   is_prime(N,K) when K*K > N -> true; is_prime(N,K) when N rem K == 0 -> false; is_prime(N,K) -> is_prime(N,K+2).
Give a code snippet in #Erlang Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loop...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_object_at_a_given_address
Create an object at a given address
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Action.21
Action!
DEFINE FIRST="12345" DEFINE SECOND="54321" DEFINE PTR="CARD"   PROC Main() PTR base,copy=base   PrintF("Address of base variable: %H%E",@base) PrintF("Address of copy variable: %H%E",@copy) PutE()   PrintF("Assign %U value to base variable%E",FIRST) base=FIRST PrintF("Value of base variable: %U%E",base) ...
Give a code snippet in #Action.21 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 Operati...
christopher/rosetta-code
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language...
#R
R
dog <- 'Benjamin' Dog <- 'Samba' DOG <- 'Bernie'   # Having fun with cats and dogs cat('The three dogs are named ') cat(dog) cat(', ') cat(Dog) cat(' and ') cat(DOG) cat('.\n') # In one line it would be: # cat('The three dogs are named ', dog, ', ', Dog, ' and ', DOG, '.\n', sep = '')
Give a code snippet in #R Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba ...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#COBOL
COBOL
CALL "No-Arguments"   *> Fixed number of arguments. CALL "2-Arguments" USING Foo Bar   CALL "Optional-Arguments" USING Foo CALL "Optional-Arguments" USING Foo Bar *> If an optional argument is omitted and replaced with OMITTED, any following *> arguments can still be specified. CALL "Optional-Arguments" USING Foo OMITT...
Give a code snippet in #COBOL Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a va...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Clojure
Clojure
(defn towers-of-hanoi [n from to via] (when (pos? n) (towers-of-hanoi (dec n) from via to) (printf "Move from %s to %s\n" from to) (recur (dec n) via to from)))
Give a code snippet in #Clojure Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#Ada
Ada
generic type Float_Type is digits <>; Gravitation : Float_Type; package Pendulums is type Pendulum is private; function New_Pendulum (Length : Float_Type; Theta0 : Float_Type) return Pendulum; function Get_X (From : Pendulum) return Float_Type; function Get_Y (From : Pendulum...
Give a code snippet in #Ada One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and ani...
christopher/rosetta-code