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/Quoting_constructs
Quoting constructs
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof. Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitati...
#Wren
Wren
import "/fmt" for Fmt   // simple string literal System.print("Hello world!")   // string literal including an escape sequence System.print("Hello tabbed\tworld!")   // interpolated string literal var w = "world" System.print("Hello interpolated %(w)!")   // 'printf' style Fmt.print("Hello 'printf' style $s!", w)   // ...
Give a code snippet in #Wren Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof. Show examples of the quoting constructs in your language. Explain where they would likely be used, what their...
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#MiniScript
MiniScript
isLeapYear = function(year) return year%4==0 and (year % 100 or not year % 400) end function
Give a code snippet in #MiniScript Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an...
#Racket
Racket
  #lang racket   (define A (set 1 2 3 4)) (define B (set 3 4 5 6)) (define C (set 4 5))   (set-union A B)  ; gives (set 1 2 3 4 5 6) (set-intersect A B) ; gives (set 3 4) (set-subtract A B)  ; gives (set 1 2) (set=? A B)  ; gives #f (subset? C A)  ; gives #f (subset? C B)  ; gives #t  
Give a code snippet in #Racket Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set ...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming langu...
#Julia
Julia
using Primes, Printf   println("Primes ≤ $hi written in common bases.") @printf("%8s%8s%8s%8s", "bin", "oct", "dec", "hex") for i in primes(50) @printf("%8s%8s%8s%8s\n", bin(i), oct(i), dec(i), hex(i)) end  
Give a code snippet in #Julia Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard rou...
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#BCPL
BCPL
get "libhdr"   let sumdigitsq(n) = n=0 -> 0, (n rem 10)*(n rem 10)+sumdigitsq(n/10)   let happy(n) = valof $( let seen = vec 255 for i = 0 to 255 do i!seen := false $( n!seen := true n := sumdigitsq(n) $) repeatuntil n!seen resultis 1!seen $)   let start() be $( let n, i = 0, 0 while...
Give a code snippet in #BCPL From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly i...
christopher/rosetta-code
http://rosettacode.org/wiki/Validate_International_Securities_Identification_Number
Validate International Securities Identification Number
An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct format,   and   the embedded c...
#Lua
Lua
function luhn (n) local revStr, s1, s2, digit, mod = n:reverse(), 0, 0 for pos = 1, #revStr do digit = tonumber(revStr:sub(pos, pos)) if pos % 2 == 1 then s1 = s1 + digit else digit = digit * 2 if digit > 9 then mod = digit % 10 ...
Give a code snippet in #Lua An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. Task Write a function or program that takes a string as input, and checks whether it is a valid ISIN. It is only valid if it has the correct f...
christopher/rosetta-code
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octa...
#Kotlin
Kotlin
// Kotlin Native v0.3   import kotlinx.cinterop.* import win32.*   fun main(args: Array<String>) { val freqs = intArrayOf(262, 294, 330, 349, 392, 440, 494, 523) // CDEFGABc val dur = 500 repeat(5) { for (freq in freqs) Beep(freq, dur) } }
Give a code snippet in #Kotlin Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, M...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_join
Hash join
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash join" algorithm, and demonstrate tha...
#Forth
Forth
  include FMS-SI.f include FMS-SILib.f   \ Since the same join attribute, Name, occurs more than once \ in both tables for this problem we need a hash table that \ will accept and retrieve multiple identical keys if we want \ an efficient solution for large tables. We make use \ of the hash collision handling feature o...
Give a code snippet in #Forth An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash join"...
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#Picat
Picat
go => println(happy_len(8)).   happy(N) => S = [N], Happy = 1, while (Happy == 1, N > 1) N := sum([to_integer(I)**2 : I in N.to_string()]), if member(N,S) then Happy := 0 else S := S ++ [N] end end, Happy == 1.   happy_len(Limit) = S => S = [], N = 1, whil...
Give a code snippet in #Picat From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#EchoLisp
EchoLisp
  (define (fib n) (if (< n 2) n (+ (fib (- n 2)) (fib (1- n)))))   (remember 'fib #(0 1))   (for ((i 12)) (write (fib i))) 0 1 1 2 3 5 8 13 21 34 55 89  
Give a code snippet in #EchoLisp The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions ...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Pythagorean_means
Averages/Pythagorean means
Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})} for this set of p...
#JavaScript
JavaScript
(function () { 'use strict';   // arithmetic_mean :: [Number] -> Number function arithmetic_mean(ns) { return ( ns.reduce( // sum function (sum, n) { return (sum + n); }, 0 ) / ns.length ); }   ...
Give a code snippet in #JavaScript Task[edit] Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive). Show that A ( x 1 , … , x n ) ≥ G ( x 1 , … , x n ) ≥ H ( x 1 , … , x n ) {\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1}...
christopher/rosetta-code
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Tcl
Tcl
package require Tk 8.5 set curWindow [lindex [wm stackorder .] end] # Everything below will work with anything from Tk 8.0 onwards set x [expr {[winfo pointerx .] - [winfo rootx $curWindow]}] set y [expr {[winfo pointery .] - [winfo rooty $curWindow]}] tk_messageBox -message "the mouse is at ($x,$y) in window $curWindo...
Give a code snippet in #Tcl Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
christopher/rosetta-code
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Frege
Frege
module FractalTree where   import Java.IO import Prelude.Math   data AffineTransform = native java.awt.geom.AffineTransform where native new :: () -> STMutable s AffineTransform native clone :: Mutable s AffineTransform -> STMutable s AffineTransform native rotate :: Mutable s AffineTransform -> Double -> ST s ()...
Give a code snippet in #Frege Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#360_Assembly
360 Assembly
X DS F Y DS F Z DS F
Give a code snippet in #360_Assembly Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function wi...
christopher/rosetta-code
http://rosettacode.org/wiki/String_append
String append
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 |...
#Forth
Forth
\ Strings in Forth are simply named memory locations   create astring 256 allot \ create a "string"   s" Hello " astring PLACE \ initialize the string   s" World!" astring +PLACE \ append with "+place"
Give a code snippet in #Forth Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations ...
christopher/rosetta-code
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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 Miller–Rabin primality test or Rabin–Miller prima...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i";   const func boolean: millerRabin (in bigInteger: n, in integer: k) is func result var boolean: probablyPrime is TRUE; local var bigInteger: d is 0_; var integer: r is 0; var integer: s is 0; var bigInteger: a is 0_; var bigInteger: x is 0_; ...
Give a code snippet in #Seed7 This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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 Miller–Rabin prima...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT ERROR/STOP OPEN ("rosetta.txt",READ,-std-) var=FILE ("rosetta.txt")  
Give a code snippet in #TUSCRIPT Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished in...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function romanDecode(roman As Const String) As Integer If roman = "" Then Return 0 '' zero denotes invalid roman number Dim roman1(0 To 2) As String = {"MMM", "MM", "M"} Dim roman2(0 To 8) As String = {"CM", "DCCC", "DCC", "DC", "D", "CD", "CCC", "CC", "C"} Dim roman3(0 To 8) As String = {"...
Give a code snippet in #FreeBASIC Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,...
christopher/rosetta-code
http://rosettacode.org/wiki/Formal_power_series
Formal power series
A power series is an infinite sum of the form a 0 + a 1 ⋅ x + a 2 ⋅ x 2 + a 3 ⋅ x 3 + ⋯ {\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots } The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of ...
#Common_Lisp
Common Lisp
(defpackage #:formal-power-series (:nicknames #:fps) (:use "COMMON-LISP") (:shadow #:+ #:- #:* #:/))   (in-package #:formal-power-series)
Give a code snippet in #Common_Lisp A power series is an infinite sum of the form a 0 + a 1 ⋅ x + a 2 ⋅ x 2 + a 3 ⋅ x 3 + ⋯ {\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots } The ai are called the coefficients of the series. Such sums can be added, multiplied...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
Sorting algorithms/Sleep 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 ...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary import java.util.concurrent.CountDownLatch   -- ============================================================================= class RSortingSleepsort properties constant private dflt = '-6 3 1 4 5 2 3 -7 1 6 001 3 -9 2 5 -009 -8 4 6 1 9 ...
Give a code snippet in #NetRexx 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#z.2FArch_Assembler
z/Arch Assembler
* Binary search BINSRCH LA R5,TABLE Begin of table SR R2,R2 low = 0 LA R3,ENTRIES-1 high = N-1 LOOP CR R2,R3 while (low <= high) JH NOTFOUND { ...
Give a code snippet in #z.2FArch_Assembler A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer h...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#Java
Java
  import com.objectwave.utility.*;   public class MultiCombinationsTester {   public MultiCombinationsTester() throws CombinatoricException { Object[] objects = {"iced", "jam", "plain"}; //Object[] objects = {"abba", "baba", "ab"}; //Object[] objects = {"aaa", "aa", "a"}; //Object[] ...
Give a code snippet in #Java The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of t...
christopher/rosetta-code
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#Alore
Alore
def Main() var len as Int var result as Str result = Str(5**4**3**2) len = result.length() Print(len) Print(result[:20]) Print(result[len-20:]) end
Give a code snippet in #Alore Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
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.
#Ring
Ring
  decimals(12) see "cube root of 5 is : " + root(3, 5, 0) + nl   func root n, a, d y = 0 x = a / n while fabs (x - y) > d y = ((n - 1)*x + a/pow(x,(n-1))) / n temp = x x = y y = temp end return x  
Give a code snippet in #Ring 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/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#Java
Java
public class IntegerLiterals { public static void main(String[] args) { System.out.println( 727 == 0x2d7 && 727 == 01327 ); } }
Give a code snippet in #Java Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Nanoquery
Nanoquery
print "Number 1: " x = int(input()) print "Number 2: " y = int(input())   println format("Sum: %d", x + y) println format("Difference: %d", x - y) println format("Product: %d", x * y) println format("Quotient: %f", x / y)   println format("Remainder: %d", x % y) println format("Power: %d", x ^ y)
Give a code snippet in #Nanoquery Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operati...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays 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_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#Scala
Scala
object FindTheLastSundayOfEachMonth extends App { import java.util.Calendar._ val cal = getInstance   def lastSundaysOf(year: Int) = (JANUARY to DECEMBER).map{month => cal.set(year, month + 1, 1) // first day of next month (1 to 7).find{_ => cal.add(DAY_OF_MONTH, -1); cal.get(DAY_OF_WEEK) == SUNDA...
Give a code snippet in #Scala Write a program or a script that returns the last Sundays 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_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 201...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly...
#Julia
Julia
using Primes   numfactors(n) = reduce(*, e+1 for (_,e) in factor(n); init=1)   A005179(n) = findfirst(k -> numfactors(k) == n, 1:typemax(Int))   println("The first 15 terms of the sequence are:") println(map(A005179, 1:15))  
Give a code snippet in #Julia Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Se...
christopher/rosetta-code
http://rosettacode.org/wiki/Play_recorded_sounds
Play recorded sounds
Load at least two prerecorded sounds, and demonstrate as many of these features as you can: playing them individually and simultaneously stopping before the end of the sound looping (preferably glitch-free) setting the volume of each sound stereo or 3D positional mixing performing other actions when marked times...
#VBA
VBA
  Declare Function libPlaySound Lib "winmm.dll" Alias "sndPlaySoundA" _ (ByVal filename As String, ByVal Flags As Long) As Long   Sub PlaySound(sWav As String) Call libPlaySound(sWav, 1) '1 to play asynchronously End Sub  
Give a code snippet in #VBA Load at least two prerecorded sounds, and demonstrate as many of these features as you can: playing them individually and simultaneously stopping before the end of the sound looping (preferably glitch-free) setting the volume of each sound stereo or 3D positional mixing performing ot...
christopher/rosetta-code
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In ...
#D
D
import std.stdio, std.bigint, std.algorithm, std.range, core.memory;   auto hamming(in uint n) pure nothrow /*@safe*/ { immutable BigInt two = 2, three = 3, five = 5; auto h = new BigInt[n]; h[0] = 1; BigInt x2 = 2, x3 = 3, x5 = 5; size_t i, j, k;   foreach (ref el; h.dropOne) { el = min...
Give a code snippet in #D Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers,...
christopher/rosetta-code
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#Perl
Perl
use warnings; # use warnings pragma module use strict; # use strict pragma module
Give a code snippet in #Perl Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate ...
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...
#Sidef
Sidef
func map_range(a, b, x) { var (a1, a2, b1, b2) = (a.bounds, b.bounds); x-a1 * b2-b1 / a2-a1 + b1; }   var a = 0..10; var b = -1..0;   for x in a { say "#{x} maps to #{map_range(a, b, x)}"; }
Give a code snippet in #Sidef Given two ranges:   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   and   [ b 1 , b 2 ] {\displaystyle [b_{1},b_{2}]} ;   then a value   s {\displaystyle s}   in range   [ a 1 , a 2 ] {\displaystyle [a_{1},a_{2}]}   is linearly m...
christopher/rosetta-code
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed positi...
#Raku
Raku
class Automaton { has $.rule; has @.cells; has @.code = $!rule.fmt('%08b').flip.comb».Int;   method gist { "|{ @!cells.map({+$_ ?? '#' !! ' '}).join }|" }   method succ { self.new: :$!rule, :@!code, :cells( @!code[ 4 «*« @!cells.rotate(-1)  »+«...
Give a code snippet in #Raku Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting suc...
christopher/rosetta-code
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#Gambas
Gambas
Public Sub Main() Dim byKey As Byte = 3 'The key (Enter 26 to get the same output as input) Dim byCount As Byte 'Counter Dim sCeasar As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQR...
Give a code snippet in #Gambas Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z t...
christopher/rosetta-code
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers
Chernick's Carmichael numbers
In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1: U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1) is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4). Example U(3, m) = (6m + 1) * (12m + 1) * (18m + 1) U(4, m) = U(3, m) * (2^2 * 9m + 1)...
#Perl
Perl
use 5.020; use warnings; use ntheory qw/:all/; use experimental qw/signatures/;   sub chernick_carmichael_factors ($n, $m) { (6*$m + 1, 12*$m + 1, (map { (1 << $_) * 9*$m + 1 } 1 .. $n-2)); }   sub chernick_carmichael_number ($n, $callback) {   my $multiplier = ($n > 4) ? (1 << ($n-4)) : 1;   for (my $m = 1...
Give a code snippet in #Perl In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1: U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1) is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4). Example U(3, m) = (6m + 1) * (12m + 1) * (18m + 1) U(4,...
christopher/rosetta-code
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume t...
#R
R
integ <- function(f, a, b, n, u, v) { h <- (b - a) / n s <- 0 for (i in seq(0, n - 1)) { s <- s + sum(v * f(a + i * h + u * h)) } s * h }   test <- function(f, a, b, n) { c(rect.left = integ(f, a, b, n, 0, 1), rect.right = integ(f, a, b, n, 1, 1), rect.mid = integ(f, a, b, n, 0.5, 1), trapez...
Give a code snippet in #R Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make i...
christopher/rosetta-code
http://rosettacode.org/wiki/Problem_of_Apollonius
Problem of Apollonius
Task Implement a solution to the Problem of Apollonius   (description on Wikipedia)   which is the problem of finding the circle that is tangent to three specified circles   (colored black in the diagram below to the right). There is an   algebraic solution   which is pretty straightforward. The solutions to the ...
#Scala
Scala
object ApolloniusSolver extends App { case class Circle(x: Double, y: Double, r: Double) object Tangent extends Enumeration { type Tangent = Value val intern = Value(-1) val extern = Value(1) }   import Tangent._ import scala.Math._   val solveApollonius: (Circle, Circle, Circle, Triple[Tangent, Tangent,...
Give a code snippet in #Scala Task Implement a solution to the Problem of Apollonius   (description on Wikipedia)   which is the problem of finding the circle that is tangent to three specified circles   (colored black in the diagram below to the right). There is an   algebraic solution   which is pretty straightfo...
christopher/rosetta-code
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#Ruby
Ruby
def game_of_life(name, size, generations, initial_life=nil) board = new_board size seed board, size, initial_life print_board board, name, 0 reason = generations.times do |gen| new = evolve board, size print_board new, name, gen+1 break :all_dead if barren? new, size break :static if board == ...
Give a code snippet in #Ruby The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 ...
#Groovy
Groovy
def fs = { fn, values -> values.collect { fn(it) } } def f1 = { v -> v * 2 } def f2 = { v -> v ** 2 } def fsf1 = fs.curry(f1) def fsf2 = fs.curry(f2)
Give a code snippet in #Groovy Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original functi...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversa...
#F.23
F#
let rand = System.Random()   while true do let rec randomNums() = let xs = [|for i in 1..9 -> rand.Next(), i|] |> Array.sort |> Array.map snd if xs = Array.sort xs then randomNums() else xs   let xs = randomNums()   let suffix = function | 1 -> "st" | 2 -> "nd" | 3 -> "rd" | _ -> "th"   let rec move i =...
Give a code snippet in #F.23 Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The sco...
christopher/rosetta-code
http://rosettacode.org/wiki/Operator_precedence
Operator precedence
This page uses content from Wikipedia. The original article was at Operators in C and C++. 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 Provide a list of   precedence   and   associativity...
#BQN
BQN
3 * 2 + 1
Give a code snippet in #BQN This page uses content from Wikipedia. The original article was at Operators in C and C++. 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 Provide a list of   pre...
christopher/rosetta-code
http://rosettacode.org/wiki/Honeycombs
Honeycombs
The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position...
#Prolog
Prolog
honeycomb :- new(W, window('Honeycomb')), new(Counter, counter(20)), new(Ph, phrase(W, point(50,500))), send(W, recogniser, new(KB, key_binding(@nil, argument))), numlist(0, 19, NL), create_letters(20, [], LL), maplist(build_list(150,100), NL, LP), new(ChCell, chain), maplist(create_cell(W, Counter, Ph,...
Give a code snippet in #Prolog The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two ...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#REBOL
REBOL
rebol [ Title: "12x12 Multiplication Table" URL: http://rosettacode.org/wiki/Print_a_Multiplication_Table ]   size: 12   ; Because of REBOL's GUI focus, it doesn't really do pictured output, ; so I roll my own. See Formatted_Numeric_Output for more ; comprehensive version:   pad: func [pad n][ n: to-string n ...
Give a code snippet in #REBOL Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#GW-BASIC
GW-BASIC
1 DEFINT A-W : DEFDBL X-Z : DIM D(9) : DIM X2(9) : KEY OFF : CLS 2 FOR A = 0 TO 9 : X2(A) = A : NEXT A 3 FOR N = 1 TO 7 4 FOR N9 = N TO 0 STEP -1 5 FOR N8 = N-N9 TO 0 STEP -1 6 FOR N7 = N-N9-N8 TO 0 STEP -1 7 FOR N6 = N-N9-N8-N7 TO 0 STEP -1 8 FOR N5 = N-N9-N8-N7-N6 TO 0 STEP -1 9 FOR N4 = N-N9-N8-N7-N6-N5 TO 0 STEP -1...
Give a code snippet in #GW-BASIC A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle...
christopher/rosetta-code
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#AutoHotkey
AutoHotkey
h := A_ScreenHeight w := A_ScreenWidth pToken := gdip_Startup() hdc := CreateCompatibleDC() hbm := CreateDIBSection(w, h) obm := SelectObject(hdc, hbm) G := Gdip_GraphicsFromHDC(hdc)   OnExit, Exit   Gui +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop hwnd := WinExist() Gui Show, NA   columnHeight := h/4   Loop 4 ...
Give a code snippet in #AutoHotkey The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Swift
Swift
func insertionSort<T:Comparable>(inout list:[T]) { for i in 1..<list.count { var j = i   while j > 0 && list[j - 1] > list[j] { swap(&list[j], &list[j - 1]) j-- } } }
Give a code snippet in #Swift Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick so...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Swift
Swift
  import Foundation   func lastFridays(of year: Int) -> [Date] {   let calendar = Calendar.current var dates = [Date]()   for month in 2...13 {   let lastDayOfMonth = DateComponents(calendar: calendar, year: year, month: month, ...
Give a code snippet in #Swift 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Flow-control_structures
Flow-control structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   construct. Note that   Conditional Struc...
#Relation
Relation
call routineName /*no arguments passed to routine.*/ call routineName 50 /*one argument (fifty) passed. */ call routineName 50,60 /*two arguments passed. */ call routineName 50, 60 /*(same as above) */ call routineName 5...
Give a code snippet in #Relation Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task Document common flow-control structures. One common example of a flow-control structure is the   goto   constru...
christopher/rosetta-code
http://rosettacode.org/wiki/Update_a_configuration_file
Update a configuration file
We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non comment line is the configurati...
#Erlang
Erlang
  -module( update_configuration_file ).   -export( [add/3, change/3, disable/2, enable/2, read/1, task/0, write/2] ).   add( Option, Value, Lines ) -> Upper = string:to_upper( Option ), [string:join( [Upper, Value], " " ) | Lines].   change( Option, Value, Lines ) -> Upper = string:to_upper( Option ), change_done( ...
Give a code snippet in #Erlang We have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines begininning with a hash or a semicolon are ignored by the application # program. Blank lines are also ignored by the application program. # The first word on each non...
christopher/rosetta-code
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#C.23
C#
using System; using System.IO;   Console.WriteLine(File.GetLastWriteTime("file.txt")); File.SetLastWriteTime("file.txt", DateTime.Now);
Give a code snippet in #C.23 Task Get and set the modification time of a file.
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#Monte
Monte
  while (true): traceln("SPAM")  
Give a code snippet in #Monte Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loop...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Phix
Phix
function sum_digits(integer n, integer base) integer res = 0 while n do res += remainder(n,base) n = floor(n/base) end while return res end function ?sum_digits(1,10) ?sum_digits(1234,10) ?sum_digits(#FE,16) ?sum_digits(#F0E,16)
Give a code snippet in #Phix Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
christopher/rosetta-code
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#Picat
Picat
main(ARGS) => println(ARGS). main(_) => true.
Give a code snippet in #Picat Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
christopher/rosetta-code
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers...
#8086_Assembly
8086 Assembly
;;; ------------------------------------------------------------- ;;; SUBLEQ interpreter that runs under MS-DOS. ;;; The word size is 16 bits, and the SUBLEQ program gets a 64KB ;;; (that is, 32K Subleq words) address space. ;;; The SUBLEQ program is read from a text file given on the ;;; command line, I/O is do...
Give a code snippet in #8086_Assembly Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an arr...
christopher/rosetta-code
http://rosettacode.org/wiki/String_matching
String matching
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Euphoria
Euphoria
sequence first, second integer x   first = "qwertyuiop"   -- Determining if the first string starts with second string second = "qwerty" if match(second, first) = 1 then printf(1, "'%s' starts with '%s'\n", {first, second}) else printf(1, "'%s' does not start with '%s'\n", {first, second}) end if   -- Determini...
Give a code snippet in #Euphoria 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/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat...
#C.2B.2B
C++
#include <iterator> #include <utility> #include <algorithm> #include <list> #include <iostream>   // helper struct template<typename T> struct referring { referring(T const& t): value(t) {} template<typename Iter> bool operator()(std::pair<Iter, int> const& p) const { return *p.first == value; } T cons...
Give a code snippet in #C.2B.2B Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if ...
christopher/rosetta-code
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#11l
11l
V phrase = ‘rosetta code phrase reversal’ print(reversed(phrase)) print(phrase.split(‘ ’).map(word -> reversed(word)).join(‘ ’)) print(reversed(phrase.split(‘ ’)).join(‘ ’))
Give a code snippet in #11l Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each ...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#Go
Go
package main   import "fmt" import "io/ioutil" import "log" import "os" import "regexp" import "strings"   func main() { err := fix() if err != nil { log.Fatalln(err) } }   func fix() (err error) { buf, err := ioutil.ReadAll(os.Stdin) if err != nil { return err } out, err := Lang(string(buf)) if err != nil ...
Give a code snippet in #Go Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#Haskell
Haskell
import Text.Printf main = printf "%09.3f" 7.125
Give a code snippet in #Haskell Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/Zumkeller_numbers
Zumkeller numbers
Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the divisors are partitioned, only that ...
#Ring
Ring
  load "stdlib.ring"   see "working..." + nl see "The first 220 Zumkeller numbers are:" + nl   permut = [] zumind = [] zumodd = [] limit = 19305 num1 = 0 num2 = 0   for n = 2 to limit zumkeller = [] zumList = [] permut = [] calmo = [] zumind = [] num = 0 nold = 0 for m = 1 to n i...
Give a code snippet in #Ring Zumkeller numbers are the set of numbers whose divisors can be partitioned into two disjoint sets that sum to the same value. Each sum must contain divisor values that are not in the other sum, and all of the divisors must be in one or the other. There are no restrictions on how the diviso...
christopher/rosetta-code
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#jq
jq
def sigma( stream ): reduce stream as $x (0; . + $x ) ;   def ismunchausen: def digits: tostring | split("")[] | tonumber; . == sigma(digits | pow(.;.));   # Munchausen numbers from 1 to 5000 inclusive: range(1;5001) | select(ismunchausen)
Give a code snippet in #jq A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see Th...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Vlang
Vlang
fn insertion(mut arr []int) { for i in 1 .. arr.len { value := arr[i] mut j := i - 1 for j >= 0 && arr[j] > value { arr[j + 1] = arr[j] j-- } arr[j + 1] = value } }   fn main() { mut arr := [4, 65, 2, -31, 0, 99, 2, 83, 782, 1] println('Input: ' + arr.str()) insertion(mut arr) println('Output: ' +...
Give a code snippet in #Vlang Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick so...
christopher/rosetta-code
http://rosettacode.org/wiki/Hilbert_curve
Hilbert curve
Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
#Racket
Racket
#lang racket   (require racket/draw)   (define rules '([A . (- B F + A F A + F B -)] [B . (+ A F - B F B - F A +)]))   (define (get-cmds n cmd) (cond [(= 0 n) (list cmd)] [else (append-map (curry get-cmds (sub1 n)) (dict-ref rules cmd (list cmd)))]))   (define (make-curve...
Give a code snippet in #Racket Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associativ...
#Arturo
Arturo
details: #[name: "Rocket Skates" price: 12.75 colour: 'yellow] newDetails: extend details #[price: 15.25 colour: 'red year: 1974]   print newDetails
Give a code snippet in #Arturo Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 M...
christopher/rosetta-code
http://rosettacode.org/wiki/Idiomatically_determine_all_the_lowercase_and_uppercase_letters
Idiomatically determine all the lowercase and uppercase letters
Idiomatically determine all the lowercase and uppercase letters   (of the Latin [English] alphabet)   being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). Task requirements Display the set of...
#Phix
Phix
sequence lc = {}, uc = {} for ch=1 to 255 do if islower(ch) then lc &= ch end if if isupper(ch) then uc &= ch end if end for lc = utf32_to_utf8(lc)&"\n" uc = utf32_to_utf8(uc)&"\n" puts(1,lc) puts(1,uc)
Give a code snippet in #Phix Idiomatically determine all the lowercase and uppercase letters   (of the Latin [English] alphabet)   being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). Task r...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Scheme
Scheme
(define (fib-iter n) (do ((num 2 (+ num 1)) (fib-prev 1 fib) (fib 1 (+ fib fib-prev))) ((>= num n) fib)))
Give a code snippet in #Scheme The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions ar...
christopher/rosetta-code
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneous...
#Standard_ML
Standard ML
(* Maximilian Wuttke 12.04.2016 *)   type world = char vector vector   fun getstate (w:world, (x, y)) = (Vector.sub (Vector.sub (w, y), x)) handle Subscript => #" "   fun conductor (w:world, (x, y)) = let val s = [getstate (w, (x-1, y-1)) = #"H", getstate (w, (x-1, y)) = #"H", getstate (w, (x-1, y+1)) = #"H", ...
Give a code snippet in #Standard_ML Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays 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_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#Groovy
Groovy
enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat static Day valueOf(Date d) { Day.valueOf(d.format('EEE')) } }   def date = Date.&parse.curry('yyyy-MM-dd') def month = { it.format('MM') } def days = { year -> (date("${year}-01-01")..<date("${year+1}-01-01")) } def weekDays = { dayOfWeek, year -> days(year).findAll ...
Give a code snippet in #Groovy Write a program or a script that returns the last Sundays 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_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 20...
christopher/rosetta-code
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
E Pi Sqrt[x] Log[x] Log[b,x] Exp[x] Abs[x] Floor[x] Ceiling[x] Power[x, y]
Give a code snippet in #Mathematica.2FWolfram_Language Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   ab...
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo...
#Lua
Lua
local ANIMALS = {"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"} local ELEMENTS = {"Wood","Fire","Earth","Metal","Water"}   function element(year) local idx = math.floor(((year - 4) % 10) / 2) return ELEMENTS[idx + 1] end   function animal(year) local idx = (year ...
Give a code snippet in #Lua Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results ...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#Julia
Julia
using Combinatorics   l = ["iced", "jam", "plain"] println("List: ", l, "\nCombinations:") for c in with_replacement_combinations(l, 2) println(c) end   @show length(with_replacement_combinations(1:10, 3))
Give a code snippet in #Julia The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of ...
christopher/rosetta-code
http://rosettacode.org/wiki/MD5
MD5
Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wikipedia article. Warning:...
#E
E
def makeMessageDigest := <import:java.security.makeMessageDigest> def sprintf := <import:java.lang.makeString>.format   def digest := makeMessageDigest.getInstance("MD5") \ .digest("The quick brown fox jumped over the lazy dog's back".getBytes("iso-8859-1"))   for b in digest { print(sprintf("%02x", [b])) } println...
Give a code snippet in #E Task Encode a string using an MD5 algorithm.   The algorithm can be found on   Wikipedia. Optionally, validate your implementation by running all of the test values in   IETF RFC (1321)   for MD5. Additionally,   RFC 1321   provides more precise information on the algorithm than the Wiki...
christopher/rosetta-code
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute z...
#MiniScript
MiniScript
fromKelvin = function(temp) print temp + " degrees in Kelvin is:" Celsius = temp - 273.15 print Celsius + " degrees Celsius" Fahrenheit = round(Celsius * 9/5 + 32,2) print Fahrenheit + " degrees Fahrenheit" Rankine = Fahrenheit + 459.67 print Rankine + " degrees Rankine" end function   temp...
Give a code snippet in #MiniScript There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 27...
christopher/rosetta-code
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In ...
#Wren
Wren
import "/big" for BigInt, BigInts   var primes = [2, 3, 5].map { |p| BigInt.new(p) }.toList   var hamming = Fn.new { |size| if (size < 1) Fiber.abort("size must be at least 1") var ns = List.filled(size, null) ns[0] = BigInt.one var next = primes.toList var indices = List.filled(3, 0) for (m in ...
Give a code snippet in #Wren Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbe...
christopher/rosetta-code
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
Ramer-Douglas-Peucker line simplification
Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Task Using the   Ramer–Douglas–P...
#Wren
Wren
import "/dynamic" for Tuple   var Point = Tuple.create("Point", ["x", "y"])   var rdp // recursive rdp = Fn.new { |l, eps| var x = 0 var dMax = -1 var p1 = l[0] var p2 = l[-1] var x21 = p2.x - p1.x var y21 = p2.y - p1.y var i = 0 for (p in l[1..-1]) { var d = (y21*p.x - x21*p.y +...
Give a code snippet in #Wren Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Tas...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Phix
Phix
with javascript_semantics function matrix_mul(sequence a, b) integer {ha,wa,hb,wb} = apply({a,a[1],b,b[1]},length) if wa!=hb then crash("invalid aguments") end if sequence c = repeat(repeat(0,wb),ha) for i=1 to ha do for j=1 to wb do for k=1 to wa do c[i][j] += a[i][k...
Give a code snippet in #Phix Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Voronoi_diagram
Voronoi diagram
A Voronoi diagram is a diagram consisting of a number of sites. Each Voronoi site s also has a Voronoi cell consisting of all points closest to s. Task Demonstrate how to generate and display a Voroni diagram. See algo K-means++ clustering.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "draw.s7i"; include "keybd.s7i";   const type: point is new struct var integer: xPos is 0; var integer: yPos is 0; var color: col is black; end struct;   const proc: generateVoronoiDiagram (in integer: width, in integer: height, in integer: numCells) is func local ...
Give a code snippet in #Seed7 A Voronoi diagram is a diagram consisting of a number of sites. Each Voronoi site s also has a Voronoi cell consisting of all points closest to s. Task Demonstrate how to generate and display a Voroni diagram. See algo K-means++ clustering.
christopher/rosetta-code
http://rosettacode.org/wiki/Cuban_primes
Cuban primes
The name   cuban   has nothing to do with   Cuba  (the country),   but has to do with the fact that cubes   (3rd powers)   play a role in its definition. Some definitions of cuban primes   primes which are the difference of two consecutive cubes.   primes of the form:   (n+1)3 - n3.   primes of the form:   n3 - ...
#C
C
#include <limits.h> #include <math.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h>   typedef long long llong_t; struct PrimeArray { llong_t *ptr; size_t size; size_t capacity; };   struct PrimeArray allocate() { struct PrimeArray primes;   primes.size = 0; primes.capacity = 10; ...
Give a code snippet in #C The name   cuban   has nothing to do with   Cuba  (the country),   but has to do with the fact that cubes   (3rd powers)   play a role in its definition. Some definitions of cuban primes   primes which are the difference of two consecutive cubes.   primes of the form:   (n+1)3 - n3.   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
bd = Graph[{"a" \[DirectedEdge] "b", "a" \[DirectedEdge] "c", "b" \[DirectedEdge] "c", "b" \[DirectedEdge] "d", "c" \[DirectedEdge] "d", "d" \[DirectedEdge] "e", "a" \[DirectedEdge] "f", "c" \[DirectedEdge] "f", "e" \[DirectedEdge] "f"}, EdgeWeight -> {7, 9, 10, 15, 11, 6, 14, 2, 9}, VertexLabels ...
Give a code snippet in #Mathematica.2FWolfram_Language This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search a...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#M2000_Interpreter
M2000 Interpreter
  Module RomanNumbers { flush ' empty current stack gosub Initialize document Doc$ while not empty read rom$ print rom$;"=";RomanEval$(rom$) Doc$=rom$+"="+RomanEval$(rom$)+{ } end while Clipboard Doc$ end Initialize: functi...
Give a code snippet in #M2000_Interpreter Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded sep...
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Raven
Raven
define multiReturn use $v $v each   3 multiReturn
Give a code snippet in #Raven Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#Pop11
Pop11
lib objectclass;   define :class foo; enddefine;   define define_named_method(method, class); lvars method_str = method >< ''; lvars class_str = class >< ''; lvars method_hash_str = 'hash_' >< length(class_str) >< '_' >< class_str >< '_' >< length(method_str) ...
Give a code snippet in #Pop11 Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metapr...
christopher/rosetta-code
http://rosettacode.org/wiki/Numeric_error_propagation
Numeric error propagation
If   f,   a,   and   b   are values with uncertainties   σf,   σa,   and   σb,   and   c   is a constant; then if   f   is derived from   a,   b,   and   c   in the following ways, then   σf   can be calculated as follows: Addition/Subtraction If   f = a ± c,   or   f = c ± a   then   σf = σa If   f = a ± b   then...
#Factor
Factor
USING: accessors arrays fry kernel locals math math.functions multi-methods parser prettyprint prettyprint.custom sequences ; RENAME: GENERIC: multi-methods => MM-GENERIC: FROM: syntax => M: ; IN: imprecise   TUPLE: imprecise { value float read-only } { sigma float read-only } ;   C: <imprecise> imprecise   : >...
Give a code snippet in #Factor If   f,   a,   and   b   are values with uncertainties   σf,   σa,   and   σb,   and   c   is a constant; then if   f   is derived from   a,   b,   and   c   in the following ways, then   σf   can be calculated as follows: Addition/Subtraction If   f = a ± c,   or   f = c ± a   then ...
christopher/rosetta-code
http://rosettacode.org/wiki/Stable_marriage_problem
Stable marriage problem
Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of engagements for marriage is o...
#Ceylon
Ceylon
abstract class Single(name) of Gal | Guy {   shared String name; shared late Single[] preferences;   shared variable Single? fiance = null; shared Boolean free => fiance is Null;   shared variable Integer currentProposalIndex = 0;   "Does this single prefer this other single over their fiance?" ...
Give a code snippet in #Ceylon Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#beeswax
beeswax
#>'#{; _`Enter n: `TN`Fib(`{`)=`X~P~K#{; #>~P~L#MM@>+@'q@{; b~@M<
Give a code snippet in #beeswax The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions a...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_random_chess_position
Generate random chess position
Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacent squares; there can not be any p...
#Action.21
Action!
DEFINE BOARDSIZE="64" DEFINE EMPTY="'."   BYTE FUNC AbsDist(BYTE a,b) IF a>b THEN RETURN (a-b) FI RETURN (b-a)   BYTE FUNC GetPiece(BYTE ARRAY board BYTE x,y) RETURN (board(x+y*8))   PROC PutPiece(BYTE ARRAY board BYTE x,y,piece) board(x+y*8)=piece RETURN   PROC PrintBoard(BYTE ARRAY board) BYTE i,j,c   FOR j=0...
Give a code snippet in #Action.21 Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjace...
christopher/rosetta-code
http://rosettacode.org/wiki/Distributed_programming
Distributed programming
Write two programs (or one program with two modes) which run on networked computers, and send some messages between them. The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example ...
#Racket
Racket
  #lang racket/base (require racket/place/distributed racket/place)   (define (fib n) (if (<= n 1) n (+ (fib (- n 1)) (fib (- n 2)))))   (provide work) (define (work) (place ch (place-channel-put ch (fib (place-channel-get ch)))))   (module+ main (define places (for/list ([host '("localhost" "localhost" "...
Give a code snippet in #Racket Write two programs (or one program with two modes) which run on networked computers, and send some messages between them. The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed ...
christopher/rosetta-code
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecib...
#PowerShell
PowerShell
  function isPrime ($n) { if ($n -le 1) {$false} elseif (($n -eq 2) -or ($n -eq 3)) {$true} else{ $m = [Math]::Floor([Math]::Sqrt($n)) (@(2..$m | where {($_ -lt $n) -and ($n % $_ -eq 0) }).Count -eq 0) } } function semiprime ($n) { if($n -gt 3) { $lim = [Math]::Floor($n/2)+...
Give a code snippet in #PowerShell Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number wa...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_the_coins
Count the coins
There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pennies   A nickel and 10 pen...
#PicoLisp
PicoLisp
(de coins (Sum Coins) (let (Buf (mapcar '((N) (cons 1 (need (dec N) 0))) Coins) Prev) (do Sum (zero Prev) (for L Buf (inc (rot L) Prev) (setq Prev (car L)) ) ) Prev ) )
Give a code snippet in #PicoLisp There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels an...
christopher/rosetta-code
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Sidef
Sidef
var a1 = 1 var a2 = 0 var δ = 3.2.float   say " i\tδ"   for i in (2..15) { var a0 = ((a1 - a2)/δ + a1) 10.times { var (x, y) = (0, 0) 2**i -> times { y = (1 - 2*x*y) x = (a0 - x²) } a0 -= x/y } δ = ((a1 - a2) / (a0 - a1)) (a2, a1) = (a1, a0) ...
Give a code snippet in #Sidef Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
christopher/rosetta-code
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#Modula-3
Modula-3
MODULE TextCase EXPORTS Main;   IMPORT IO, Text, ASCII;   PROCEDURE Upper(txt: TEXT): TEXT = VAR len := Text.Length(txt); res := ""; BEGIN FOR i := 0 TO len - 1 DO res := Text.Cat(res, Text.FromChar(ASCII.Upper[Text.GetChar(txt, i)])); END; RETURN res; END Upper;   PROCEDURE Lower(txt: T...
Give a code snippet in #Modula-3 Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is no...
christopher/rosetta-code
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ...
#UNIX_Shell
UNIX Shell
selfdescribing() { local n=$1 local count=() local i for ((i=0; i<${#n}; i++)); do ((count[${n:i:1}]++)) done for ((i=0; i<${#n}; i++)); do (( ${n:i:1} == ${count[i]:-0} )) || return 1 done return 0 }   for n in 0 1 10 11 1210 2020 21200 3211000 42101000; do if selfd...
Give a code snippet in #UNIX_Shell Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, wh...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#Phix
Phix
without javascript_semantics integer i = 0 while 1 do ?i i += 1 end while
Give a code snippet in #Phix Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations lim...
christopher/rosetta-code
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#Chapel
Chapel
  config const gridHeight: int = 3; config const gridWidth: int = 3;   enum State { dead = 0, alive = 1 };   class ConwaysGameofLife {   var gridDomain: domain(2); var computeDomain: subdomain( gridDomain ); var grid: [gridDomain] int;   proc ConwaysGameofLife( height: int, width: int ) { this.gridDomain = ...
Give a code snippet in #Chapel The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#Sidef
Sidef
require('Tk')   var root = %s<MainWindow>.new('-title' => 'Pendulum Animation') var canvas = root.Canvas('-width' => 320, '-height' => 200)   canvas.createLine( 0, 25, 320, 25, '-tags' => <plate>, '-width' => 2, '-fill' => :grey50) canvas.createOval(155, 20, 165, 30, '-tags' => <pivot outline>, '-fi...
Give a code snippet in #Sidef One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and a...
christopher/rosetta-code
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#VBA
VBA
Sub HigherOrder() Dim result As Single result = first("second") MsgBox result End Sub Function first(f As String) As Single first = Application.Run(f, 1) + 2 End Function Function second(x As Single) As Single second = x / 2 End Function
Give a code snippet in #VBA Task Pass a function     as an argument     to another function. Related task   First-class functions
christopher/rosetta-code
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle
Solve the no connection puzzle
You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/ G H You ar...
#11l
11l
V connections = [(0, 2), (0, 3), (0, 4), (1, 3), (1, 4), (1, 5), (6, 2), (6, 3), (6, 4), (7, 3), (7, 4), (7, 5), (2, 3), (3, 4), (4, 5)]   F ok(conn, perm) R abs(perm[conn[0]] - perm[conn[1]]) != 1   F solve() [[Int]] r V perm = Array(1..8) ...
Give a code snippet in #11l You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \...
christopher/rosetta-code
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbe...
#Clojure
Clojure
(defn emirp? [v] (let [a (biginteger v) b (biginteger (clojure.string/reverse (str v)))] (and (not= a b) (.isProbablePrime a 16) (.isProbablePrime b 16))))   ; Generate the output (println "first20: " (clojure.string/join " " (take 20 (filter emirp? (iterate inc 0))))) (println "7700-...
Give a code snippet in #Clojure An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th ...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays 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_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#Smalltalk
Smalltalk
  Pharo Smalltalk   [ :yr | | firstDay firstSunday | firstDay := Date year: yr month: 1 day: 1. firstSunday := firstDay addDays: (1 - firstDay dayOfWeek). (0 to: 53) collect: [ :each | firstSunday addDays: (each * 7) ] thenSelect: [ :each | (((Date daysInMonth: each monthIndex forYear: yr)...
Give a code snippet in #Smalltalk Write a program or a script that returns the last Sundays 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_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28...
christopher/rosetta-code
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#Oforth
Oforth
: encryptRot13(c) c dup isLetter ifFalse: [ return ] isUpper ifTrue: [ 'A' ] else: [ 'a' ] c 13 + over - 26 mod + ;   : rot13 map(#encryptRot13) charsAsString ;
Give a code snippet in #Oforth Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-1...
christopher/rosetta-code