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/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 ...
#Julia
Julia
largest = 0   function iscolorful(n, base=10) 0 <= n < 10 && return true dig = digits(n, base=base) (1 in dig || 0 in dig || !allunique(dig)) && return false products = Set(dig) for i in 2:length(dig), j in 1:length(dig)-i+1 p = prod(dig[j:j+i-1]) p in products && return false ...
Give a code snippet in #Julia 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 Ev...
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Wren
Wren
import "/fmt" for Fmt   var n = 7.125 System.print(Fmt.rjust(9, n, "0"))
Give a code snippet in #Wren Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/Abelian_sandpile_model/Identity
Abelian sandpile model/Identity
Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that contain a number from 0 to 3 inclusive. (The numbers are said to represent grains of sand in each area of the sandpile). E.g. s1 = 1 2 0 2 1 1 0 1 3 and s2 = 2 1 3 1 0 1 0 1 0 Addition on sandpiles is done by a...
#11l
11l
T Sandpile DefaultDict[(Int, Int), Int] grid   F (gridtext) V array = gridtext.split_py().map(x -> Int(x)) L(x) array .grid[(L.index I/ 3, L.index % 3)] = x   Set[(Int, Int)] _border = Set(cart_product(-1 .< 4, -1 .< 4).filter((r, c) -> !(r C 0..2) | !(c C 0..2))) _cell_coords = cart_pr...
Give a code snippet in #11l Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that contain a number from 0 to 3 inclusive. (The numbers are said to represent grains of sand in each area of the sandpile). E.g. s1 = 1 2 0 2 1 1 0 1 3 and s2 = 2 1 3 1 0 1 0 1 0 Addit...
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
#Swahili
Swahili
andika("Hello world!")
Give a code snippet in #Swahili 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/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#Gambas
Gambas
'Note that the 1st item in 'Args' is the file name as on the command line './CLIOnly.gambas'   Public Sub Main() Dim sContents As String 'To store the file contents Dim sArgs As String[] = Args.All 'To store all the Command l...
Give a code snippet in #Gambas Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TX...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task...
#Java
Java
import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Objects;   public class RandomLatinSquares { private static void printSquare(List<List<Integer>> latin) { for (List<Integer> row : latin) { Iterator<Integer> it = row.iter...
Give a code snippet in #Java A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#PL.2FI
PL/I
tok: Proc Options(main); declare s character (100) initial ('Hello,How,Are,You,Today'); declare n fixed binary (31);   n = tally(s, ',')+1;   begin; declare table(n) character (50) varying; declare c character (1); declare (i, k) fixed binary (31);   table = ''; k = 1; do i = 1 to length(s); c = su...
Give a code snippet in #PL.2FI Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks r...
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
#K
K
  "Hello world!"  
Give a code snippet in #K 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   He...
christopher/rosetta-code
http://rosettacode.org/wiki/Truth_table
Truth table
A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function. Task Input a Boolean function from the user as a string then calculate and print a formatted truth table for the g...
#Java
Java
import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack;   public class TruthTable { public static void main( final String... args ) { System.out.println( new Tr...
Give a code snippet in #Java A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function. Task Input a Boolean function from the user as a string then calculate and print a f...
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
#RPG
RPG
// fully qualified syntax: /include library/file,member   // most sensible; file found on *libl: /include file,member   // shortest one, the same library and file: /include member   // and alternative: /copy library/file,member   //... farther like "include"
Give a code snippet in #RPG 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/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...
#R
R
checkPangram <- function(sentence){ my.letters <- tolower(unlist(strsplit(sentence, ""))) is.pangram <- all(letters %in% my.letters)   if (is.pangram){ cat("\"", sentence, "\" is a pangram! \n", sep="") } else { cat("\"", sentence, "\" is not a pangram! \n", sep="") } }  
Give a code snippet in #R 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#M2000_Interpreter
M2000 Interpreter
  module Archimedean_spiral { smooth on ' enable GDI+ def r(θ)=5+3*θ cls #002222,0 pen #FFFF00 refresh 5000 every 1000 { \\ redifine window (console width and height) and place it to center (symbol ;) Window 12, random(10, 18)*1000, random(8, 12)*1000; move scale.x/2, scale.y/2 let N=2, k1=pi/120, k=k1, o...
Give a code snippet in #M2000_Interpreter The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#Kotlin
Kotlin
// version 1.1.2   var total = 0L var prim = 0L var maxPeri = 0L   fun newTri(s0: Long, s1: Long, s2: Long) { val p = s0 + s1 + s2 if (p <= maxPeri) { prim++ total += maxPeri / p newTri( s0 - 2 * s1 + 2 * s2, 2 * s0 - s1 + 2 * s2, 2 * s0 - 2 * s1 + 3 * s2) newTri( s0 + 2 * s1 +...
Give a code snippet in #Kotlin A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\dis...
christopher/rosetta-code
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#Icon_and_Unicon
Icon and Unicon
procedure main() every write(left(i := !10/10.0,5),gamma(.i)) end   procedure gamma(z) # Stirling's approximation return (2*&pi/z)^0.5 * (z/&e)^z end
Give a code snippet in #Icon_and_Unicon Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the bu...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#EGL
EGL
  function fact(n int in) returns (bigint) if (n < 0) writestdout("No negative numbers"); return (0); end ans bigint = 1; for (i int from 1 to n) ans *= i; end return (ans); end  
Give a code snippet in #EGL Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a num...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#11l
11l
F insertion_sort(&l) L(i) 1 .< l.len V j = i - 1 V key = l[i] L j >= 0 & l[j] > key l[j + 1] = l[j] j-- l[j + 1] = key   V arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0] insertion_sort(&arr) print(arr)
Give a code snippet in #11l Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort...
christopher/rosetta-code
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#Ruby
Ruby
require 'set'   a = [0] used = Set[0] used1000 = Set[0] foundDup = false n = 1 while n <= 15 or not foundDup or used1000.size < 1001 nxt = a[n - 1] - n if nxt < 1 or used === nxt then nxt = nxt + 2 * n end alreadyUsed = used === nxt a << nxt if not alreadyUsed then used << nxt ...
Give a code snippet in #Ruby The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Tas...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity
Rosetta Code/Rank languages by popularity
Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 2022 at 14:13 +02 Rank: 1 (1,...
#F.23
F#
open System open System.Text.RegularExpressions   [<EntryPoint>] let main argv = let rosettacodeSpecialCategoriesAddress = "http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000" let rosettacodeProgrammingLaguagesAddress = "http://rosettacode.org/wiki/Category:Programming_L...
Give a code snippet in #F.23 Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 2...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Elena
Elena
import system'routines; import extensions; import extensions'text;   extension extension { reversedLiteral() = self.toArray().sequenceReverse().summarize(new StringWriter()); }   public program() { console.printLine("Hello World".reversedLiteral()) }
Give a code snippet in #Elena Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty...
christopher/rosetta-code
http://rosettacode.org/wiki/Imaginary_base_numbers
Imaginary base numbers
Imaginary base numbers are a non-standard positional numeral system which uses an imaginary number as its radix. The most common is quater-imaginary with radix 2i. The quater-imaginary numeral system was first proposed by Donald Knuth in 1955 as a submission for a high school science talent search. [Ref.] Other imagi...
#Python
Python
import math import re   def inv(c): denom = c.real * c.real + c.imag * c.imag return complex(c.real / denom, -c.imag / denom)   class QuaterImaginary: twoI = complex(0, 2) invTwoI = inv(twoI)   def __init__(self, str): if not re.match("^[0123.]+$", str) or str.count('.') > 1: rai...
Give a code snippet in #Python Imaginary base numbers are a non-standard positional numeral system which uses an imaginary number as its radix. The most common is quater-imaginary with radix 2i. The quater-imaginary numeral system was first proposed by Donald Knuth in 1955 as a submission for a high school science ta...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Swift
Swift
let text = "Hello,How,Are,You,Today" let tokens = text.components(separatedBy: ",") // for single or multi-character separator print(tokens) let result = tokens.joined(separator: ".") print(result)
Give a code snippet in #Swift Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks re...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Metafont
Metafont
show max(4,5,20,1); show max((12,3), (10,10), (25,5)); show max("hello", "world", "Hello World");
Give a code snippet in #Metafont Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Special_characters
Special characters
Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal charact...
#PicoLisp
PicoLisp
Markup: () [] List . Dotted pair (when surounded by white space) " Transient symbol (string) {} External symbol (database object) \ Escape for following character # Comment line #{ }# Comment block Read macros: ' The 'quote' function ` E...
Give a code snippet in #PicoLisp Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers. Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Tcl
Tcl
split $string ","
Give a code snippet in #Tcl Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks rela...
christopher/rosetta-code
http://rosettacode.org/wiki/Break_OO_privacy
Break OO privacy
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is...
#ABAP
ABAP
class friendly_class definition deferred.   class my_class definition friends friendly_class .   public section. methods constructor.   private section. data secret type char30.   endclass.   class my_class implementation .   method constructor. secret = 'a password'. " Instantiate secret. endmethod...
Give a code snippet in #ABAP Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool mi...
christopher/rosetta-code
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#PL.2FI
PL/I
sternBrocot: procedure options(main);  %replace MAX by 1200; declare S(1:MAX) fixed;   /* find the first occurrence of N in S */ findFirst: procedure(n) returns(fixed); declare (n, i) fixed; do i=1 to MAX; if S(i)=n then return(i); end; end findFirst;   /* find...
Give a code snippet in #PL.2FI For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered memb...
christopher/rosetta-code
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously
Loop over multiple arrays simultaneously
Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example, loop over the arrays: ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
MapThread[Print, {{"a", "b", "c"}, {"A", "B", "C"}, {1, 2, 3}}];
Give a code snippet in #Mathematica.2FWolfram_Language Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some oth...
christopher/rosetta-code
http://rosettacode.org/wiki/Seven-sided_dice_from_five-sided_dice
Seven-sided dice from five-sided dice
Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using the function created in   Simple R...
#ALGOL_68
ALGOL 68
PROC dice5 = INT: 1 + ENTIER (5*random);   PROC mulby5 = (INT n)INT: ABS (BIN n SHL 2) + n;   PROC dice7 = INT: ( INT d55 := 0; INT m := 1; WHILE m := ABS ((2r1 AND BIN m) SHL 2) + ABS (BIN m SHR 1); # repeats 4 - 2 - 1 # d55 := mulby5(mulby5(d55)) + mulby5(dice5) + dice5 - 6; # WHILE # d55 < m DO S...
Give a code snippet in #ALGOL_68 Task (Given an equal-probability generator of one of the integers 1 to 5 as dice5),   create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers,   and check the distribution for at least one million calls using ...
christopher/rosetta-code
http://rosettacode.org/wiki/Start_from_a_main_routine
Start from a main routine
Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may also require similar tricker...
#sed
sed
# This code runs only for line 1. 1 { i\ Explain-a-lot processed this file and i\ replaced every period with three exclamation points!!! i\   }   # This code runs for each line of input. s/\./!!!/g
Give a code snippet in #sed Some languages (like Gambas and Visual Basic) support two startup modes.   Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead.   Data driven or event driven languages may...
christopher/rosetta-code
http://rosettacode.org/wiki/Cistercian_numerals
Cistercian numerals
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyp...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[CistercianNumberEncodeHelper, CistercianNumberEncode] \[Delta] = 0.25; CistercianNumberEncodeHelper[0] := {} CistercianNumberEncodeHelper[1] := Line[{{0, 1}, {\[Delta], 1}}] CistercianNumberEncodeHelper[2] := Line[{{0, 1 - \[Delta]}, {\[Delta], 1 - \[Delta]}}] CistercianNumberEncodeHelper[3] := Line[{{0, 1}, {...
Give a code snippet in #Mathematica.2FWolfram_Language Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segm...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Stata
Stata
function repeat(f,n) { for (i=1; i<=n; i++) (*f)() }   function hello() { printf("Hello\n") }   repeat(&hello(),3)
Give a code snippet in #Stata Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
christopher/rosetta-code
http://rosettacode.org/wiki/Lah_numbers
Lah numbers
Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-empty linearly ordered subsets. Lah numbers a...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Numerics   Module Module1   Function Factorial(n As BigInteger) As BigInteger If n = 0 Then Return 1 End If   Dim res As BigInteger = 1 While n > 0 res *= n n -= 1 End While Return res End Function   Function ...
Give a code snippet in #Visual_Basic_.NET Lah numbers, sometimes referred to as Stirling numbers of the third kind, are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials. Unsigned Lah numbers count the number of ways a set of n elements can be partitioned into k non-emp...
christopher/rosetta-code
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Console Imports BI = System.Numerics.BigInteger   Module Module1   Dim Implems() As String = {"Built-In", "Recursive", "Iterative"}, powers() As Integer = {5, 4, 3, 2}   Function intPowR(val As BI, exp As BI) As BI If exp = 0 Then Return 1 Dim ne As BI, vs As BI = val * v...
Give a code snippet in #Visual_Basic_.NET Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#Lang5
Lang5
0 do dup . 1 + loop
Give a code snippet in #Lang5 Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations li...
christopher/rosetta-code
http://rosettacode.org/wiki/Chat_server
Chat server
Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
#Julia
Julia
  using HttpServer using WebSockets   const connections = Dict{Int,WebSocket}() const usernames = Dict{Int,String}()   function decodeMessage( msg ) String(copy(msg)) end     wsh = WebSocketHandler() do req, client global connections @show connections[client.id] = client println("req is $req") not...
Give a code snippet in #Julia Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages. ...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="heal...
#Bracmat
Bracmat
{Retrieve the first "item" element} ( nestML$(get$("doc.xml",X,ML))  :  ? ( inventory . ?,? (section.?,? ((item.?):?item) ?) ? )  ? & out$(toML$!item) )   {Perform an action on each "price" element (print it out)} ( nestML$(get$("doc.xml",X,ML))  :  ? ( inventory .  ? ...
Give a code snippet in #Bracmat Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#8051_Assembly
8051 Assembly
; constant array (elements are unchangeable) - the array is stored in the CODE segment myarray db 'Array' ; db = define bytes - initializes 5 bytes with values 41, 72, 72, etc. (the ascii characters A,r,r,a,y) myarray2 dw 'A','r','r','a','y' ; dw = define words - initializes 5 words (1 word = 2 bytes) with values 41 00...
Give a code snippet in #8051_Assembly This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, a...
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
#Euphoria
Euphoria
-- In Euphoria puts() does not insert a newline character after outputting a string puts(1,"Goodbye, world!")
Give a code snippet in #Euphoria 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/St...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters
Determine if a string has all unique characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length   (as the strings are being ...
#D
D
import std.stdio;   void uniqueCharacters(string str) { writefln("input: `%s`, length: %d", str, str.length); foreach (i; 0 .. str.length) { foreach (j; i + 1 .. str.length) { if (str[i] == str[j]) { writeln("String contains a repeated character."); writefln("...
Give a code snippet in #D Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#Python
Python
with open(filename, 'w') as f: f.write(data)
Give a code snippet in #Python Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#R
R
cat("\33[2J")
Give a code snippet in #R Task Clear the terminal window.
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
#Lisaac
Lisaac
Section Header // The Header section is required. + name := GOODBYE; // Define the name of this object.   Section Public - main <- ("Hello world!\n".print;);
Give a code snippet in #Lisaac 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/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Fortran
Fortran
module multiple_values implicit none type res integer :: p, m end type   contains   function addsub(x,y) result(r) integer :: x, y type(res) :: r r%p = x+y r%m = x-y end function end module   program main use multiple_values print *, addsub(33, 22) end program  
Give a code snippet in #Fortran Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of S...
#Factor
Factor
IN: scratchpad [ 0 1 1 "%2d : %d / %d\n" printf 1 -1 2 "%2d : %d / %d\n" printf 30 iota [ 1 + 2 * dup bernoulli [ numerator ] [ denominator ] bi "%2d : %d / %d\n" printf ] each ] time 0 : 1 / 1 1 : -1 / 2 2 : 1 / 6 4 : -1 / 30 6 : 1 / 42 8 : -1 / 30 10 : 5 / 66 12 ...
Give a code snippet in #Factor Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as p...
christopher/rosetta-code
http://rosettacode.org/wiki/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#BaCon
BaCon
OPTION PARSE FALSE   PRAGMA INCLUDE <curl/curl.h> PRAGMA LDFLAGS -lcurl   DECLARE easyhandle TYPE CURL*   OPEN "data.txt" FOR WRITING AS download   easyhandle = curl_easy_init() curl_easy_setopt(easyhandle, CURLOPT_URL, "ftp://localhost/pub/data.txt") curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, download) curl_easy_...
Give a code snippet in #BaCon Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
christopher/rosetta-code
http://rosettacode.org/wiki/Count_occurrences_of_a_substring
Count occurrences of a substring
Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It should return an integer cou...
#Eiffel
Eiffel
  class APPLICATION inherit ARGUMENTS create make feature {NONE} -- Initialization make -- Run application. do occurance := 0 from index := 1 until index > text.count loop temp := text.fuzzy_index(search_for, index, 0) if temp /= 0 then index := temp + search_for.count...
Give a code snippet in #Eiffel Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
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 ...
#Oz
Oz
declare fun {LexicographicLessThan Xs Ys} for X in {Map Xs Char.toLower} Y in {Map Ys Char.toLower} return:Return default:{Length Xs}<{Length Ys} do if X < Y then {Return true} end end end   fun {LessThan Xs Ys} {Length Xs} > {Length Ys} orelse ...
Give a code snippet in #Oz Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort ...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#8086_Assembly
8086 Assembly
cpu 8086 bits 16 org 100h section .text mov bx,0402h ; Set up first arguments to move() mov cx,0103h ; Registers chosen s.t. CX contains output ;;; Move BH disks from CH via BL to CL move: dec bh ; One fewer disk in next iteration jz .out ; If this was last disk, just print move push bx ; Save the registers ...
Give a code snippet in #8086_Assembly Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#Forth
Forth
8 constant (gamma-shift)   : (mortici) ( f1 -- f2) -1 s>f f+ 1 s>f fover 271828183e-8 f* 12 s>f f* f/ fover 271828183e-8 f/ f+ fover f** fswap 628318530e-8 f* fsqrt f* \ 2*pi ;   : gamma ( f1 -- f2) fdup f0< >r fdup f0= r> or abort" Gamma...
Give a code snippet in #Forth Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/lib...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Pascal
Pascal
"ha" x 5
Give a code snippet in #Pascal Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5)...
christopher/rosetta-code
http://rosettacode.org/wiki/UTF-8_encode_and_decode
UTF-8 encode and decode
As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the...
#Kotlin
Kotlin
// version 1.1.2   fun utf8Encode(codePoint: Int) = String(intArrayOf(codePoint), 0, 1).toByteArray(Charsets.UTF_8)   fun utf8Decode(bytes: ByteArray) = String(bytes, Charsets.UTF_8).codePointAt(0)   fun main(args: Array<String>) { val codePoints = intArrayOf(0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E) println("Ch...
Give a code snippet in #Kotlin As described in UTF-8 and in Wikipedia, UTF-8 is a popular encoding of (multi-byte) Unicode code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes re...
christopher/rosetta-code
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle
4-rings or 4-squares puzzle
4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the four large squares add up to t...
#Ruby
Ruby
def four_squares(low, high, unique=true, show=unique) f = -> (a,b,c,d,e,f,g) {[a+b, b+c+d, d+e+f, f+g].uniq.size == 1} if unique uniq = "unique" solutions = [*low..high].permutation(7).select{|ary| f.call(*ary)} else uniq = "non-unique" solutions = [*low..high].repeated_permutation(7).select{|ary|...
Give a code snippet in #Ruby 4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the ...
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...
#Beads
Beads
beads 1 program 'Generic swap'   var a = [1 2 "Beads" 3 4] b = [1 2 "Language" 4 5]   calc main_init swap a[4] <=> b[3]
Give a code snippet in #Beads 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 genericit...
christopher/rosetta-code
http://rosettacode.org/wiki/Benford%27s_law
Benford's law
This page uses content from Wikipedia. The original article was at Benford's_law. 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) Benford's law, also called the first-digit law, refers to the freque...
#ALGOL_68
ALGOL 68
BEGIN # set the number of digits for LONG LONG INT values # PR precision 256 PR # returns the probability of the first digit of each non-zero number in s # PROC digit probability = ( []LONG LONG INT s )[]REAL: BEGIN [ 1 : 9 ]REAL result; # count the number of times each ...
Give a code snippet in #ALGOL_68 This page uses content from Wikipedia. The original article was at Benford's_law. 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) Benford's law, also called the fir...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Visual_Basic_.NET
Visual Basic .NET
#Const REDIRECTOUT = True   Module Program Const OUTPATH = "out.txt"   ReadOnly TestCases As String() = {"asdf", "as⃝df̅", "Les Misérables"}   ' SIMPLE VERSION Function Reverse(s As String) As String Dim t = s.ToCharArray() Array.Reverse(t) Return New String(t) End Function  ...
Give a code snippet in #Visual_Basic_.NET Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a s...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) t...
#Kotlin
Kotlin
// version 1.0.6   fun f(n: Int, x: Int, y: Int) = (x + y * 2 + 1) % n   fun main(args: Array<String>) { var n: Int while (true) { print("Enter the order of the magic square : ") n = readLine()!!.toInt() if (n < 1 || n % 2 == 0) println("Must be odd and >= 1, try again") else bre...
Give a code snippet in #Kotlin A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The number...
christopher/rosetta-code
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded c...
#Yabasic
Yabasic
sub luhntest(cardnr$) local i, j, s1, s2, l   cardnr$ = Trim$(cardnr$) // remove spaces   l = Len(cardnr$)   // sum odd numbers For i = l To 1 Step -2 s1 = s1 + (asc(mid$(cardnr$, i, 1)) - Asc("0")) Next // sum even numbers For i = l-1 To 1 Step -2 j = asc(mid$(cardnr$, i...
Give a code snippet in #Yabasic An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the corre...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_syntax
Inverted syntax
Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the statement or code block: needumb...
#PicoLisp
PicoLisp
(de rv Prg (append (last Prg) (head -1 Prg)) )
Give a code snippet in #PicoLisp Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Zebra_puzzle
Zebra puzzle
Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five houses.   The English man lives ...
#PicoLisp
PicoLisp
(be match (@House @Person @Drink @Pet @Cigarettes) (permute (red blue green yellow white) @House) (left-of @House white @House green)   (permute (Norwegian English Swede German Dane) @Person) (has @Person English @House red) (equal @Person (Norwegian . @)) (next-to @Person Norwegian @House blue)   ...
Give a code snippet in #PicoLisp Zebra puzzle You are encouraged to solve this task according to the task description, using any language you may know. The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, one of them this:   There are five...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#QB64
QB64
INPUT "Press any key...", a$ IF 1 THEN SYSTEM
Give a code snippet in #QB64 Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/...
christopher/rosetta-code
http://rosettacode.org/wiki/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ......
#Common_Lisp
Common Lisp
(defun pi-spigot () (labels ((g (q r t1 k n l) (cond ((< (- (+ (* 4 q) r) t1) (* n t1)) (princ n) (g (* 10 q) (* 10 (- r (* n t1))) t1 k (- (floor (/ (* 10 (+ (* 3 q) r)) ...
Give a code snippet in #Common_Lisp Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decima...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#Lasso
Lasso
'Hello, world!'->size // 13 'møøse'->size // 5 '𝔘𝔫𝔦𝔠𝔬𝔡𝔢'->size // 7
Give a code snippet in #Lasso Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme cont...
christopher/rosetta-code
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#Tailspin
Tailspin
  processor Tic-Tac-Toe @: [1..9 -> (position:$) -> $::value];   source isWonOrDone [$@Tic-Tac-Toe(1..3) -> #, $@Tic-Tac-Toe(4..6) -> #, $@Tic-Tac-Toe(7..9) -> #, $@Tic-Tac-Toe(1..9:3) -> #, $@Tic-Tac-Toe(2..9:3) -> #, $@Tic-Tac-Toe(3..9:3) -> #, $@Tic-Tac-Toe([1,5,9]) -> #, $@Tic-Tac-Toe([3,5,7]) -...
Give a code snippet in #Tailspin Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWor...
christopher/rosetta-code
http://rosettacode.org/wiki/Abstract_type
Abstract type
Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations and/or components. Abstract ...
#Oberon-2
Oberon-2
  TYPE Animal = POINTER TO AnimalDesc; AnimalDec = RECORD [ABSTRACT] END;   (* Cat inherits from Animal *) Cat = POINTER TO CatDesc; CatDesc = RECORD (AnimalDesc) END;  
Give a code snippet in #Oberon-2 Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some opera...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#XPL0
XPL0
include c:\cxpl\codes; int X, Y; [Format(4, 0); Text(0, " |"); for X:= 1 to 12 do RlOut(0, float(X)); CrLf(0); Text(0, " --+"); for X:= 1 to 12 do Text(0, "----"); CrLf(0); for Y:= 1 to 12 do [RlOut(0, float(Y)); ChOut(0, ^|); for X:= 1 to 12 do if X>=Y then RlOut(0, float(X*Y)) else Text(0, " . ...
Give a code snippet in #XPL0 Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
christopher/rosetta-code
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Fortran
Fortran
program thue_morse implicit none logical :: f(32) = .false. integer :: n = 1   do write(*,*) f(1:n) if (n > size(f)/2) exit f(n+1:2*n) = .not. f(1:n) n = n * 2 end do   end program thue_morse
Give a code snippet in #Fortran Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_block_comments
Strip block comments
A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at least handle simple, non-ne...
#J
J
strip=:#~1 0 _1*./@:(|."0 1)2>4{"1(5;(0,"0~".;._2]0 :0);'/*'i.a.)&;: 1 0 0 0 2 0 2 3 2 0 2 2 )
Give a code snippet in #J A block comment begins with a   beginning delimiter   and ends with a   ending delimiter,   including the delimiters.   These delimiters are often multi-character sequences. Task Strip block comments from program text (of a programming language much like classic C). Your demos should at ...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Maple
Maple
  Hanoi := proc(n::posint,a,b,c) if n = 1 then printf("Move disk from tower %a to tower %a.\n",a,c); else Hanoi(n-1,a,c,b); Hanoi(1,a,b,c); Hanoi(n-1,b,a,c); fi; end:   printf("Moving 2 disks from tower A to tower C using tower B.\n"); Hanoi(2,A,B,C);  
Give a code snippet in #Maple Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/First_class_environments
First class environments
According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a programming language may support "...
#Racket
Racket
  #lang racket   (define namespaces (for/list ([i (in-range 1 13)]) (define ns (make-base-namespace)) (eval `(begin (define N ,i) (define count 0)) ns) ns))   (define (get-var-values name) (map (curry namespace-variable-value name #t #f) namespaces))   (define code '(when (> N 1) (set! N (if (eve...
Give a code snippet in #Racket According to Wikipedia, "In computing, a first-class object ... is an entity that can be constructed at run-time, passed as a parameter, returned from a subroutine, or assigned into a variable". Often this term is used in the context of "first class functions". In an analogous way, a pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded c...
#VBScript
VBScript
' Validate International Securities Identification Number - 03/03/2019 buf=buf&test("US0378331005")&vbCrLf buf=buf&test("US0373831005")&vbCrLf buf=buf&test("U50378331005")&vbCrLf buf=buf&test("US03378331005")&vbCrLf buf=buf&test("AU0000XVGZA3")&vbCrLf buf=buf&test("AU0000VXGZA3")&vbCrLf buf=buf&test("FR0000988040")&vb...
Give a code snippet in #VBScript An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the corr...
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Sed
Sed
s/^.*$/&:/ :bubble s/^:/1/ /.:/ { h s/^.*\(.\):.*$/\1/ y/0123456789/123456789:/ s/:/:0/ G s/\(.*\)\n\(.*\).:\(.*\)$/\2\1\3/ b bubble }
Give a code snippet in #Sed Task Increment a numerical string.
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.
#Julia
Julia
  using HTTP, HTTP.IOExtras, JSON, MusicProcessing HTTP.open("POST", "http://music.com/play") do io write(io, JSON.json([ "auth" => "12345XXXX", "song_id" => 7, ])) r = startread(io) @show r.status while !eof(io) bytes = readavailable(io) play(bytes) end end  
Give a code snippet in #Julia 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/Create_a_file
Create a file
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Standard_ML
Standard ML
let val out = TextIO.openOut "output.txt" in TextIO.closeOut out end;   OS.FileSys.mkDir "docs";
Give a code snippet in #Standard_ML In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
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...
#C.23
C#
using System; using System.Linq;   static class Program { static bool IsPangram(this string text, string alphabet = "abcdefghijklmnopqrstuvwxyz") { return alphabet.All(text.ToLower().Contains); }   static void Main(string[] arguments) { Console.WriteLine(arguments.Any() && arguments....
Give a code snippet in #C.23 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/Set_puzzle
Set puzzle
Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: color, symbol, number and shading. there are...
#Tcl
Tcl
# Generate random integer uniformly on range [0..$n-1] proc random n {expr {int(rand() * $n)}}   # Generate a shuffled deck of all cards; the card encoding was stolen from the # Perl6 solution. This is done once and then used as a constant. Note that the # rest of the code assumes that all cards in the deck are unique....
Give a code snippet in #Tcl Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: color, symbol, nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer 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 |...
#Batch_File
Batch File
@echo off setlocal EnableDelayedExpansion set /p a="A: " set /p b="B: " if %a% LSS %b% ( echo %a% is less than %b% ) else ( if %a% GTR %b% ( echo %a% is greater than %b% ) else ( if %a% EQU %b% ( echo %a% is equal to %b% )))
Give a code snippet in #Batch_File 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 Operat...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#APL
APL
wilson ← {⍵<2:0 ⋄ (⍵-1)=(⍵|×)/⍳⍵-1}
Give a code snippet in #APL Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wi...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#J
J
p:i.20 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 (#~ >:&100)i.&.(p:inv) 150 101 103 107 109 113 127 131 137 139 149 #(#~ >:&7700)i.&.(p:inv) 8000 30 p:10000-1 104729
Give a code snippet in #J 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 programm...
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...
#Racket
Racket
#lang racket/base (require racket/string racket/list)   (define (seconds->compound-durations s) (define-values (w d.h.m.s) (for/fold ((prev-q s) (rs (list))) ((Q (in-list (list 60 60 24 7)))) (define-values (q r) (quotient/remainder prev-q Q)) (values q (cons r rs)))) (cons w d.h.m.s))   (d...
Give a code snippet in #Racket 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/Distributed_programming
Distributed programming
Write two programs (or one program with two modes) which run on networked computers, and send some messages between them. The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example ...
#Wren
Wren
/* distributed_programming_server.wren */   class Rpc { foreign static register()   foreign static handleHTTP() }   foreign class Listener { construct listen(network, address) {} }   class HTTP { foreign static serve(listener) }   Rpc.register() Rpc.handleHTTP() var listener = Listener.listen("tcp", ":1...
Give a code snippet in #Wren Write two programs (or one program with two modes) which run on networked computers, and send some messages between them. The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed ju...
christopher/rosetta-code
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#jq
jq
# Input is the string to be encoded, st is the initial symbol table (an array) # Output: the encoded string (an array) def m2f_encode(st): reduce explode[] as $ch ( [ [], st]; # state: [ans, st] (.[1]|index($ch)) as $ix | .[1] as $st | [ (.[0] + [ $ix ]), [$st[$ix]] + $st[0:$i...
Give a code snippet in #jq Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in...
christopher/rosetta-code
http://rosettacode.org/wiki/Table_creation/Postal_addresses
Table creation/Postal addresses
Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip...
#Sidef
Sidef
require('DBI');   var db = %s'DBI'.connect('DBI:mysql:database:server','login','password');   var statment = <<'EOF'; CREATE TABLE `Address` ( `addrID` int(11) NOT NULL auto_increment, `addrStreet` varchar(50) NOT NULL default '', `addrCity` varchar(25) NOT NULL default '', `addrSt...
Give a code snippet in #Sidef Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state co...
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...
#Ring
Ring
  pangram = 0 s = "The quick brown fox jumps over the lazy dog." see "" + pangram(s) + " " + s + nl   s = "My dog has fleas." see "" + pangram(s) + " " + s + nl   func pangram str str = lower(str) for i = ascii("a") to ascii("z") bool = substr(str, char(i)) > 0 pangram = pangram + b...
Give a code snippet in #Ring 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/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...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. demo-map-range.   DATA DIVISION. WORKING-STORAGE SECTION. 01 i USAGE FLOAT-LONG.   01 mapped-num USAGE FLOAT-LONG.   01 a-begin USAGE FLOAT-LONG VALUE 0. 01 a-end ...
Give a code snippet in #COBOL 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/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#C.2B.2B
C++
#include <algorithm> //std::max_element #include <iterator> //std::begin and std::end #include <functional> //std::less   template<class It, class Comp = std::less<>> //requires ForwardIterator<It> && Compare<Comp> constexpr auto max_value(It first, It last, Comp compare = std::less{}) { //Precondition: firs...
Give a code snippet in #C.2B.2B Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#11l
11l
F happy(=n) Set[Int] past L n != 1 n = sum(String(n).map(с -> Int(с)^2)) I n C past R 0B past.add(n) R 1B   print((0.<500).filter(x -> happy(x))[0.<8])
Give a code snippet in #11l From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in...
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...
#CoffeeScript
CoffeeScript
# Functions as values of a variable cube = (x) -> Math.pow x, 3 cuberoot = (x) -> Math.pow x, 1 / 3   # Higher order function compose = (f, g) -> (x) -> f g(x)   # Storing functions in a array fun = [Math.sin, Math.cos, cube] inv = [Math.asin, Math.acos, cuberoot]   # Applying the composition to 0.5 console.log compose...
Give a code snippet in #CoffeeScript 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 ...
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...
#J
J
'names numbers'=:|:".;._2]0 :0 'map'; 9 150 1 'compass'; 13 35 1 'water'; 153 200 2 'sandwich'; 50 60 2 'glucose'; 15 60 2 'tin'; 68 ...
Give a code snippet in #J 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#J
J
readLine=: 4 :0 (x-1) {:: <;.2 ] 1!:1 boxxopen y )
Give a code snippet in #J Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a ...
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. ...
#AppleScript
AppleScript
set x to linefeed repeat with i from 1 to 5 repeat with j from 1 to i set x to x & "*" end repeat set x to x & linefeed end repeat return x
Give a code snippet in #AppleScript “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 s...
christopher/rosetta-code
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit ...
#Q
Q
scd:{ v:{("i"$x) - ?[("0"<=x) & x<="9"; "i"$"0"; -10+"i"$"A"]} each x; / Turn characters of SEDOL into their values w:sum v*1 3 1 7 3 9; / Weighted sum of values d:(10 - w mod 10) mod 10; / Check digit value x,"c"$(("i"$"0")+d) / Append to SEDOL }   scd each ("710889";"B0YBKJ";"406566";...
Give a code snippet in #Q Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0Y...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#Stata
Stata
window stopbox note "Goodbye, World!"
Give a code snippet in #Stata Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have download...
#Clojure
Clojure
(defn is-sorted? [coll] (not-any? pos? (map compare coll (next coll))))   (defn take-while-eqcount [coll] (let [n (count (first coll))] (take-while #(== n (count %)) coll)))   (with-open [rdr (clojure.java.io/reader "unixdict.txt")] (->> rdr line-seq (filter is-sorted?) (sort-by count >) ...
Give a code snippet in #Clojure An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file loca...
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...
#Racket
Racket
  #lang racket   ;; Explicit conversion of numbers can use the standard radices (map (λ(r) (number->string 123 r)) '(2 8 10 16)) ;; -> '("1111011" "173" "123" "7b")   ;; There is also the `~r' formatting function that works with any radix ;; up to 36 (for/list ([r (in-range 2 37)]) (~r 123 #:base r)) ;; -> '("1111011" ...
Give a code snippet in #Racket 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 ro...
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#OCaml
OCaml
let luhn s = let rec g r c = function | 0 -> r | i -> let d = c * ((int_of_char s.[i-1]) - 48) in g (r + (d/10) + (d mod 10)) (3-c) (i-1) in (g 0 1 (String.length s)) mod 10 = 0 ;;
Give a code snippet in #OCaml The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of...
christopher/rosetta-code
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identif...
#Perl
Perl
use utf8;   my $Δ = 1; $Δ++; print $Δ, "\n";
Give a code snippet in #Perl Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task ...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Scheme
Scheme
(define (transpose m) (apply map list m))
Give a code snippet in #Scheme Transpose an arbitrarily sized rectangular Matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#NetRexx
NetRexx
  class LuhnTest   method main(args=String[]) static cc = 0 cc[1] = '49927398716' cc[2] = '49927398717' cc[3] = '1234567812345678' cc[4] = '1234567812345670'   loop k=1 while cc[k] <> 0 r = checksum(cc[k]) if r==0 then say cc[k].right(20) 'passed' else say cc[k].right(20) ...
Give a code snippet in #NetRexx The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#JavaScript
JavaScript
#!/usr/bin/env js   function main() { var len = 4; playBullsAndCows(len); }   function playBullsAndCows(len) { var num = pickNum(len); // print('The secret number is:\n ' + num.join('\n ')); showInstructions(len); var nGuesses = 0; while (true) { nGuesses++; var guess = get...
Give a code snippet in #JavaScript Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if...
christopher/rosetta-code
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/et...
#Lua
Lua
-- Dataset declaration local cityPops = { {name = "Lagos", population = 21.0}, {name = "Cairo", population = 15.2}, {name = "Kinshasa-Brazzaville", population = 11.3}, {name = "Greater Johannesburg", population = 7.55}, {name = "Mogadishu", population = 5.85}, {name = "Khartoum-Omdurman", popula...
Give a code snippet in #Lua Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edi...
christopher/rosetta-code