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/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#Pascal
Pascal
Program Combinations;   const m_max = 3; n_max = 5; var combination: array [0..m_max] of integer;   procedure generate(m: integer); var n, i: integer; begin if (m > m_max) then begin for i := 1 to m_max do write (combination[i], ' '); writeln; end else for n := 1 to n_max do ...
Give a code snippet in #Pascal Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Numerical_integration/Gauss-Legendre_Quadrature
Numerical integration/Gauss-Legendre Quadrature
In a general Gaussian quadrature rule, an definite integral of f ( x ) {\displaystyle f(x)} is first approximated over the interval [ − 1 , 1 ] {\displaystyle [-1,1]} by a polynomial approximable function g ( x ) {\displaystyle g(x)} and a known weighting function W ( x ) {\displaystyle ...
#JavaScript
JavaScript
  const factorial = n => n <= 1 ? 1 : n * factorial(n - 1); const M = n => (n - (n % 2 !== 0)) / 2; const gaussLegendre = (fn, a, b, n) => { // coefficients of the Legendre polynomial const coef = [...Array(M(n) + 1)].map((v, m) => v = (-1) ** m * factorial(2 * n - 2 * m) / (2 ** n * factorial(m) * factorial(n - m) ...
Give a code snippet in #JavaScript In a general Gaussian quadrature rule, an definite integral of f ( x ) {\displaystyle f(x)} is first approximated over the interval [ − 1 , 1 ] {\displaystyle [-1,1]} by a polynomial approximable function g ( x ) {\displaystyle g(x)} and a known weighting fu...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#Elena
Elena
import system'collections; import system'routines; import extensions;   public program() { // 1. Create var map := Dictionary.new(); map["key"] := "foox"; map["key"] := "foo"; map["key2"]:= "foo2"; map["key3"]:= "foo3"; map["key4"]:= "foo4";   // Enumerate map.forEach: (keyVa...
Give a code snippet in #Elena Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Com...
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...
#Tcl
Tcl
  namespace import ::tcl::mathop::-   proc subleq {pgm} { set ip 0 while {$ip >= 0} { lassign [lrange $pgm $ip $ip+2] a b c incr ip 3 if {$a == -1} { scan [read stdin 1] %C char lset pgm $b $char } elseif {$b == -1} { set char [format %c [linde...
Give a code snippet in #Tcl 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 sign...
christopher/rosetta-code
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1} ...
#Julia
Julia
function equindex2pass(data::Array) rst = Vector{Int}(0) suml, sumr, ddelayed = 0, sum(data), 0 for (i, d) in enumerate(data) suml += ddelayed sumr -= d ddelayed = d if suml == sumr push!(rst, i) end end return rst end   @show equindex2pass([1, -1,...
Give a code snippet in #Julia An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#CoffeeScript
CoffeeScript
knuth_shuffle = (a) -> n = a.length while n > 1 r = Math.floor(n * Math.random()) n -= 1 [a[n], a[r]] = [a[r], a[n]] a   counts = "1,2,3": 0 "1,3,2": 0 "2,1,3": 0 "2,3,1": 0 "3,1,2": 0 "3,2,1": 0   for i in [1..100000] counts[knuth_shuffle([ 1, 2, 3 ]).join(",")] += 1   for key, val of c...
Give a code snippet in #CoffeeScript The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging ...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Logo
Logo
to split :str :sep output parse map [ifelse ? = :sep ["| |] [?]] :str end
Give a code snippet in #Logo Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks rel...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_largest_left_truncatable_prime_in_a_given_base
Find largest left truncatable prime in a given base
A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2. Let's consider what happens in...
#Julia
Julia
using Primes, Printf   function addmsdigit(p::Integer, b::Integer, s::Integer) a = Vector{typeof(p)}() q = p for i in 1:(b-1) q += s isprime(q) || continue push!(a, q) end return a end   function lefttruncprime(pbase::Integer) a = Vector{BigInt}() append!(a, primes(pb...
Give a code snippet in #Julia A truncatable prime is one where all non-empty substrings that finish at the end of the number (right-substrings) are also primes when understood as numbers in a particular base. The largest such prime in a given (integer) base is therefore computable, provided the base is larger than 2. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Oforth
Oforth
: avg ( x -- avg ) x sum x size dup ifZero: [ 2drop null ] else: [ >float / ] ;
Give a code snippet in #Oforth Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an est...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#F.23
F#
#light [<EntryPoint>] let main args = for i = 1 to 5 do for j = 1 to i do printf "*" printfn "" 0
Give a code snippet in #F.23 “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structur...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead 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 ...
#Eiffel
Eiffel
  class BEAD_SORT   feature   bead_sort (ar: ARRAY [INTEGER]): ARRAY [INTEGER] -- Sorted array in descending order. require only_positive_integers: across ar as a all a.item > 0 end local max, count, i, j, k: INTEGER do max := max_item (ar) create Result.make_filled (0, 1, ar.count) from i...
Give a code snippet in #Eiffel Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#Sidef
Sidef
var table = <<'EOT'.lines.map { .words.grep{.is_numeric}.map{.to_n} } >= 0.00 < 0.06  := 0.10 >= 0.06 < 0.11  := 0.18 >= 0.11 < 0.16  := 0.26 >= 0.16 < 0.21  := 0.32 >= 0.21 < 0.26  := 0.38 >= 0.26 < 0.31  := 0.44 >= 0.31 < 0.36  := 0.50 >= 0.36 < 0.41  := 0.54 >= 0.41 < 0.46  := 0.5...
Give a code snippet in #Sidef A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and ...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Cubescript
Cubescript
alias fizzbuzz [ loop i 100 [ push i (+ $i 1) [ cond (! (mod $i 15)) [ echo FizzBuzz ] (! (mod $i 3)) [ echo Fizz ] (! (mod $i 5)) [ echo Buzz ] [ echo $i ] ] ] ]
Give a code snippet in #Cubescript Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   Fiz...
christopher/rosetta-code
http://rosettacode.org/wiki/Go_Fish
Go Fish
Write a program to let the user play Go Fish against a computer opponent. Use the following rules: Each player is dealt nine cards to start with. On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one card of a given rank to ask for more. If t...
#Locomotive_Basic
Locomotive Basic
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Go_Fish use warnings; use List::Util qw( first shuffle );   my $pat = qr/[atjqk2-9]/; # ranks my $deck = join '', shuffle map { my $rank = $_; map "$rank$_", qw( S H C D ) } qw( a t j q k ), 2 .. 9;   my $mebooks = my $youbooks = 0;   my $me = substr $deck,...
Give a code snippet in #Locomotive_Basic Write a program to let the user play Go Fish against a computer opponent. Use the following rules: Each player is dealt nine cards to start with. On their turn, a player asks their opponent for a given rank (such as threes or kings). A player must already have at least one c...
christopher/rosetta-code
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas
The Twelve Days of Christmas
Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations: Metrics Array length Stri...
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   ( "A partridge in a pear tree." "Two turtle doves, and" "Three French hens," "Four calling birds," "Five gold rings," "Six geese a-laying," "Seven swans a-swimming," "Eight maids a-milking," "Nine ladies dancing," "Ten lords a-leaping," "Eleven pipers piping," "Twelve dru...
Give a code snippet in #Phixmonti Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string opera...
christopher/rosetta-code
http://rosettacode.org/wiki/Inheritance/Multiple
Inheritance/Multiple
Multiple inheritance allows to specify that one class is a subclass of several other classes. Some languages allow multiple inheritance for arbitrary classes,   others restrict it to interfaces,   some don't allow it at all. Task Write two classes (or interfaces) Camera and MobilePhone,   then write a class Camer...
#Racket
Racket
#lang racket   (define camera<%> (interface ())) (define mobile-phone<%> (interface ()))   (define camera-phone% (class* object% (camera<%> mobile-phone<%>) (super-new)  ;; implement methods here ))
Give a code snippet in #Racket Multiple inheritance allows to specify that one class is a subclass of several other classes. Some languages allow multiple inheritance for arbitrary classes,   others restrict it to interfaces,   some don't allow it at all. Task Write two classes (or interfaces) Camera and MobileP...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort
Sorting algorithms/Pancake sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Ruby
Ruby
class Array def pancake_sort! num_flips = 0 (self.size-1).downto(1) do |end_idx| max = self[0..end_idx].max max_idx = self[0..end_idx].index(max) next if max_idx == end_idx   if max_idx > 0 self[0..max_idx] = self[0..max_idx].reverse p [num_flips += 1, self] if $D...
Give a code snippet in #Ruby Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#OxygenBasic
OxygenBasic
  function fiboRatio() as double function fibo( double i, j ) as double if j > 2e12 then return j / i return fibo j, i + j end function return fibo 1, 1 end function   print fiboRatio    
Give a code snippet in #OxygenBasic While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing ...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#VBScript
VBScript
function Squish( s1 ) dim sRes sRes = vbNullString dim i, c for i = 1 to len( s1 ) c = lcase( mid( s1, i, 1 )) if instr( "abcdefghijklmnopqrstuvwxyz0123456789", c ) then sRes = sRes & c end if next Squish = sRes end function   function isPalindrome( s1 ) dim squished squished = Squish( s1 ) isPalindro...
Give a code snippet in #VBScript A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly...
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Bracmat
Bracmat
2+2:5 & put$"Strange, must check that Bracmat interpreter." & 0 | put$"That's what I thought." & Right
Give a code snippet in #Bracmat Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Commo...
christopher/rosetta-code
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a...
#Kotlin
Kotlin
class BellTriangle(n: Int) { private val arr: Array<Int>   init { val length = n * (n + 1) / 2 arr = Array(length) { 0 }   set(1, 0, 1) for (i in 2..n) { set(i, 0, get(i - 1, i - 2)) for (j in 1 until i) { val value = get(i, j - 1) + get(i ...
Give a code snippet in #Kotlin Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {...
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...
#Quackery
Quackery
[ [] $ "" rot sort$ witheach [ tuck != if [ dup dip [ nested join ] ] ] drop ] is -duplicates ( { --> { )   [ [] $ "" rot sort$ witheach [ tuck = if [ nested join $ "" ] ] drop -duplicates ] is duplica...
Give a code snippet in #Quackery 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: Se...
christopher/rosetta-code
http://rosettacode.org/wiki/Superpermutation_minimisation
Superpermutation minimisation
A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'...
#Kotlin
Kotlin
// version 1.1.2   const val MAX = 12   var sp = CharArray(0) val count = IntArray(MAX) var pos = 0   fun factSum(n: Int): Int { var s = 0 var x = 0 var f = 1 while (x < n) { f *= ++x s += f } return s }   fun r(n: Int): Boolean { if (n == 0) return false val c = sp[p...
Give a code snippet in #Kotlin A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring. For example, representing the characters as A..Z, using N=2 we choose to u...
christopher/rosetta-code
http://rosettacode.org/wiki/Input_loop
Input loop
Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
#Oberon-2
Oberon-2
  MODULE InputLoop; IMPORT StdChannels, Channel; VAR reader: Channel.Reader; writer: Channel.Writer; c: CHAR; BEGIN reader := StdChannels.stdin.NewReader(); writer := StdChannels.stdout.NewWriter();   reader.ReadByte(c); WHILE reader.res = Channel.done DO writer.WriteByte(c); reader.ReadByte(c...
Give a code snippet in #Oberon-2 Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
NumberQ[ToExpression["02553352000242"]]
Give a code snippet in #Mathematica_.2F_Wolfram_Language Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to str...
christopher/rosetta-code
http://rosettacode.org/wiki/Simulate_input/Keyboard
Simulate input/Keyboard
Task Send simulated keystrokes to a GUI window, or terminal. You should specify whether the target may be externally created (i.e., if the keystrokes are going to an application other than the application that is creating them).
#Racket
Racket
#lang racket/gui   (define frame (new frame% (label "Example") (width 300) (height 300)))  ; Defines an instance of a frame to put the canvas in   (define simulate-key-canvas% (class canvas% (define/public (simulate-key key) (send this on-cha...
Give a code snippet in #Racket Task Send simulated keystrokes to a GUI window, or terminal. You should specify whether the target may be externally created (i.e., if the keystrokes are going to an application other than the application that is creating them).
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#Apex
Apex
for (Integer i = 0; i < 5; i++) { String line = '';   for (Integer j = 0; j < i; j++) { line += '*'; }   System.debug(line); }   List<String> lines = new List<String> { '*', '**', '***', '****', '*****' };   for (String line : lines) { System.debug(line); }
Give a code snippet in #Apex “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structur...
christopher/rosetta-code
http://rosettacode.org/wiki/Monads/Maybe_monad
Monads/Maybe monad
Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and return a monadic number, e.g. Int ...
#C
C
  #include <stdio.h> #include <stdlib.h> #include <stdbool.h>   typedef enum type { INT, STRING } Type;   typedef struct maybe { int i; char *s; Type t; _Bool is_something; } Maybe;   void print_Maybe(Maybe *m) { if (m->t == INT) printf("Just %d : INT\n", m->i);   else if (m->t == STRING) printf...
Give a code snippet in #C Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and return ...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#PureBasic
PureBasic
Procedure displayArray(Array a(1), msg.s) Protected i Print(msg + " [") For i = 0 To ArraySize(a()) Print(Str(a(i))) If i <> ArraySize(a()) Print(", ") EndIf Next PrintN("]") EndProcedure   Procedure randomElements(Array a(1), lo, hi) Protected i For i = 0 To ArraySize(a()) a(i) = ...
Give a code snippet in #PureBasic Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/Canny_edge_detector
Canny edge detector
Task Write a program that performs so-called canny edge detection on an image. A possible algorithm consists of the following steps: Noise reduction.   May be performed by Gaussian filter.   Compute intensity gradient   (matrices G x {\displaystyle G_{x}} and G y {\displaystyle G_{y}} ) ...
#Raku
Raku
#include <stdio.h> #include <string.h> #include <magick/MagickCore.h>   int CannyEdgeDetector( const char *infile, const char *outfile, double radius, double sigma, double lower, double upper ) {   ExceptionInfo *exception; Image *image, *processed_image, *output; ImageInfo *input_info;...
Give a code snippet in #Raku Task Write a program that performs so-called canny edge detection on an image. A possible algorithm consists of the following steps: Noise reduction.   May be performed by Gaussian filter.   Compute intensity gradient   (matrices G x {\displaystyle G_{x}} and G y...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#F.23
F#
#light open System open System.Windows.Forms [<EntryPoint>] let main _ = MessageBox.Show("Hello World!") |> ignore 0
Give a code snippet in #F.23 Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/Extensible_prime_generator
Extensible prime generator
Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In thi...
#Seed7
Seed7
$ include "seed7_05.s7i";   const func boolean: isPrime (in integer: number) is func result var boolean: prime is FALSE; local var integer: count is 2; begin if number = 2 then prime := TRUE; elsif number > 2 then while number rem count <> 0 and count * count <= number do incr(...
Give a code snippet in #Seed7 Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or prog...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Iteration
Associative array/Iteration
Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked ...
#zkl
zkl
var d=Dictionary("A","alpha","D","delta", "B","beta", "C", "gamma"); d.keys.pump(Console.print,fcn(k){String(k,",")}) d.values.apply("toUpper").println(); d.makeReadOnly(); // can only iterate over k,v pairs if read only foreach k,v in (d){print(k,":",v,"; ")}
Give a code snippet in #zkl Show how to iterate over the key-value pairs of an associative array, and print each pair out. Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language. See also Array Associative array: Creation, Iteration Collections Compo...
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...
#D
D
double mapRange(in double[] a, in double[] b, in double s) pure nothrow @nogc { return b[0] + ((s - a[0]) * (b[1] - b[0]) / (a[1] - a[0])); }   void main() { import std.stdio;   immutable r1 = [0.0, 10.0]; immutable r2 = [-1.0, 0.0]; foreach (immutable s; 0 .. 11) writefln("%2d maps to %5.2f...
Give a code snippet in #D 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 mappe...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#PureBasic
PureBasic
MessageRequester("Hello","Goodbye, World!")
Give a code snippet in #PureBasic Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Erlang
Erlang
  -module( number_reversal_game ).   -export( [task/0, start/1] ).   start( N ) when N > 1 -> io:fwrite( "Usage: ~s~n", [usage(N)] ), Targets = lists:seq( 1, N ), Jumbleds = [X||{_,X} <- lists:sort([ {random:uniform(), Y} || Y <- Targets])], Attempt = loop( Targets, Jumbleds, 0 ), io:fwrite( "Numbers sorted in ~p ...
Give a code snippet in #Erlang 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 s...
christopher/rosetta-code
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#PureBasic
PureBasic
a$="1001110011"+#CRLF$+"1110111011"+#CRLF$+"0010010010"+#CRLF$+"1010101010"+#CRLF$+"1111111111"+#CRLF$+ "0100101101"+#CRLF$+"0100100" +#CRLF$+"101" +#CRLF$+"11" +#CRLF$+"00" +#CRLF$+ "1" +#CRLF$   OpenConsole()   Procedure isRepStr(s1$,s2$) If Int(Len(s1$)/Len(s2$))>=2 : ProcedureR...
Give a code snippet in #PureBasic Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at ...
christopher/rosetta-code
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#PHP
PHP
  function convertToBinary($integer) { $binary = "";   do { $quotient = (int) ($integer / 2); $binary .= $integer % 2; $integer = $quotient; } while ($quotient > 0);   return $binary; }   function getPopCount($integer) { $binary = convertToBinary($integer); $offset = ...
Give a code snippet in #PHP Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count ...
christopher/rosetta-code
http://rosettacode.org/wiki/Web_scraping
Web scraping
Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page. If possible,...
#AWK
AWK
SYS "LoadLibrary", "URLMON.DLL" TO urlmon% SYS "GetProcAddress", urlmon%, "URLDownloadToFileA" TO UDTF% SYS "LoadLibrary", "WININET.DLL" TO wininet% SYS "GetProcAddress", wininet%, "DeleteUrlCacheEntryA" TO DUCE%   url$ = "http://tycho.usno.navy.mil/cgi-bin/timer.pl" file$ = @tmp$+"n...
Give a code snippet in #AWK Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a progr...
#AutoHotkey
AutoHotkey
fact:=[] fact[0] := 1 while (A_Index < 12) fact[A_Index] := fact[A_Index-1] * A_Index b := 9 while (b <= 12) { res .= "base " b " factorions: `t" while (A_Index < 1500000){ sum := 0 j := A_Index while (j > 0){ d := Mod(j, b) sum += fact[d] j /= b } if (sum = A_Index) res .= A_Index " " } b...
Give a code snippet in #AutoHotkey Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed...
christopher/rosetta-code
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribut...
#PARI.2FGP
PARI/GP
cumChi2(chi2,dof)={ my(g=gamma(dof/2)); incgam(dof/2,chi2/2,g)/g }; test(v,alpha=.05)={ my(chi2,p,s=sum(i=1,#v,v[i]),ave=s/#v); print("chi^2 statistic: ",chi2=sum(i=1,#v,(v[i]-ave)^2)/ave); print("p-value: ",p=cumChi2(chi2,#v-1)); if(p<alpha, print("Significant at the alpha = "alpha" level: not uniform"); , ...
Give a code snippet in #PARI.2FGP Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a bo...
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#Run_BASIC
Run BASIC
card$(1) = "49927398716" card$(2) = "49927398717" card$(3) = "1234567812345678" card$(4) = "1234567812345670"   for i = 1 to 4 print card$(i);" ";luhn$(card$(i)) next i   FUNCTION luhn$(card$) lc = len(card$) for i = lc to 1 step -1 digit = val(mid$(card$,i,1)) if ((lc -i) mod 2) = 0 then chk...
Give a code snippet in #Run_BASIC The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the orde...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#Befunge
Befunge
&&+.@
Give a code snippet in #Befunge A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separa...
christopher/rosetta-code
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that...
#Raku
Raku
role Egyptian { method gist { join ' + ', ("[{self.floor}]" if self.abs >= 1), map {"1/$_"}, self.denominators; } method denominators { my ($x, $y) = self.nude; $x %= $y; my @denom = gather ($x, $y) = -$y % $x, $y * take ($y / $x).ceiling while $x; } }   say .nude.join('/'), " = ", $_...
Give a code snippet in #Raku An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (u...
christopher/rosetta-code
http://rosettacode.org/wiki/Test_a_function
Test a function
Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
#AutoHotkey
AutoHotkey
; assert.ahk ;; assert(a, b, test=2) assert(a, b="blank", test=0) { if (b = "blank") { if !a msgbox % "blank value" return 0 } if equal_list(a, b, "`n") return 0 else msgbox % test . ":`n" . a . "`nexpected:`n" . b }   !r::reload   ;; equal_list(a, b, delimiter) equal_list(a, b, deli...
Give a code snippet in #AutoHotkey Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
christopher/rosetta-code
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call
Respond to an unknown method call
Task Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions. Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin...
#Slate
Slate
define: #shell &builder: [lobby newSubSpace].   _@shell didNotUnderstand: message at: position "Form a command string and execute it." [ position > 0 ifTrue: [resend] ifFalse: [([| :command | message selector isUnarySelector ifTrue: [command ; message selector. message optionals pairsDo: [...
Give a code snippet in #Slate Task Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions. Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#FreeBASIC
FreeBASIC
  Function in_carpet(x As Uinteger, y As Uinteger) As Boolean While x <> 0 And y <> 0 If(x Mod 3) = 1 And (y Mod 3) = 1 Then Return False y = y \ 3: x = x \ 3 Wend Return True End Function   Sub carpet(n As Uinteger) Dim As Uinteger i, j, k = (3^n)-1   For i = 0 To k For j =...
Give a code snippet in #FreeBASIC Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # ...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#Kotlin
Kotlin
// version 1.1.2   import java.io.File   fun main(args: Array<String>) { val text = "empty vessels make most noise" File("output.txt").writeText(text) }
Give a code snippet in #Kotlin Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#Run_BASIC
Run BASIC
run SomeProgram.bas",#include ' this gives it a handle of #include render #include ' render will RUN the program with handle #include
Give a code snippet in #Run_BASIC Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#Scheme
Scheme
(do ((n 1024 (quotient n 2))) ((<= n 0)) (display n) (newline))
Give a code snippet in #Scheme Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downwa...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle
Pascal's triangle/Puzzle
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the...
#Factor
Factor
USING: arrays backtrack combinators.extras fry grouping.extras interpolate io kernel math math.ranges sequences ;   : base ( ?x ?z -- seq ) 2dup + swap '[ _ 11 _ 4 _ ] >array ;   : up ( seq -- seq' ) [ [ + ] 2clump-map ] twice ;   : find-solution ( -- x z ) 10 [1,b] dup [ amb-lazy ] bi@ 2dup base up dup first 4...
Give a code snippet in #Factor This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers...
christopher/rosetta-code
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#Snobol
Snobol
* GCD function DEFINE('GCD(A,B)')  :(GCD_END) GCD GCD = A EQ(B,0)  :S(RETURN) A = B B = REMDR(GCD,B)  :(GCD) GCD_END   * Find first occurrence of element in array DEFINE('IDX(ARR,ELM)') ...
Give a code snippet in #Snobol For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered memb...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Gambas
Gambas
Public Sub Main() Dim siCount, siRev, siProcess As Short Dim bSorting As Boolean Dim byToSort As Byte[] = [249, 28, 111, 36, 171, 98, 29, 448, 44, 154, 147, 102, 46, 183, 24, 120, 19, 123, 2, 17, 226, 11, 211, 25, 191, 205, 77]   Print "To sort: -" ShowWorking(byToSort) Print   Repeat bSort...
Give a code snippet in #Gambas Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#PureBasic
PureBasic
; if you just want the DigitalRoot ; Procedure.q DigitalRoot(N.q) apparently will do ; i must have missed something because it seems too simple ; http://en.wikipedia.org/wiki/Digital_root#Congruence_formula   Procedure.q DigitalRoot(N.q) Protected M.q=N%9 if M=0:ProcedureReturn 9 Else  :ProcedureReturn M:EndIf EndProc...
Give a code snippet in #PureBasic The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X}...
christopher/rosetta-code
http://rosettacode.org/wiki/Linear_congruential_generator
Linear congruential generator
The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaystyle r_{0}} is a seed. r 1 ...
#PureBasic
PureBasic
Procedure ms_LCG(seed.q = -1) Static state.q If seed >= 0 state = seed Else state = (state * 214013 + 2531011) % (1 << 31) ProcedureReturn state >> 16 EndIf EndProcedure   Procedure.q bsd_LCG(seed.q = -1) Static state.q If seed >= 0 state = seed Else state = (state * 1103515245 + 12...
Give a code snippet in #PureBasic The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaysty...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET x=10 20 LET y=20 30 DIM a(x) 40 DIM b(y) 50 DIM c(x+y) 60 FOR i=1 TO x 70 LET c(i)=a(i) 80 NEXT i 90 FOR i=1 TO y 100 LET c(x+i)=b(i) 110 NEXT i 120 FOR i=1 TO x+y 130 PRINT c(i);", "; 140 NEXT i  
Give a code snippet in #ZX_Spectrum_Basic Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). T...
#Python
Python
>>> x="From global scope" >>> def outerfunc(): x = "From scope at outerfunc"   def scoped_local(): x = "scope local" return "scoped_local scope gives x = " + x print(scoped_local())   def scoped_nonlocal(): nonlocal x return "scoped_nonlocal scope gives x = " + x prin...
Give a code snippet in #Python Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static s...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Harbour
Harbour
? Replicate( "Ha", 5 )
Give a code snippet in #Harbour Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#XBS
XBS
set letters="ABCDEFGHIJKLMNOPQRSTUVWXYZ"::split();   func caesar(text,shift:number=1){ set res:string=""; for(i=0;?text-1;1){ set t=text::at(i); set n=(letters::find(t::upper())+shift)%?letters; while(n<0){ n=?letters+n; } set l=letters[n]; (t::upper()==t)|=>l=l::lower() res+=l; } send res; }   fun...
Give a code snippet in #XBS 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Define_a_primitive_data_type
Define a primitive data type
Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
#Elena
Elena
import extensions;   sealed struct TinyInt : BaseNumber { int value;   int cast() = value;   constructor(int n) { if (n <= 1 || n >= 10) { InvalidArgumentException.raise() };   value := n }   cast t(string s) { value := s.toInt();   ...
Give a code snippet in #Elena Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes ...
#Racket
Racket
#lang racket ;; {{trans|Sidef}} ;; vectors are represented by lists   (struct Line (P0 u⃗))   (struct Plane (V0 n⃗))   (define (· a b) (apply + (map * a b)))   (define (line-plane-intersection L P) (match-define (cons (Line P0 u⃗) (Plane V0 n⃗)) (cons L P)) (define cos (· n⃗ u⃗)) (when (zero? cos) (error "vec...
Give a code snippet in #Racket Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of...
christopher/rosetta-code
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#Quackery
Quackery
[ [ dup while tuck mod again ] drop abs ] is gcd ( n n --> n )   [ 2dup peek dip [ 1+ 2dup peek ] over + swap join swap dip join ] is two-terms ( [ n --> [ n )   ' [ 1 1 ] 0 8 times two-terms over 15 split drop witheach [ echo sp ] cr [ two-terms over -2 pe...
Give a code snippet in #Quackery For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered me...
christopher/rosetta-code
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactl...
#Tcl
Tcl
proc factorPairs {n {from 2}} { set result [list 1 $n] if {$from<=1} {set from 2} for {set i $from} {$i<=sqrt($n)} {incr i} { if {$n%$i} {} {lappend result $i [expr {$n/$i}]} } return $result }   proc vampireFactors {n} { if {[string length $n]%2} return set half [expr {[string length $n]/2...
Give a code snippet in #Tcl A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   to...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#Klong
Klong
  {(1:$(*x?0c )#x)+1:$(1+*|x?0c )_x}@.rl() 2 3 5  
Give a code snippet in #Klong A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separate...
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 ...
#jq
jq
# fs(f, s) takes a function, f, of one value and a sequence of values s, # and returns an ordered sequence of the result of applying function f to every value of s in turn.   def fs(f; s): s | f;   # f1 takes a value and returns it multiplied by 2: def f1: 2 * .;   # f2 takes a value and returns it squared: def f2: . *...
Give a code snippet in #jq 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. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#PHP
PHP
  function transpose($m) { if (count($m) == 0) // special case: empty matrix return array(); else if (count($m) == 1) // special case: row matrix return array_chunk($m[0], 1);   // array_map(NULL, m[0], m[1], ..) array_unshift($m, NULL); // the original matrix is not modified because it was passed by va...
Give a code snippet in #PHP Transpose an arbitrarily sized rectangular Matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Synchronous_concurrency
Synchronous concurrency
The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with different names. Some languages use th...
#EchoLisp
EchoLisp
  (require 'sequences) (require 'tasks)   ;; inter-tasks message : (op-code . data) (define (is-message? op message) (and message (equal? op (first message))))   ;; reader task (define (reader infile ) (wait S) (define message (semaphore-pop S)) (when (is-message? 'count message ) (writeln 'reader-> message) (task-...
Give a code snippet in #EchoLisp The goal of this task is to create two concurrent activities ("Threads" or "Tasks", not processes.) that share data synchronously. Your language may provide syntax or libraries to perform concurrency. Different languages provide different implementations of concurrency, often with diff...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_comments_from_a_string
Strip comments from a string
Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whitespace debacle:   There is s...
#Go
Go
package main   import ( "fmt" "strings" "unicode" )   const commentChars = "#;"   func stripComment(source string) string { if cut := strings.IndexAny(source, commentChars); cut >= 0 { return strings.TrimRightFunc(source[:cut], unicode.IsSpace) } return source }   func main() { for _, s := range []string{ "a...
Give a code snippet in #Go Strip comments from a string You are encouraged to solve this task according to the task description, using any language you may know. The task is to remove text that follow any of a set of comment markers, (in these examples either a hash or a semicolon) from a string or input line. Whit...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Sidef
Sidef
var original = "hello"; # new String object var reference = original; # points at the original object var copy1 = String.new(original); # creates a new String object var copy2 = original+''; # ==//==
Give a code snippet in #Sidef This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty s...
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...
#11l
11l
L print(‘SPAM’)
Give a code snippet in #11l 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/...
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#Cach.C3.A9_ObjectScript
Caché ObjectScript
USER>set hash=$System.Encryption.SHAHash(256, "Rosetta code") USER>zzdump hash 0000: 76 4F AF 5C 61 AC 31 5F 14 97 F9 DF A5 42 71 39 0010: 65 B7 85 E5 CC 2F 70 7D 64 68 D7 D1 12 4C DF CF
Give a code snippet in #Cach.C3.A9_ObjectScript SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f149...
christopher/rosetta-code
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#Maple
Maple
  L1 := [3, 4, 5, 6]; L1 := [3, 4, 5, 6]   L2 := [7, 8, 9]; L2 := [7, 8, 9]  
Give a code snippet in #Maple This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Cr...
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction/Arithmetic/Construct_from_rational_number
Continued fraction/Arithmetic/Construct from rational number
Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a c t i o n {\displaystyle {\m...
#Factor
Factor
USING: formatting kernel lists lists.lazy math math.parser qw sequences ; IN: rosetta-code.cf-arithmetic   : r2cf ( x -- lazy ) [ >fraction [ /mod ] keep swap [ ] [ / ] if-zero nip ] lfrom-by [ integer? ] luntil [ >fraction /i ] lmap-lazy ;   : main ( -- ) qw{ 1/2 3 23/8 13/1...
Give a code snippet in #Factor Continued fraction arithmetic The purpose of this task is to write a function r 2 c f ( i n t {\displaystyle {\mathit {r2cf}}(\mathrm {int} } N 1 , i n t {\displaystyle N_{1},\mathrm {int} } N 2 ) {\displaystyle N_{2})} , or r 2 c f ( F r a...
christopher/rosetta-code
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#CLU
CLU
middle_three_digits = proc (n: int) returns (string) signals (too_small, even_length) s: string := int$unparse(int$abs(n)) if string$size(s) < 3 then signal too_small end if string$size(s) // 2 = 0 then signal even_length end return(string$substr(s, string$size(s)/2, 3)) end middle...
Give a code snippet in #CLU Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be test...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler%27s_identity
Euler's identity
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, Euler's identity is the equality: ...
#Bracmat
Bracmat
e^(i*pi)+1
Give a code snippet in #Bracmat This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, Euler's identit...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_common_subsequence
Longest common subsequence
Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of ...
#Clojure
Clojure
(defn longest [xs ys] (if (> (count xs) (count ys)) xs ys))   (def lcs (memoize (fn [[x & xs] [y & ys]] (cond (or (= x nil) (= y nil)) nil (= x y) (cons x (lcs xs ys))  :else (longest (lcs (cons x xs) ys) (lcs xs (cons y ys)))))))
Give a code snippet in #Clojure Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be str...
christopher/rosetta-code
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers....
#Ada
Ada
  with Ada.Text_IO;   procedure smith is type Vector is array (natural range <>) of Positive; empty_vector : constant Vector(1..0):= (others=>1);   function digits_sum (n : Positive) return Positive is (if n < 10 then n else n mod 10 + digits_sum (n / 10));   function prime_factors (n : Positive; d : Positiv...
Give a code snippet in #Ada Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are al...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections ...
#J
J
coclass'DoublyLinkedListElement' create=:3 :0 this=:coname'' 'predecessor successor data'=:y successor__predecessor=: predecessor__successor=: this )
Give a code snippet in #J Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creati...
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...
#BQN
BQN
¯5 ¯3000
Give a code snippet in #BQN 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 i...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort
Sorting algorithms/Strand 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 ...
#CMake
CMake
# strand_sort(<output variable> [<value>...]) sorts a list of integers. function(strand_sort var) # Strand sort moves elements from _ARGN_ to _answer_. set(answer) # answer: a sorted list while(DEFINED ARGN) # Split _ARGN_ into two lists, _accept_ and _reject_. set(accept) ...
Give a code snippet in #CMake 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/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...
#D
D
void main() @safe { import std.stdio, std.math, std.algorithm, std.traits, std.string;   enum Peg { A, B, C, D, E, F, G, H } immutable Peg[2][15] connections = [[Peg.A, Peg.C], [Peg.A, Peg.D], [Peg.A, Peg.E], [Peg.B, Peg.D], [Peg.B, Peg.E], [Peg.B, Peg.F], [Peg.C, Peg.D...
Give a code snippet in #D 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/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...
#Clojure
Clojure
  (defn maprange [[a1 a2] [b1 b2] s] (+ b1 (/ (* (- s a1) (- b2 b1)) (- a2 a1))))   > (doseq [s (range 11)] (printf "%2s maps to %s\n" s (maprange [0 10] [-1 0] s)))   0 maps to -1 1 maps to -9/10 2 maps to -4/5 3 maps to -7/10 4 maps to -3/5 5 maps to -1/2 6 maps to -2/5 7 maps to -3/10 8 maps to -1/5...
Give a code snippet in #Clojure 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base
Exponentiation with infix operators in (or operating on) the base
(Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Some languages treat/honor infix operators when performing exponentiation   (raising numbers to some power by the language's exponentiation operator,   if ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
{-5^2, -(5)^2, (-5)^2, -(5^2)} {-5^3, -(5)^3, (-5)^3, -(5^3)}
Give a code snippet in #Mathematica_.2F_Wolfram_Language (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Some languages treat/honor infix operators when performing exponentiation   (raising numbers to s...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_definition
Singly-linked list/Element definition
singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, Lis...
#Haskell
Haskell
data List a = Nil | Cons a (List a)
Give a code snippet in #Haskell singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element d...
christopher/rosetta-code
http://rosettacode.org/wiki/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/sub...
#AutoHotkey
AutoHotkey
Biased(){ Random, q, 0, 4 return q=4 } Unbiased(){ Loop If ((a := Biased()) != biased()) return a } Loop 1000 t .= biased(), t2 .= unbiased() StringReplace, junk, t2, 1, , UseErrorLevel MsgBox % "Unbiased probability of a 1 occurring: " Errorlevel/1000 StringReplace, junk, t, 1, , UseErrorLe...
Give a code snippet in #AutoHotkey P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number gener...
christopher/rosetta-code
http://rosettacode.org/wiki/Inheritance/Single
Inheritance/Single
This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent types. Usually inherited properties...
#Common_Lisp
Common Lisp
(defclass animal () ()) (defclass dog (animal) ()) (defclass lab (dog) ()) (defclass collie (dog) ()) (defclass cat (animal) ())
Give a code snippet in #Common_Lisp This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Heapsort
Sorting algorithms/Heapsort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#TI-83_BASIC
TI-83 BASIC
:If dim(L1)>7 :Then :Disp "ERR:7" :Stop :End :If dim(L1)<7 :Then :For(A,1,7) :If A>dim(L1) :0→L1(A) :End :End :{0}→L2 :For(B,2,7) :0→L2(B) :End :L1→L3 :For(B,0,6) :If L3(4)>L3(2) :Then :L3(2)→A :L3(4)→L3(2) :A→L3(4) :End :If L3(5)>L3(2) :Then :L3(2)→A :L3(5)→L3(2) :A→L3(5) :End :If L3(6)>L3(3) :Then :L3(3)→A :L3(6)→L3(...
Give a code snippet in #TI-83_BASIC Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Qu...
christopher/rosetta-code
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Java
Java
import java.awt.Graphics; import java.awt.image.BufferedImage; import javax.swing.JFrame;   public class Mandelbrot extends JFrame {   private final int MAX_ITER = 570; private final double ZOOM = 150; private BufferedImage I; private double zx, zy, cX, cY, tmp;   public Mandelbrot() { super...
Give a code snippet in #Java Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
christopher/rosetta-code
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149....
#LiveCode
LiveCode
  on plotGraphic local tCoordinates local x = "0, 1, 2, 3, 4, 5, 6, 7, 8, 9" local y = "2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0" if there is a graphic "graph" then delete graphic "graph" repeat with i = 1 to the number of items of x put ite...
Give a code snippet in #LiveCode Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, an...
#Wren
Wren
import "/dynamic" for Enum import "/crypto" for Bytes import "/fmt" for Conv import "/ioutil" for FileUtil   var codes = [ "fetch", "store", "push", "add", "sub", "mul", "div", "mod", "lt", "gt", "le", "ge", "eq", "ne", "and", "or", "neg", "not", ...
Give a code snippet in #Wren A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read inpu...
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...
#K
K
rot13: {a:+65 97+\:2 13#!26;_ci@[!256;a;:;|a]_ic x}   rot13 "Testing! 1 2 3" "Grfgvat! 1 2 3"
Give a code snippet in #K 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 enc...
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#Delphi
Delphi
program Project1;   {$APPTYPE CONSOLE}   uses SysUtils; var aChar:Char; aCode:Byte; uChar:WideChar; uCode:Word; begin aChar := Chr(97); Writeln(aChar); aCode := Ord(aChar); Writeln(aCode); uChar := WideChar(97); Writeln(uChar); uCode := Ord(uChar); Writeln(uCode);   Readln; end.
Give a code snippet in #Delphi Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Con...
christopher/rosetta-code
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#Clojure
Clojure
(ns boxing-the-compass (:use [clojure.string :only [capitalize]]))   (def headings (for [i (range 0 (inc 32))] (let [heading (* i 11.25)] (case (mod i 3) 1 (+ heading 5.62) 2 (- heading 5.62) heading))))   (defn angle2compass [angle] (let [dirs ["N" "NbE" "N-NE" "NEbN" "NE" "...
Give a code snippet in #Clojure There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Oberon-2
Oberon-2
  MODULE Assertions; VAR a: INTEGER; BEGIN a := 40; ASSERT(a = 42); END Assertions.  
Give a code snippet in #Oberon-2 Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively
Walk a directory/Non-recursively
Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directory, not an entire directory tree. ...
#Action.21
Action!
PROC GetFileName(CHAR ARRAY line,fname) BYTE i,len   len=0 i=3 FOR i=3 TO 10 DO IF line(i)=32 THEN EXIT FI len==+1 fname(len)=line(i) OD len==+1 fname(len)='. FOR i=11 TO 13 DO IF line(i)=32 THEN EXIT FI len==+1 fname(len)=line(i) OD fname(0)=len RETURN   PROC Dir(CHAR AR...
Give a code snippet in #Action.21 Task Walk a given directory and print the names of files matching a given pattern. (How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?) Note: This task is for non-recursive methods.   These tasks should read a single directo...
christopher/rosetta-code
http://rosettacode.org/wiki/String_comparison
String comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Elixir
Elixir
s = "abcd" s == "abcd" #=> true s == "abce" #=> false s != "abcd" #=> false s != "abce" #=> true s > "abcd" #=> false s < "abce" #=> true s >= "abce" #=> false s <= "abce" #=> true
Give a code snippet in #Elixir 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/Variable_size/Set
Variable size/Set
Task Demonstrate how to specify the minimum size of a variable or a data type.
#REXX
REXX
/*REXX program demonstrates on setting a variable (using a "minimum var size".*/ numeric digits 100 /*default: 9 (decimal digs) for numbers*/   /*── 1 2 3 4 5 6 7──*/ /*──1234567890123456789012345678901234567890123456789012345678901234567890──*...
Give a code snippet in #REXX Task Demonstrate how to specify the minimum size of a variable or a data type.
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The ...
#Phix
Phix
-- demo\rosetta\Arithmetic_evaluation.exw with javascript_semantics sequence opstack = {} -- atom elements are literals, -- sequence elements are subexpressions -- on completion length(opstack) should be 1 object token constant op_p_p = 1 -- 1: ex...
Give a code snippet in #Phix Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a sim...
christopher/rosetta-code
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#Prolog
Prolog
main() :- christmas_days_falling_on_sunday(2011, 2121, SundayList), writeln(SundayList).   christmas_days_falling_on_sunday(StartYear, EndYear, SundayList) :- numlist(StartYear, EndYear, YearRangeList), include(is_christmas_day_a_sunday, YearRangeList, SundayList).   is_christmas_day_a_sunday(Year) :- ...
Give a code snippet in #Prolog A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between...
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...
#Scheme
Scheme
(define (a-mean l) (/ (apply + l) (length l)))   (define (g-mean l) (expt (apply * l) (/ (length l))))   (define (h-mean l) (/ (length l) (apply + (map / l))))   (define (iota start stop) (if (> start stop) (list) (cons start (iota (+ start 1) stop))))   (let* ((l (iota 1 10)) (a (a-mean l)) (g (g-m...
Give a code snippet in #Scheme 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},\ld...
christopher/rosetta-code