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/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#Action.21
Action!
BYTE FUNC CheckNeighbors(CARD x BYTE y) IF Locate(x-1,y-1)=1 THEN RETURN (1) FI IF Locate(x,y-1)=1 THEN RETURN (1) FI IF Locate(x+1,y-1)=1 THEN RETURN (1) FI IF Locate(x-1,y)=1 THEN RETURN (1) FI IF Locate(x+1,y)=1 THEN RETURN (1) FI IF Locate(x-1,y+1)=1 THEN RETURN (1) FI IF Locate(x,y+1)=1 THEN RETURN (...
Give a code snippet in #Action.21 Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The in...
christopher/rosetta-code
http://rosettacode.org/wiki/Fraction_reduction
Fraction reduction
There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16 ──── and then (simp...
#Raku
Raku
my %reduced; my $digits = 2..4;   for $digits.map: * - 1 -> $exp { my $start = sum (0..$exp).map( { 10 ** $_ * ($exp - $_ + 1) }); my $end = 10**($exp+1) - sum (^$exp).map( { 10 ** $_ * ($exp - $_) } ) - 1;   ($start ..^ $end).race(:8degree, :3batch).map: -> $den { next if $den.contains: '0'; ...
Give a code snippet in #Raku There is a fine line between numerator and denominator.       ─── anonymous A method to   "reduce"   some reducible fractions is to   cross out   a digit from the numerator and the denominator.   An example is: 16 16...
christopher/rosetta-code
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Crystal
Crystal
  require "json_mapping"   class Foo JSON.mapping( num: Int64, array: Array(String), ) end   def json foo = Foo.from_json(%({"num": 1, "array": ["a", "b"]})) puts("#{foo.num} #{foo.array}") puts(foo.to_json) end  
Give a code snippet in #Crystal Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
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...
#Delphi
Delphi
program LastFridayOfMonth;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.DateUtils;   var Year: Word; Month: Word; D1: TDateTime; D2: Word;   begin Write('Enter year: '); ReadLn(Year);   for Month := MonthJanuary to MonthDecember do begin D1 := EndOfAMonth(Year, Month); D2 := DayOfTheWeek(...
Give a code snippet in #Delphi 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 201...
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...
#Scala
Scala
import scala.collection.parallel.immutable.ParSeq   object LeftTruncatablePrime extends App { private def leftTruncatablePrime(maxRadix: Int, millerRabinCertainty: Int) { def getLargestLeftTruncatablePrime(radix: Int, millerRabinCertainty: Int): BigInt = { def getNextLeftTruncatablePrimes(n: BigInt, radix: ...
Give a code snippet in #Scala 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/Find_palindromic_numbers_in_both_binary_and_ternary_bases
Find palindromic numbers in both binary and ternary bases
Find palindromic numbers in both binary and ternary bases You are encouraged to solve this task according to the task description, using any language you may know. Task   Find and show (in decimal) the first six numbers (non-negative integers) that are   palindromes   in   both:   base 2   base 3   Display   0   ...
#Ada
Ada
with Ada.Text_IO, Base_Conversion;   procedure Brute is   type Long is range 0 .. 2**63-1; package BC is new Base_Conversion(Long);   function Palindrome (S : String) return Boolean is (if S'Length < 2 then True elsif S(S'First) /= S(S'Last) then False else Palindrome(S(S'First+1 .. S'Last-1)...
Give a code snippet in #Ada Find palindromic numbers in both binary and ternary bases You are encouraged to solve this task according to the task description, using any language you may know. Task   Find and show (in decimal) the first six numbers (non-negative integers) that are   palindromes   in   both:   base ...
christopher/rosetta-code
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#AutoHotkey
AutoHotkey
SetBatchLines -1   InputBox, Enter_value, Enter the no. of lines sought array := [] Loop, % 2*Enter_value - 1 Loop, % x := A_Index y := A_Index, Array[x, y] := 1   x := 3   Loop { base_r := x - 1 , x++ , y := 2 , index := x , new := 1   Loop, % base_r - 1 { array[x, new+1] := array[x-1, new] + array[base_r,...
Give a code snippet in #AutoHotkey This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer ...
christopher/rosetta-code
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#Visual_Basic_.NET
Visual Basic .NET
  Imports System.Drawing.Imaging   Public Function Grayscale(ByVal Map As Bitmap) As Bitmap   Dim oData() As Integer = GetData(Map) Dim oReturn As New Bitmap(Map.Width, Map.Height, Map.PixelFormat) Dim a As Integer = 0 Dim r As Integer = 0 Dim g As Integer = 0 Dim b As Integer = 0 Dim l As...
Give a code snippet in #Visual_Basic_.NET Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward...
christopher/rosetta-code
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#Eiffel
Eiffel
  class APPLICATION   inherit ARGUMENTS   create make   feature {NONE} -- Initialization   make -- Run application. local dim : INTEGER -- Dimension of the identity matrix do from dim := 1 until dim > 10 loop print_matrix( identity_matrix(dim) ) dim := dim + 1 io.new_line end   ...
Give a code snippet in #Eiffel Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_turtle_graphics
Simple turtle graphics
The first turtle graphic discussed in Mindstorms: Children, Computers, and Powerful Ideas by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof. For a slightly more advanced audience, a more practical introduction to turtle graphics might be to draw a bar chart. See imag...
#Yabasic
Yabasic
// Rosetta Code problem: http://rosettacode.org/wiki/Simple_turtle_graphics // Adapted from Python to Yabasic by Galileo, 01/2022   import turtle   sub rectang(width, height) local i   for i = 1 to 2 move(height) turn(-90) move(width) turn(-90) next end sub   sub square(size)...
Give a code snippet in #Yabasic The first turtle graphic discussed in Mindstorms: Children, Computers, and Powerful Ideas by Seymour Papert is a simple drawing of a house. It is a square with a triangle on top for the roof. For a slightly more advanced audience, a more practical introduction to turtle graphics might ...
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...
#Scheme
Scheme
(define (power-set set) (if (null? set) '(()) (let ((rest (power-set (cdr set)))) (append (map (lambda (element) (cons (car set) element)) rest) rest))))   (display (power-set (list 1 2 3))) (newline)   (display (power-set (list "A" "C" "E"))) (newline)
Give a code snippet in #Scheme 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. Give...
christopher/rosetta-code
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#PL.2FI
PL/I
  identity: procedure (A, n); declare A(n,n) fixed controlled; declare (i,n) fixed binary; allocate A; A = 0; do i = 1 to n; A(i,i) = 1; end; end identity;  
Give a code snippet in #PL.2FI Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 ...
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...
#Mathprog
Mathprog
  /*Arithmetic Mean of a large number of Integers - or - solve a very large constraint matrix over 1 million rows and columns Nigel_Galloway March 18th., 2008. */   param e := 20; set Sample := {1..2**e-1};   var Mean; var E{z in Sample};   /* sum of variances is zero */ zumVariance: sum{z in Sample} E[z...
Give a code snippet in #Mathprog 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 e...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#Tailspin
Tailspin
  templates ssq when <[](0)> do 0 ! otherwise $... -> $*$ -> ..=Sum&{of: :()} ! end ssq   [] -> ssq -> !OUT::write // outputs 0 [1..5] -> ssq -> !OUT::write // outputs 55  
Give a code snippet in #Tailspin Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
christopher/rosetta-code
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#REXX
REXX
pr. = /*define a default for all elements for the array*/   pr.1 = 2 /*note that this array starts at 1 (one). */ pr.2 = 3 pr.3 = 5 pr.4 = 7 pr.5 = 11 pr.6 = 13 pr.7 = 17 pr.8 = 19 pr.9 = 23 pr.10 = 29 pr.11 = 31 pr.12 = 37 pr.13 = 41 pr.14 = 43 pr.15 ...
Give a code snippet in #REXX This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Cre...
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...
#GDScript
GDScript
func mapRange(s:float, a1:float, a2:float, b1:float, b2:float) -> float : return b1 + ((b2-b1)/(a2-a1))*(s-a1)   for i in 11 : print( "%2d %+.1f" % [i,mapRange(i,0.0,10.0,-1.0,0.0)] )  
Give a code snippet in #GDScript 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 linearl...
christopher/rosetta-code
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#LOLCODE
LOLCODE
HAI 1.3   HOW IZ I fib YR x DIFFRINT x AN BIGGR OF x AN 0, O RLY? YA RLY, FOUND YR "ERROR" OIC   HOW IZ I fib_i YR n DIFFRINT n AN BIGGR OF n AN 2, O RLY? YA RLY, FOUND YR n OIC   FOUND YR SUM OF... I IZ fib_i YR DIFF OF n AN 2 MKAY AN... I IZ fib_...
Give a code snippet in #LOLCODE While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwa...
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...
#Julia
Julia
function tag(x::Pair, attr::Pair...) t, b = x attrstr = join(" $n=\"$p\"" for (n, p) in attr) return "<$t$attrstr>$b</$t>" end   colnames = split(",X,Y,Z", ',')   header = join(tag(:th => txt) for txt in colnames) * "\n" rows = collect(tag(:tr => join(tag(:td => i, :style => "font-weight: bold;") * join(t...
Give a code snippet in #Julia 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 wit...
christopher/rosetta-code
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#mIRC_Scripting_Language
mIRC Scripting Language
alias Write2FileAndReadIt { .write myfilename.txt Goodbye Mike! .echo -a Myfilename.txt contains: $read(myfilename.txt,1) }
Give a code snippet in #mIRC_Scripting_Language File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Primes_-_allocate_descendants_to_their_ancestors
Primes - allocate descendants to their ancestors
The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'. The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance. This solution could be compared to the solution that would use the decomposition into primes for all the numbers betw...
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <vector>   typedef unsigned long long integer;   // returns all ancestors of n. n is not its own ancestor. std::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) { std::vector<integer> result; for (integer a = ancestor[n]; a != 0 && ...
Give a code snippet in #C.2B.2B The concept, is to add the decomposition into prime factors of a number to get its 'ancestors'. The objective is to demonstrate that the choice of the algorithm can be crucial in term of performance. This solution could be compared to the solution that would use the decomposition int...
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#Nemerle
Nemerle
Shuffle[T] (arr : array[T]) : array[T] { def rnd = Random();   foreach (i in [0 .. (arr.Length - 2)]) arr[i] <-> arr[(rnd.Next(i, arr.Length))]; arr }
Give a code snippet in #Nemerle The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from ...
christopher/rosetta-code
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X
Isqrt (integer square root) of X
Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your computer programming language,   assume...
#Phix
Phix
with javascript_semantics include mpfr.e function isqrt(mpz x) if mpz_cmp_si(x,0)<0 then crash("Argument cannot be negative.") end if mpz q = mpz_init(1), r = mpz_init(0), t = mpz_init(), z = mpz_init_set(x) while mpz_cmp(q,x)<= 0 do mpz_mul_si(q,q,4) end wh...
Give a code snippet in #Phix Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your computer ...
christopher/rosetta-code
http://rosettacode.org/wiki/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#Ring
Ring
  see lcm(24,36)   func lcm m,n lcm = m*n / gcd(m,n) return lcm   func gcd gcd, b while b c = gcd gcd = b b = c % b end return gcd  
Give a code snippet in #Ring Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has ...
christopher/rosetta-code
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly
Old lady swallowed a fly
Task Present a program which emits the lyrics to the song   I Knew an Old Lady Who Swallowed a Fly,   taking advantage of the repetitive structure of the song's lyrics. This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output. Other tasks related to st...
#PL.2FM
PL/M
100H:   /* CP/M CALL */ BDOS: PROCEDURE(FUNC, ARGS); DECLARE FUNC BYTE, ARGS ADDRESS; GO TO 5; END BDOS;   /* PRINT STRING */ PRINT: PROCEDURE(STRING); DECLARE STRING ADDRESS; CALL BDOS(9, STRING); END PRINT;   DECLARE COMMA$CRLF DATA (',',13,10,'$'); DECLARE CRLF DATA (13,10,'$');   DECLARE ANIMALS (8)...
Give a code snippet in #PL.2FM Task Present a program which emits the lyrics to the song   I Knew an Old Lady Who Swallowed a Fly,   taking advantage of the repetitive structure of the song's lyrics. This song has multiple versions with slightly different lyrics, so all these programs might not emit identical outpu...
christopher/rosetta-code
http://rosettacode.org/wiki/Pernicious_numbers
Pernicious numbers
A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,   and therefore 22   is a pe...
#AWK
AWK
  # syntax: GAWK -f PERNICIOUS_NUMBERS.AWK BEGIN { pernicious(25) pernicious(888888877,888888888) exit(0) } function pernicious(x,y, count,n) { if (y == "") { # print first X pernicious numbers while (count < x) { if (is_prime(pop_count(++n)) == 1) { printf("%d ",n) co...
Give a code snippet in #AWK A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same 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 the same   indicate if or which character is different from the previous character   display each string and its length   (as the...
#Clojure
Clojure
  (defn check-all-chars-same [s] (println (format "String (%s) of len: %d" s (count s))) (let [num-same (-> (take-while #(= (first s) %) s) count)] (if (= num-same (count s)) (println "...all characters the same") (println (format "...character %d differs - it is 0x%x" ...
Give a code snippet in #Clojure 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 the same   indicate if or which character is different from the previous character   display eac...
christopher/rosetta-code
http://rosettacode.org/wiki/Faulhaber%27s_formula
Faulhaber's formula
In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expressions, starting with p = 0. R...
#F.C5.8Drmul.C3.A6
Fōrmulæ
n := X(Rationals, "n"); sum1 := p -> Sum([0 .. p], k -> Stirling2(p, k) * Product([0 .. k], j -> n + 1 - j) / (k + 1)) + 2 * Bernoulli(2 * p + 1); sum2 := p -> Sum([0 .. p], j -> (-1)^j * Binomial(p + 1, j) * Bernoulli(j) * n^(p + 1 - j)) / (p + 1); ForAll([0 .. 20], k -> sum1(k) = sum2(k));   for p in [0 .. 9] do ...
Give a code snippet in #F.C5.8Drmul.C3.A6 In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-...
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...
#Erlang
Erlang
-module(pangram). -export([is_pangram/1]).   is_pangram(String) -> ordsets:is_subset(lists:seq($a, $z), ordsets:from_list(string:to_lower(String))).
Give a code snippet in #Erlang 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 Wr...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * ...
#Delphi
Delphi
program SierpinskiTriangle;   {$APPTYPE CONSOLE}   procedure PrintSierpinski(order: Integer); var x, y, size: Integer; begin size := (1 shl order) - 1; for y := size downto 0 do begin Write(StringOfChar(' ', y)); for x := 0 to size - y do begin if (x and y) = 0 then Write('* ') e...
Give a code snippet in #Delphi Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * ...
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 ≤...
#Gosu
Gosu
  uses java.io.InputStreamReader uses java.util.Scanner uses java.lang.System   var scanner = new Scanner( new InputStreamReader( System.in ) ) var a = scanner.nextInt() var b = scanner.nextInt()   print( a + b )  
Give a code snippet in #Gosu 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...
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...
#Forth
Forth
: array ( n -- ) ( i -- addr) create cells allot does> swap cells + ;   100 array sequence   : sequence. ( n -- ) cr 0 ?do i sequence @ . loop ;   : ?unused ( n -- t | n ) 100 0 ?do dup i sequence @ = if unloop exit then loop drop true ;   : sequence-next ( n -- a[n] ) dup 0= if 0 0 sequence ! exit then ...
Give a code snippet in #Forth 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. Ta...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations/Rank_of_a_permutation
Permutations/Rank of a permutation
A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items. For our purposes the ranking will assign integers 0.. ( n ! − 1 ) {\displaystyle 0..(n!-1)} to an ordering of all the permutations of the integers 0.. ( n − 1 ) {\disp...
#D
D
import std.stdio, std.algorithm, std.range;   alias TRank = ulong;   TRank factorial(in uint n) pure nothrow { TRank result = 1; foreach (immutable i; 2 .. n + 1) result *= i; return result; }   /// Fill the integer array <vec> with the permutation at rank <rank>. void computePermutation(size_t N)(r...
Give a code snippet in #D A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items. For our purposes the ranking will assign integers 0.. ( n ! − 1 ) {\displaystyle 0..(n!-1)} to an ordering of all the permutations of the integers...
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...
#C.23
C#
using System; using System.Linq;   class Program { static void Main() { Console.WriteLine(new[] { 1, 2, 3 }.Average()); } }
Give a code snippet in #C.23 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 estab...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_string_challenge
Longest string challenge
Background This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through th...
#Phix
Phix
with javascript_semantics --integer fn = open(command_line()[2],"r") -- (reading the source file) sequence fn = unix_dict()[1..40]&-1 function allx(string line) line[1..-1] = 'x' return line end function function longest(string mask) -- object line = gets(fn) object line = fn[1]; fn = fn[2..$]; if ...
Give a code snippet in #Phix Background This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challeng...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#WDTE
WDTE
let s => import 'stream';   s.range 1 1001 -> s.map (@ inner k => / 1 (* k k)) -> s.reduce 0 + -- io.writeln io.stdout ;
Give a code snippet in #WDTE Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Optional_parameters
Optional parameters
Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicographic by default. column ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Options[OptionalSort]={ordering->lexicographic,column->1,reverse-> False}; OptionalSort[x_List,OptionsPattern[]]:=If[OptionValue[reverse]==True, SortBy[x ,#[[OptionValue[column]]]&]//Reverse, SortBy[x,#[[OptionValue[column]]]&] ]   OptionalSort[{{"a" ,"b", "c"}, {"", "q", "z"},{"zap" ,"zip", "Zot"}} ] ->{{,q,z},{a,b,c}...
Give a code snippet in #Mathematica.2FWolfram_Language Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#PHP
PHP
# this is commented // this is commented
Give a code snippet in #PHP Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Run_BASIC
Run BASIC
gifts$ = " A partridge in a pear tree., Two turtle doves, Three french hens, Four calling birds, Five golden rings, Six geese a-laying, Seven swans a-swimming, Eight maids a-milking, Nine ladies dancing, Ten lords a-leaping, Eleven pipers piping, Twelve drummers drumming"   days$ = "first second third fourth fifth sixt...
Give a code snippet in #Run_BASIC 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 opera...
christopher/rosetta-code
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a v...
#Perl
Perl
use strict; use warnings;   use constant EXIT_FAILURE => 1; use constant EXIT_SUCCESS => 0;   sub amb { exit(EXIT_FAILURE) if !@_; for my $word (@_) { my $pid = fork; die $! unless defined $pid; return $word if !$pid; my $wpid = waitpid $pid, 0; die $! unless $wpid == $pid; exi...
Give a code snippet in #Perl Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"...
christopher/rosetta-code
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#360_Assembly
360 Assembly
* ABC Problem 21/07/2016 ABC CSECT USING ABC,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 ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete ...
christopher/rosetta-code
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#Swift
Swift
extension FloatingPoint where Self: ExpressibleByFloatLiteral { @inlinable public func power(_ e: Int) -> Self { var res = Self(1)   for _ in 0..<e { res *= self }   return res }   @inlinable public func root(n: Int, epsilon: Self = 2.220446049250313e-16) -> Self { var d = Self(0) ...
Give a code snippet in #Swift Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#XPL0
XPL0
func real Det; real A0, B0, A1, B1; return A0*B1 - A1*B0;   func Cramer; real A0, B0, C0, A1, B1, C1; real Denom; [Denom:= Det(A0, B0, A1, B1); RlOut(0, Det(C0, B0, C1, B1) / Denom); RlOut(0, Det(A0, C0, A1, C1) / Denom); ];   real L0, L1, M0, M1; [L0:= [[ 4., 0.], [ 6., 10.]]; L1:= [[ 0., 3.], [10., 7.]]; M0:= (L0...
Give a code snippet in #XPL0 [1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#PARI.2FGP
PARI/GP
dsum(n)=my(s); while(n, s+=n%10; n\=10); s additivePersistence(n)=my(s); while(n>9, s++; n=dsum(n)); s digitalRoot(n)=if(n, (n-1)%9+1, 0)
Give a code snippet in #PARI.2FGP The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X}...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant_odd_numbers
Abundant odd numbers
An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternately,   has the sigma sum of ...
#q
q
s:{c where 0=x mod c:1+til x div 2} / proper divisors sd:sum s@ / sum of proper divisors abundant:{x<sd x} Filter:{y where x each y}
Give a code snippet in #q An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternate...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Break
Loops/Break
Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If the number 10 is never gener...
#dc
dc
1 ss [s = seed of the random number generator]sz 0k [scale = 0]sz   [Function r: Push a random number from 0 to 20.]sz [ [2Q]SA [ [Formula (from POSIX) for random numbers of low quality.]sz ls 1103515245 * 12345 + 4294967296 % d ss [Compute next s]sz 65536 / [it = s / 65536]sz d 16 !>A [Break loop...
Give a code snippet in #dc Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If ...
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...
#NewLISP
NewLISP
(define (Mean Lst) (if (empty? Lst) 0 (/ (apply + Lst) (length Lst))))   (Mean (sequence 1 1000))-> 500 (Mean '()) -> 0
Give a code snippet in #NewLISP 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 es...
christopher/rosetta-code
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#TechBASIC
TechBASIC
  {{trans|BASIC}} FUNCTION HAVERSINE !--------------------------------------------------------------- !*** Haversine Formula - Calculate distances by LAT/LONG !   !*** LAT/LON of the two locations and Unit of measure are GLOBAL !*** as they are defined in the main logic of the program, so they !*** available for use in...
Give a code snippet in #TechBASIC This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an ...
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...
#dc
dc
[Benjamin]sd [Samba]sD [The two dogs are named ]P ldP [ and ]P lDP [. ]P
Give a code snippet in #dc 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/Non-decimal_radices/Convert
Non-decimal radices/Convert
Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary, but that's typically invisibl...
#OCaml
OCaml
let int_of_basen n str = match n with | 16 -> int_of_string("0x" ^ str) | 2 -> int_of_string("0b" ^ str) | 8 -> int_of_string("0o" ^ str) | _ -> failwith "unhandled"   let basen_of_int n d = match n with | 16 -> Printf.sprintf "%x" d | 8 -> Printf.sprintf "%o" d | _ -> failwith "unhandled"
Give a code snippet in #OCaml Number base conversion is when you express a stored integer in an integer base, such as in octal (base 8) or binary (base 2). It also is involved when you take a string representing a number in a given base and convert it to the stored integer form. Normally, a stored integer is in binary...
christopher/rosetta-code
http://rosettacode.org/wiki/15_puzzle_game
15 puzzle game
Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
#Visual_Prolog
Visual Prolog
  /* ------------------------------------------------------------------------------------------------------   Copyright (c) 2004 - Gal Zsolt (CalmoSoft)   ------------------------------------------------------------------------------------------------------ */   impleme...
Give a code snippet in #Visual_Prolog Task Implement the Fifteen Puzzle Game. The   15-puzzle   is also known as:   Fifteen Puzzle   Gem Puzzle   Boss Puzzle   Game of Fifteen   Mystic Square   14-15 Puzzle   and some others. Related Tasks   15 Puzzle Solver   16 Puzzle Game
christopher/rosetta-code
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#Icon_and_Unicon
Icon and Unicon
procedure main(args) n := integer(!args) | 5 every !(A := list(n)) := list(n) A := zigzag(A) show(A) end   procedure show(A) every writes(right(!A,5) | "\n") end   procedure zigzag(A) x := [0,0] every i := 0 to (*A^2 -1) do { x := nextIndices(*A, x) A[x[1]][x[2]] := i } ...
Give a code snippet in #Icon_and_Unicon Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arr...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-...
#Common_Lisp
Common Lisp
(defun make-fibwords (array) (loop for i from 0 below 37 for j = "0" then (concatenate 'string j k) and k = "1" then j do (setf (aref array i) k)) array)   (defvar *fib* (make-fibwords (make-array 37)))   (defun entropy (string) (let ((table (make-hash-table :test 'eql)) (entropy 0d0)...
Give a code snippet in #Common_Lisp The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_W...
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,...
#Unicon_2
Unicon
L := list(100); L[12] := 7; a := array(100, 0.0); a[3] +:= a[1]+a[2]
Give a code snippet in #Unicon_2 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 re...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle n...
#PicoLisp
PicoLisp
(scl 40)   (de solveQuad (A B C) (let SD (sqrt (- (* B B) (* 4 A C))) (if (lt0 B) (list (*/ (- SD B) A 2.0) (*/ C 2.0 (*/ A A (- SD B) `(* 1.0 1.0))) ) (list (*/ C 2.0 (*/ A A (- 0 B SD) `(* 1.0 1.0))) (*/ (- 0 B SD) A 2.0) ) ) ) )   (mapcar rou...
Give a code snippet in #PicoLisp This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Yo...
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...
#TI-83_BASIC
TI-83 BASIC
PROGRAM:LUHN :Disp "ENTER NUMBER" :Input Str1 :0→S :0→E :For(I,length(Str1),1,-1)  :inString("0123456789",sub(Str1,I,1))–1→X  :If X<0  :Goto BA  :If E≠0  :Then  :2X→X  :If X>9  :X–9→X  :End  :X+S→S  :not(E)→E :End :If fPart(S/10)=0 :Then  :Disp "GOOD CARD" :Else  :Lbl BA  :Disp "BAD CARD" :End  
Give a code snippet in #TI-83_BASIC 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 or...
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 ...
#PARI.2FGP
PARI/GP
mergeSort(v)={ if(#v<2, return(v)); my(m=#v\2,left=vector(m,i,v[i]),right=vector(#v-m,i,v[m+i])); left=mergeSort(left); right=mergeSort(right); merge(left, right) }; merge(u,v)={ my(ret=vector(#u+#v),i=1,j=1); for(k=1,#ret, if(i<=#u & (j>#v | u[i]<v[j]), ret[k]=u[i]; i++ , ret[k]=v[j]; j++ ...
Give a code snippet in #PARI.2FGP Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a maze, using the simple Depth...
#Swift
Swift
import Foundation   extension Array { mutating func shuffle() { guard count > 1 else { return }   for i in 0..<self.count - 1 { let j = Int(arc4random_uniform(UInt32(count - i))) + i guard i != j else { continue } swap(&self[i], &self[j]) } } }   enum ...
Give a code snippet in #Swift This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show...
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#8051_Assembly
8051 Assembly
clr bit ; clears setb bit ; sets
Give a code snippet in #8051_Assembly Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body...
#HicEst
HicEst
DO i = 10, 0, -1 WRITE() i ENDDO
Give a code snippet in #HicEst Task Write a   for   loop which writes a countdown from   10   to   0. 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/Incre...
christopher/rosetta-code
http://rosettacode.org/wiki/Polynomial_long_division
Polynomial long division
This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long division is an algorithm for d...
#Maple
Maple
  > p := randpoly( x ); # pick a random polynomial in x 5 4 3 2 p := -56 - 7 x + 22 x - 55 x - 94 x + 87 x   > rem( p, x^2 + 2, x, 'q' ); # remainder 220 + 169 x   > q; # quotient 3 2 ...
Give a code snippet in #Maple This page uses content from Wikipedia. The original article was at Polynomial long division. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In algebra, polynomial long...
christopher/rosetta-code
http://rosettacode.org/wiki/Optional_parameters
Optional parameters
Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of strings; lexicographic by default. column ...
#Common_Lisp
Common Lisp
(defun sort-table (table &key (ordering #'string<) (column 0) reverse) (sort table (if reverse (complement ordering) ordering) :key (lambda (row) (elt row column))))
Give a code snippet in #Common_Lisp Task Define a function/method/subroutine which sorts a sequence ("table") of sequences ("rows") of strings ("cells"), by one of the strings. Besides the input to be sorted, it shall have the following optional parameters: ordering A function specifying the ordering of string...
christopher/rosetta-code
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting 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 She...
#AppleScript
AppleScript
-- <= for lists -- compare :: [a] -> [a] -> Bool on compare(xs, ys) if length of xs = 0 then true else if length of ys = 0 then false else set {hx, txs} to uncons(xs) set {hy, tys} to uncons(ys)   if hx = hy then compare(txs...
Give a code snippet in #AppleScript sorting 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 s...
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Forth
Forth
: f ( -- ) 1 throw ." f " ; \ will throw a "1" : g ( -- ) 0 throw ." g " ; \ does not throw
Give a code snippet in #Forth Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions...
christopher/rosetta-code
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that...
#Common_Lisp
Common Lisp
(defun egyption-fractions (x y &optional acc) (let* ((a (/ x y))) (cond ((> (numerator a) (denominator a)) (multiple-value-bind (q r) (floor x y) (if (zerop r) (cons q acc) (egyption-fractions r y (cons q acc))))) ((= (numerator a) 1) (reverse (cons a acc))) (t (let ((b (ceiling y ...
Give a code snippet in #Common_Lisp An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_definition
Singly-linked list/Element definition
singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, Lis...
#Ada
Ada
type Link; type Link_Access is access Link; type Link is record Next : Link_Access := null; Data : Integer; end record;
Give a code snippet in #Ada singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element defin...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#C
C
/* using pointer arithmetic (because we can, I guess) */ int arg[] = { 1,2,3,4,5 }; int arg_length = sizeof(arg)/sizeof(arg[0]); int *end = arg+arg_length; int sum = 0, prod = 1; int *p;   for (p = arg; p!=end; ++p) { sum += *p; prod *= *p; }
Give a code snippet in #C Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Linear_congruential_generator
Linear congruential generator
The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaystyle r_{0}} is a seed. r 1 ...
#D
D
struct LinearCongruentialGenerator { enum uint RAND_MAX = (1U << 31) - 1; uint seed = 0;   uint randBSD() pure nothrow @nogc { seed = (seed * 1_103_515_245 + 12_345) & RAND_MAX; return seed; }   uint randMS() pure nothrow @nogc { seed = (seed * 214_013 + 2_531_011) & RAND_MAX...
Give a code snippet in #D The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaystyle r_{0}...
christopher/rosetta-code
http://rosettacode.org/wiki/Display_a_linear_combination
Display a linear combination
Task Display a finite linear combination in an infinite vector basis ( e 1 , e 2 , … ) {\displaystyle (e_{1},e_{2},\ldots )} . Write a function that, when given a finite list of scalars ( α 1 , α 2 , … ) {\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )} , creates a string representing t...
#Go
Go
package main   import ( "fmt" "strings" )   func linearCombo(c []int) string { var sb strings.Builder for i, n := range c { if n == 0 { continue } var op string switch { case n < 0 && sb.Len() == 0: op = "-" case n < 0: ...
Give a code snippet in #Go Task Display a finite linear combination in an infinite vector basis ( e 1 , e 2 , … ) {\displaystyle (e_{1},e_{2},\ldots )} . Write a function that, when given a finite list of scalars ( α 1 , α 2 , … ) {\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )} , cre...
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Dart
Dart
main() { moveit(from,to) { print("move ${from} ---> ${to}"); }   hanoi(height,toPole,fromPole,usePole) { if (height>0) { hanoi(height-1,usePole,fromPole,toPole); moveit(fromPole,toPole); hanoi(height-1,toPole,usePole,fromPole); } }   hanoi(3,3,1,2); }
Give a code snippet in #Dart Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#Quackery
Quackery
[ $ "BOXKDQCPNAGTRETGQDFS" $ "JWHUVIANOBERFSLYPCZM" join ] constant is blocks ( --> $ )   [ -2 & tuck pluck drop swap pluck drop ] is remove2 ( $ n --> $ )   [ iff [ say "True" ] else [ say "False" ] ] is echotruth ( b --> )   [ true blocks rot witheach [ upper...
Give a code snippet in #Quackery ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alph...
christopher/rosetta-code
http://rosettacode.org/wiki/Go_Fish
Go Fish
Write a program to let the user play Go Fish against a computer opponent. Use the following rules: Each player is dealt nine cards to start with. On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more. If t...
#PicoLisp
PicoLisp
  Red [ Title: "Go Fish" Author: "gltewalt" ]   chand: []  ;-- c and p = computer and player cguesses: [] phand: [] cbooks: 0 pbooks: 0 gf: { *************** * GO FISH * *************** } pip: ["a" "2" "3" "4" "5" "6" "7" "8" "9" "10" "j" "q" "k"] ;-- suits are not relevant pile: []  ;-- whe...
Give a code snippet in #PicoLisp Write a program to let the user play Go Fish against a computer opponent. Use the following rules: Each player is dealt nine cards to start with. On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a...
christopher/rosetta-code
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The s...
#Pascal
Pascal
program Chowla_numbers;   {$IFDEF FPC} {$MODE Delphi} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF}   uses SysUtils {$IFDEF FPC} ,StrUtils{for Numb2USA} {$ENDIF} ;     {$IFNDEF FPC} function Numb2USA(const S: string): string; var I, NA: Integer; begin I := Length(S); Result := S; NA := 0; while (I > 0) do...
Give a code snippet in #Pascal Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n...
christopher/rosetta-code
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11...
#Python
Python
from collections import namedtuple from pprint import pprint as pp from math import floor   Stem = namedtuple('Stem', 'data, leafdigits')   data0 = Stem((12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122...
Give a code snippet in #Python Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37...
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#Groovy
Groovy
import java.util.function.Function   import static java.lang.Math.pow   class Test { static double calc(Function<Integer, Integer[]> f, int n) { double temp = 0   for (int ni = n; ni >= 1; ni--) { Integer[] p = f.apply(ni) temp = p[1] / (double) (p[0] + temp) } ...
Give a code snippet in #Groovy continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to wr...
christopher/rosetta-code
http://rosettacode.org/wiki/Elementary_cellular_automaton/Infinite_length
Elementary cellular automaton/Infinite length
The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer. To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state o...
#J
J
ext9=: (9#1-{.!.1),],9#1-{:!.1 trim=: |.@(}.~ ] i. 1-{.)^:2 next=: trim@(((8$2) #: [) {~ 2 #. 1 - [: |: |.~"1 0&_1 0 1@]) ext9
Give a code snippet in #J The purpose of this task is to create a version of an Elementary cellular automaton whose number of cells is only limited by the memory size of the computer. To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other wor...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#Ring
Ring
  n = 0 While True n++ See n + nl if n % 6 = 0 exit ok end  
Give a code snippet in #Ring Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Do...
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 ...
#Ada
Ada
with Ada.Text_IO; procedure Missing_Permutations is subtype Permutation_Character is Character range 'A' .. 'D';   Character_Count : constant := 1 + Permutation_Character'Pos (Permutation_Character'Last) - Permutation_Character'Pos (Permutation_Character'First);   type Permutation_String is ...
Give a code snippet in #Ada ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB ...
christopher/rosetta-code
http://rosettacode.org/wiki/Percolation/Site_percolation
Percolation/Site percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N...
#Python
Python
from random import random import string from pprint import pprint as pp   M, N, t = 15, 15, 100   cell2char = ' #' + string.ascii_letters NOT_VISITED = 1 # filled cell not walked   class PercolatedException(Exception): pass   def newgrid(p): return [[int(random() < p) for m in range(M)] for n in range(N)] # cel...
Give a code snippet in #Python Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean clu...
christopher/rosetta-code
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#Objective-C
Objective-C
NSMutableArray *funcs = [[NSMutableArray alloc] init]; for (int i = 0; i < 10; i++) { [funcs addObject:[^ { return i * i; } copy]]; }   int (^foo)(void) = funcs[3]; NSLog(@"%d", foo()); // logs "9"  
Give a code snippet in #Objective-C Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#Clojure
Clojure
(use 'clj-figlet.core) (println (render-to-string (load-flf "ftp://ftp.figlet.org/pub/figlet/fonts/contributed/larry3d.flf") "Clojure"))
Give a code snippet in #Clojure Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
christopher/rosetta-code
http://rosettacode.org/wiki/Esthetic_numbers
Esthetic numbers
An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic number. Nine and zero differ by 9. These examples are n...
#Sidef
Sidef
func generate_esthetic(root, upto, callback, b=10) {   var v = root.digits2num(b)   return nil if (v > upto) callback(v)   var t = root.head   __FUNC__([t+1, root...], upto, callback, b) if (t+1 < b) __FUNC__([t-1, root...], upto, callback, b) if (t-1 >= 0) }   func between_esthetic(from, upto,...
Give a code snippet in #Sidef An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic number. Nine and zero diff...
christopher/rosetta-code
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#Prolog
Prolog
  :- initialization(main).   % Simulate a play. play(Switch, Won) :- % Random prize door random(1, 4, P),   % Random contestant door random(1, 4, C),   % Random reveal door, not prize or contestant door repeat, random(1, 4, R), R \= P, R \= C, !,   % Final door ( ...
Give a code snippet in #Prolog Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for th...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Tailspin
Tailspin
  [1..351 -> \(when <?(351 mod $ <=0>)> do $! \)] -> !OUT::write  
Give a code snippet in #Tailspin 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 Operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#Swift
Swift
let inputs = [[], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]]   func quibbling(var words:[String]) { if words.count == 0 { println("{}") } else if words.count == 1 { println("{\(words[0])}") } else if words.count == 2 { println("{\(words[0]) and \(words[1])}") } else { ...
Give a code snippet in #Swift Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An in...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#Go
Go
package config   import ( "errors" "io" "fmt" "bytes" "strings" "io/ioutil" )   var ( ENONE = errors.New("Requested value does not exist") EBADTYPE = errors.New("Requested type and actual type do not match") EBADVAL = errors.New("Value and type do not match") )   type varError struct { err error n stri...
Give a code snippet in #Go The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ign...
christopher/rosetta-code
http://rosettacode.org/wiki/Make_directory_path
Make directory path
Task Create a directory and any missing parents. This task is named after the posix mkdir -p command, and several libraries which implement the same behavior. Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect. If the directory already exists, return succe...
#JavaScript
JavaScript
var path = require('path'); var fs = require('fs');   function mkdirp (p, cb) { cb = cb || function () {}; p = path.resolve(p);   fs.mkdir(p, function (er) { if (!er) { return cb(null); } switch (er.code) { case 'ENOENT': // The directory doesn...
Give a code snippet in #JavaScript Task Create a directory and any missing parents. This task is named after the posix mkdir -p command, and several libraries which implement the same behavior. Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect. If the di...
christopher/rosetta-code
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes
Partition an integer x into n primes
Task Partition a positive integer   X   into   N   distinct primes. Or, to put it in another way: Find   N   unique primes such that they add up to   X. Show in the output section the sum   X   and the   N   primes in ascending order separated by plus (+) signs: •   partition 99809 with 1 prime. ...
#C
C
#include <assert.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h>   typedef struct bit_array_tag { uint32_t size; uint32_t* array; } bit_array;   bool bit_array_create(bit_array* b, uint32_t size) { uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t)); if (array =...
Give a code snippet in #C Task Partition a positive integer   X   into   N   distinct primes. Or, to put it in another way: Find   N   unique primes such that they add up to   X. Show in the output section the sum   X   and the   N   primes in ascending order separated by plus (+) signs: •   partition ...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#BCPL
BCPL
get "libhdr"   let mulinv(a, b) = b<0 -> mulinv(a, -b), a<0 -> mulinv(b - (-a rem b), b), valof $( let t, nt, r, nr = 0, 1, b, a rem b until nr = 0 $( let tmp, q = ?, r / nr tmp := nt ; nt := t - q*nt ; t := tmp tmp := nr ; nr := r - q*nr ; r := tmp $) ...
Give a code snippet in #BCPL From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\d...
christopher/rosetta-code
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or f...
#Lua
Lua
-- load the smtp support local smtp = require("socket.smtp")   -- Connects to server "localhost" and sends a message to users -- "fulano@example.com", "beltrano@example.com", -- and "sicrano@example.com". -- Note that "fulano" is the primary recipient, "beltrano" receives a -- carbon copy and neither of them knows th...
Give a code snippet in #Lua Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. S...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_frequency
Word frequency
Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a   letter   is.   Undersc...
#AppleScript
AppleScript
(* For simplicity here, words are considered to be uninterrupted sequences of letters and/or digits. The set text is too messy to warrant faffing around with anything more sophisticated. The first letter in each word is upper-cased and the rest lower-cased for case equivalence and presentation. Where mo...
Give a code snippet in #AppleScript Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to def...
christopher/rosetta-code
http://rosettacode.org/wiki/Variadic_function
Variadic function
Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Functions. Related task   Call a function...
#Visual_Basic
Visual Basic
Option Explicit '-------------------------------------------------- Sub varargs(ParamArray a()) Dim n As Long, m As Long Debug.Assert VarType(a) = (vbVariant Or vbArray) For n = LBound(a) To UBound(a) If IsArray(a(n)) Then For m = LBound(a(n)) To UBound(a(n)) Debug.Print a(n)...
Give a code snippet in #Visual_Basic Task Create a function which takes in a variable number of arguments and prints each one on its own line. Also show, if possible in your language, how to call the function on a list of arguments constructed at runtime. Functions of this type are also known as Variadic Function...
christopher/rosetta-code
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Forth
Forth
s" input.txt" delete-file throw s" /input.txt" delete-file throw
Give a code snippet in #Forth Task Delete a file called "input.txt" and delete a 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/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 ...
#PowerShell
PowerShell
  $source = @' using System; using System.Collections.Generic;   namespace Powershell { public class CSharp { public static IEnumerable<int[]> Combinations(int m, int n) { int[] result = new int[m]; Stack<int> stack = new Stack<int>...
Give a code snippet in #PowerShell 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#Wren
Wren
import "io" for File   var checkNoSpaces = Fn.new { |s| !s.contains(" ") && !s.contains("\t") }   var first = true   var process = Fn.new { |line| if (line[0] == ">") { if (!first) System.print() System.write("%(line[1..-1]): ") if (first) first = false } else if (first) { Fiber....
Give a code snippet in #Wren In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosett...
christopher/rosetta-code
http://rosettacode.org/wiki/Shell_one-liner
Shell one-liner
Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different comman...
#R
R
$ echo 'cat("Hello\n")' | R --slave Hello
Give a code snippet in #R Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations ...
christopher/rosetta-code
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#ALGOL_68
ALGOL 68
# procedure to find the longest rep-string in a given string # # the input string is not validated to contain only "0" and "1" characters # PROC longest rep string = ( STRING input )STRING: BEGIN   STRING result := "";   # ensure the string we are working on has a lower-bound of 1 ...
Give a code snippet in #ALGOL_68 Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at l...
christopher/rosetta-code
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#F.C5.8Drmul.C3.A6
Fōrmulæ
Public Sub Main() Dim iNum As Long   For iNum = 1 To 100000 If Str(iNum * iNum) Ends "269696" Then Break Next   Print "The lowest number squared that ends in '269696' is " & Str(iNum)   End
Give a code snippet in #F.C5.8Drmul.C3.A6 Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Ele...
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...
#C.2B.2B
C++
#include <cassert> #include <cstdlib> #include <iostream> #include <stdexcept> #include <utility> #include <vector>   #include <libxml/parser.h> #include <libxml/tree.h> #include <libxml/xmlerror.h> #include <libxml/xmlstring.h> #include <libxml/xmlversion.h> #include <libxml/xpath.h>   #ifndef LIBXML_XPATH_ENABLED # ...
Give a code snippet in #C.2B.2B 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/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#F.23
F#
let next = string( int( "1234" ) + 1 )
Give a code snippet in #F.23 Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Web_scraping
Web scraping
Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page. If possible,...
#Common_Lisp
Common Lisp
BOA> (let* ((url "http://tycho.usno.navy.mil/cgi-bin/timer.pl") (regexp (load-time-value (cl-ppcre:create-scanner "(?m)^.{4}(.+? UTC)"))) (data (drakma:http-request url))) (multiple-value-bind (start end start-regs end-regs) (cl-ppcre:scan regexp data) ...
Give a code snippet in #Common_Lisp Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off t...
christopher/rosetta-code