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/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#min
min
(quote cons "" join) :str-append (pick length - repeat swap str-append) :left-pad   7.125 string "0" 9 left-pad puts!
Give a code snippet in #min Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Lua
Lua
  --calculates the nth fibonacci number. Breaks for negative or non-integer n. function fibs(n) return n < 2 and n or fibs(n - 1) + fibs(n - 2) end  
Give a code snippet in #Lua The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are g...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#Ring
Ring
  for i = 1 to 10000 if perfect(i) see i + nl ok next   func perfect n sum = 0 for i = 1 to n - 1 if n % i = 0 sum = sum + i ok next if sum = n return 1 else return 0 ok return sum  
Give a code snippet in #Ring Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself)...
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have download...
#Ada
Ada
  with Ada.Text_IO, Ada.Containers.Indefinite_Vectors; use Ada.Text_IO;   procedure Ordered_Words is package Word_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); use Word_Vectors; File : File_Type; Ordered_Words : Vector; Max_Length : Positive := ...
Give a code snippet in #Ada An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally ...
christopher/rosetta-code
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#Ksh
Ksh
  #!/bin/ksh   # Produce a zig-zag array.   # # Variables: # integer DEF_SIZE=5 # Default size = 5 arr_size=${1:-$DEF_SIZE} # $1 = size, or default   # # Externals: #   # # Functions: #     ###### # main # ###### integer i j n typeset -a zzarr   for (( i=n=0; i<arr_size*2; i++ )); do for (( j= (i<arr_size)...
Give a code snippet in #Ksh Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encod...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#PL.2FpgSQL
PL/pgSQL
CREATE OR REPLACE FUNCTION fib(n INTEGER) RETURNS INTEGER AS $$ BEGIN IF (n < 2) THEN RETURN n; END IF; RETURN fib(n - 1) + fib(n - 2); END; $$ LANGUAGE plpgsql;
Give a code snippet in #PL.2FpgSQL The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solution...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#XSLT
XSLT
<xsl:for-each select="nodes[@value mod 2 = 0]"> <xsl:value-of select="@value" /> </xsl:for-each>
Give a code snippet in #XSLT Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#Ada
Ada
package String_Vec is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String);   use type String_Vec.Vector;
Give a code snippet in #Ada Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false va...
christopher/rosetta-code
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Befunge
Befunge
0" :raeY">:#,_&>\" :htnoM">:#,_&>04p" :yaD">:#,_$&>55+,1-:47*v v"f I".+1%,,,,"Day I":$_:#<0#!4#:p#-4#1g4-#0+#<<_v#!*!-2g40!-< >"o",,,/:5+*66++:4>g#<:#44#:9#+*#1-#,_$$0 v_v#!< >$ 0 "yaD " v @,+55.+*+92"j"$_,#!>#:<", in the YOLD"*84 <.>,:^ :"St. Tib's"< $# #"#"##"#"Chaos$Discord$Confusion$Bureaucracy$The Aftermath$
Give a code snippet in #Befunge Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
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 ...
#Qi
Qi
  (define remove-element 0 [_ | R] -> R Pos [A | R] -> [A | (remove-element (1- Pos) R)])   (define get-element Pos R -> (nth (1+ Pos) R))   (define shuffle-0 Pos R -> [(get-element Pos R) | (shuffle (remove-element Pos R))])   (define shuffle [] -> [] R -> (shuffle-0 (RANDOM (length R)) R))   (define in...
Give a code snippet in #Qi Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort ...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#S-BASIC
S-BASIC
  $constant DOOR_OPEN = 1 $constant DOOR_CLOSED = 0 $constant MAX_DOORS = 100   var i, j = integer dim integer doors(MAX_DOORS)   rem - all doors are initially closed for i = 1 to MAX_DOORS doors(i) = DOOR_CLOSED next i   rem - cycle through at increasing intervals and flip doors for i = 1 to MAX_DOORS for j = i to...
Give a code snippet in #S-BASIC There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...
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,...
#Julia
Julia
using Requests, Printf   function getusnotime() const url = "http://tycho.usno.navy.mil/timer.pl" s = try get(url) catch err @sprintf "get(%s)\n => %s" url err end isa(s, Requests.Response) || return (s, false) t = match(r"(?<=<BR>)(.*?UTC)", readstring(s)) isa(t, Regex...
Give a code snippet in #Julia 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 pa...
christopher/rosetta-code
http://rosettacode.org/wiki/Partition_function_P
Partition function P
The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers. Example P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1) P(n) can be expressed as the recurrence relation: P(n) = P(n-1) +P(n-2) -P(n-5) -P(n-7)...
#C.2B.2B
C++
#include <chrono> #include <iostream> #include <vector> #include <gmpxx.h>   using big_int = mpz_class;   big_int partitions(int n) { std::vector<big_int> p(n + 1); p[0] = 1; for (int i = 1; i <= n; ++i) { for (int k = 1;; ++k) { int j = (k * (3*k - 1))/2; if (j > i) ...
Give a code snippet in #C.2B.2B The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers. Example P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1) P(n) can be expressed as the recurrence relation: P(n)...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, sho...
#Clojure
Clojure
;; Wrap line naive version (defn wrap-line [size text] (loop [left size line [] lines [] words (clojure.string/split text #"\s+")] (if-let [word (first words)] (let [wlen (count word) spacing (if (== left size) "" " ") alen (+ (count spacing) wlen)] (if (<= alen left...
Give a code snippet in #Clojure Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#ooRexx
ooRexx
  say "a 3x3 identity matrix" say call printMatrix createIdentityMatrix(3) say say "a 5x5 identity matrix" say call printMatrix createIdentityMatrix(5)   ::routine createIdentityMatrix use arg size matrix = .array~new(size, size) loop i = 1 to size loop j = 1 to size if i == j then matrix[i, j] = ...
Give a code snippet in #ooRexx Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#PicoLisp
PicoLisp
(de repString (Str) (let Lst (chop Str) (for (N (/ (length Lst) 2) (gt0 N) (dec N)) (T (use (Lst X) (let H (cut N 'Lst) (loop (setq X (cut N 'Lst)) (NIL (head X H)) (NIL Lst T) ) ) ) ...
Give a code snippet in #PicoLisp Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at l...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#Cowgol
Cowgol
sub multiply(a: int32, b: int32): (rslt: int32) is rslt := a * b; end sub
Give a code snippet in #Cowgol A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print str...
#Clojure
Clojure
(defn strip [coll chars] (apply str (remove #((set chars) %) coll)))   (strip "She was a soul stripper. She took my heart!" "aei") ;; => "Sh ws soul strppr. Sh took my hrt!"
Give a code snippet in #Clojure Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#AppleScript
AppleScript
set i1 to (text returned of (display dialog "Enter an integer value" default answer "")) as integer set i2 to (text returned of (display dialog "Enter another integer value" default answer "")) as integer   set sum to i1 + i2 set diff to i1 - i2 set prod to i1 * i2 set quot to i1 div i2 -- Rounds towards zero. set rema...
Give a code snippet in #AppleScript 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 Opera...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#ERRE
ERRE
  PROGRAM ROMAN2ARAB   DIM R%[7]   PROCEDURE TOARAB(ROMAN$->ANS%) LOCAL I%,J%,P%,N% FOR I%=LEN(ROMAN$) TO 1 STEP -1 DO J%=INSTR("IVXLCDM",MID$(ROMAN$,I%,1)) IF J%=0 THEN ANS%=-9999  ! illegal character EXIT PROCEDURE END IF IF J%>=P% THEN N...
Give a code snippet in #ERRE Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, sta...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#F.23
F#
  let sum35 n = Seq.init n (id) |> Seq.reduce (fun sum i -> if i % 3 = 0 || i % 5 = 0 then sum + i else sum)   printfn "%d" (sum35 1000) printfn "----------"   let sumUpTo (n : bigint) = n * (n + 1I) / 2I   let sumMultsBelow k n = k * (sumUpTo ((n-1I)/k))   let sum35fast n = (sumMultsBelow 3I n) + (sumMultsBelow 5I n) ...
Give a code snippet in #F.23 Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
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 ...
#Verilog
Verilog
  if( expr_booleana ) command1; else command2;  
Give a code snippet in #Verilog 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/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337346448646612254452369009474497523...
#EchoLisp
EchoLisp
  (lib 'bigint)   (define a 2988348162058574136915891421498819466320163312926952423791023078876139) (define b 2351399303373464486466122544523690094744975233415544072992656881240319) (define m 1e40)   (powmod a b m) → 1527229998585248450016808958343740453059   ;; powmod is a native function ;; it could be defined as...
Give a code snippet in #EchoLisp Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 23513993033...
christopher/rosetta-code
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and...
#Phix
Phix
with javascript_semantics sequence table bool have_table = false function crc32(string s) if not have_table then have_table = true table = repeat(0,256) for i=0 to 255 do atom rem = i for j=1 to 8 do if and_bits(rem,1) then rem = ...
Give a code snippet in #Phix Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the...
#Rust
Rust
extern crate libc;   //c function that returns the sum of two integers extern { fn add_input(in1: libc::c_int, in2: libc::c_int) -> libc::c_int; }   fn main() { let (in1, in2) = (5, 4); let output = unsafe { add_input(in1, in2) }; assert!( (output == (in1 + in2) ),"Error in sum calculation") ; }
Give a code snippet in #Rust Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can b...
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
#m4
m4
include(filename)
Give a code snippet in #m4 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/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In ...
#AWK
AWK
  # syntax: gawk -M -f hamming_numbers.awk BEGIN { for (i=1; i<=20; i++) { printf("%d ",hamming(i)) } printf("\n1691: %d\n",hamming(1691)) printf("\n1000000: %d\n",hamming(1000000)) exit(0) } function hamming(limit, h,i,j,k,n,x2,x3,x5) { h[0] = 1 x2 = 2 x3 = 3 x5 = 5 for (...
Give a code snippet in #AWK Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming number...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#ML
ML
  (* 1.64393456668 *) List.foldl op+ 0.0 (List.tabulate(1000, fn x => 1.0 / Math.pow(real(x + 1),2.0)))  
Give a code snippet in #ML Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pragmatic_directives
Pragmatic directives
Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstrate how to activate and deactivate...
#PicoLisp
PicoLisp
declare (t(100),i) fixed binary; i=101; t(i)=0;
Give a code snippet in #PicoLisp Pragmatic directives cause the language to operate in a specific manner,   allowing support for operational variances within the program code   (possibly by the loading of specific or alternative modules). Task List any pragmatic directives supported by the language,   and demonstr...
christopher/rosetta-code
http://rosettacode.org/wiki/Holidays_related_to_Easter
Holidays related to Easter
Task Calculate the dates of:   Easter   Ascension Thursday   Pentecost   Trinity Sunday   Corpus Christi feast (for Catholic)   All Saints' Sunday (for Orthodox) As an example, calculate for the first year of each century from;   years     400   to   2100 CE   and for   years   2010   to   2020 CE. Note ...
#Kotlin
Kotlin
// version 1.1.2   import java.util.Calendar import java.util.GregorianCalendar   val holidayOffsets = listOf( "Easter" to 0, "Ascension" to 39, "Pentecost" to 49, "Trinity" to 56, "C/Christi" to 60 )   fun String.padCenter(n: Int): String { val len = this.length if (n <= len) return this...
Give a code snippet in #Kotlin Task Calculate the dates of:   Easter   Ascension Thursday   Pentecost   Trinity Sunday   Corpus Christi feast (for Catholic)   All Saints' Sunday (for Orthodox) As an example, calculate for the first year of each century from;   years     400   to   2100 CE   and for   yea...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#Plain_English
Plain English
To run: Start up. Create a list. Write each entry in the list to the console. Destroy the list. Wait for the escape key. Shut down.   An entry is a thing with a number.   A list is some entries.   To add a number to a list: Allocate memory for an entry. Put the number into the entry's number. Append the entry to the li...
Give a code snippet in #Plain_English Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue ...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#Forth
Forth
  \ Rosetta Code Knapp-sack 0-1 problem. Tested under GForth 0.7.3. \ 22 items. On current processors a set fits nicely in one CELL (32 or 64 bits). \ Brute force approach: for every possible set of 22 items, \ check for admissible solution then for optimal set.   : offs HERE over - ; 400 VALUE WLIMIT ...
Give a code snippet in #Forth A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have...
christopher/rosetta-code
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#uBasic.2F4tH
uBasic/4tH
Push 292929 : Gosub 100 : d = Pop()   For i = 1 To 10 Push 0 : Gosub 100 Print Pop() Next   End   100 s = Pop() If s = 0 Then p = (p + 1) % 55 @(p) = @(p) - @((p + 31) % 55) If @(p) < 0 Then @(p) = @(p) + 1000000000 Endif Push (@(p)) : Return Endif   @(54) = ...
Give a code snippet in #uBasic.2F4tH A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{...
christopher/rosetta-code
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#Elixir
Elixir
defmodule MutualRecursion do def f(0), do: 1 def f(n), do: n - m(f(n - 1)) def m(0), do: 0 def m(n), do: n - f(m(n - 1)) end   IO.inspect Enum.map(0..19, fn n -> MutualRecursion.f(n) end) IO.inspect Enum.map(0..19, fn n -> MutualRecursion.m(n) end)
Give a code snippet in #Elixir Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection
Factorial base numbers indexing permutations of a collection
You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers. The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0....
#Wren
Wren
import "random" for Random import "/math" for Int import "/fmt" for Fmt   var genFactBaseNums = Fn.new { |size, countOnly| var results = [] var count = 0 var n = 0 while (true) { var radix = 2 var res = null if (!countOnly) res = List.filled(size, 0) var k = n wh...
Give a code snippet in #Wren You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers. The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua...
#F.23
F#
  // Extend your language. Nigel Galloway: September 14th., 2021 type elsetf=TF type elseft=FT type elseff=FF let elsetf,elseft,elseff=TF,FT,FF let if2 n g tt (TF:elsetf)tf (FT:elseft)ft (FF:elseff)ff=match(n,g) with (true,true)->tt() |(true,false)->tf() |(false,true)->ft() |_->ff() if2 (13<23) (23<42) (fun()->printfn ...
Give a code snippet in #F.23 Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. ...
christopher/rosetta-code
http://rosettacode.org/wiki/One_of_n_lines_in_a_file
One of n lines in a file
A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of the file if possible and m...
#Maple
Maple
  with(RandomTools[MersenneTwister]); one_of_n_lines_in_a_file := proc(fn) local fid, N, n, L, l, line; fid := fopen(fn,'READ'); if fid<0 then return; end if; N := 0; n := 1; while not feof(fid) do N := N+1; L := FileTools[Text][ReadLine](fid); if (N*GenerateFloat() < 1) then n := N; line := L...
Give a code snippet in #Maple A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second lin...
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 ...
#Raku
Raku
class Line { has $.P0; # point has $.u⃗; # ray } class Plane { has $.V0; # point has $.n⃗; # normal }   sub infix:<∙> ( @a, @b where +@a == +@b ) { [+] @a «*» @b } # dot product   sub line-plane-intersection ($𝑳, $𝑷) { my $cos = $𝑷.n⃗ ∙ $𝑳.u⃗; # cosine between normal & ray return 'Vectors ...
Give a code snippet in #Raku 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/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced...
#PARI.2FGP
PARI/GP
install("truncate", "isL", "trunc")   trunc("/tmp/test.file", 20)
Give a code snippet in #PARI.2FGP Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by cre...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Sub split (s As String, sepList As String, result() As String, removeEmpty As Boolean = False) If s = "" OrElse sepList = "" Then Redim result(0) result(0) = s Return End If Dim As Integer i, j, count = 0, empty = 0, length Dim As Integer position(Len(s) + 1) position(0) = ...
Give a code snippet in #FreeBASIC Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#11l
11l
print(sum([1, 2, 3, 4, 5].map(x -> x^2)))
Give a code snippet in #11l Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
christopher/rosetta-code
http://rosettacode.org/wiki/Heronian_triangles
Heronian triangles
Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b + c 2 . {\displaystyle s...
#Go
Go
package main   import ( "fmt" "math" "sort" )   const ( n = 200 header = "\nSides P A" )   func gcd(a, b int) int { leftover := 1 var dividend, divisor int if (a > b) { dividend, divisor = a, b } else { dividend, divisor = b, a }   for (leftover != 0) { leftover = ...
Give a code snippet in #Go Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b +...
christopher/rosetta-code
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller prima...
#REXX
REXX
/*REXX program puts the Miller─Rabin primality test through its paces. */ parse arg limit times seed . /*obtain optional arguments from the CL*/ if limit=='' | limit=="," then limit= 1000 /*Not specified? Then use the default.*/ if times=='' | times=="," then times= 10 ...
Give a code snippet in #REXX This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primal...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#Red
Red
>> dehex "http%3A%2F%2Ffoo%20bar%2F" == "http://foo bar/" >> dehex "google.com/search?q=%60Abdu%27l-Bah%C3%A1" == "google.com/search?q=`Abdu'l-Bahá"
Give a code snippet in #Red This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded fo...
christopher/rosetta-code
http://rosettacode.org/wiki/Rate_counter
Rate counter
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish these goals: Run N seconds worth...
#Jsish
Jsish
#!/usr/bin/env jsish "use strict"; /* Rate counter, timer access, in Jsish */   /* System time in milliseconds */ var runs = 0, newMs; function countJobsIsTheJob() { runs += 1; } var milliSeconds = strptime(); while ((newMs = strptime()) < (milliSeconds + 1000)) { countJobsIsTheJob(); } puts(runs, 'runs in', newMs - mi...
Give a code snippet in #Jsish Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish the...
christopher/rosetta-code
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
HailstoneF[n_] := NestWhileList[If[OddQ[#], 3 # + 1, #/2] &, n, # > 1 &]
Give a code snippet in #Mathematica_.2F_Wolfram_Language The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the...
christopher/rosetta-code
http://rosettacode.org/wiki/Jensen%27s_Device
Jensen's Device
Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report. The following pr...
#FreeBASIC
FreeBASIC
Sub Evaluation Dim As Integer i, lo = 1, hi = 100 Dim As Double temp = 0 For i = lo To hi temp += (1/i) ''r(i) Next i Print temp End Sub   Evaluation Sleep
Give a code snippet in #FreeBASIC Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the...
christopher/rosetta-code
http://rosettacode.org/wiki/String_matching
String matching
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#K
K
startswith: {:[0<#p:_ss[x;y];~*p;0]} endswith: {0=(-#y)+(#x)-*_ss[x;y]} contains: {0<#_ss[x;y]}
Give a code snippet in #K 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 Conc...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Bracmat
Bracmat
( reverse = L x .  :?L & @( !arg  :  ? ( %?x & utf$!x & !x !L:?L & ~` )  ? ) | str$!L ) & out$reverse$Ελληνικά
Give a code snippet in #Bracmat Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Emp...
christopher/rosetta-code
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can decid...
#Processing
Processing
IntList drawers = new IntList(); int trials = 100000; int succes_count;   void setup() { for (int i = 0; i < 100; i++) { drawers.append(i); } println(trials + " trials\n");   //Random strategy println("Random strategy"); succes_count = trials; for (int i = 0; i < trials; i++) { drawers.shuffle(); ...
Give a code snippet in #Processing The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners st...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/String
Literals/String
Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Here document Other tasks r...
#Julia
Julia
greet = "Hello" whom = "world" greet * ", " * whom * "."
Give a code snippet in #Julia Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters  ...
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...
#Elena
Elena
import extensions;   extension op : IntNumber { bool randN() = randomGenerator.nextInt(self) == 0;   get bool Unbiased() { bool flip1 := self.randN(); bool flip2 := self.randN();   while (flip1 == flip2) { flip1 := self.randN(); flip2 := self.r...
Give a code snippet in #Elena 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Sidef
Sidef
func urandom() { const device = %f'/dev/urandom';   device.open('<:raw', \var fh, \var err) -> || die "Can't open `#{device}': #{err}";   fh.sysread(\var noise, 4); 'L'.unpack(noise); }   say urandom(); # sample: 3517432564
Give a code snippet in #Sidef Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Raku
Raku
my $s = "12345"; $s++;
Give a code snippet in #Raku Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#F.23
F#
let factors number = seq { for divisor in 1 .. (float >> sqrt >> int) number do if number % divisor = 0 then yield divisor if number <> 1 then yield number / divisor //special case condition: when number=1 then divisor=(number/divisor), so don't repeat it }
Give a code snippet in #F.23 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 C...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_with_repetitions
Combinations with repetitions
The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member of those sets is chosen from S...
#Fortran
Fortran
  program main integer :: chosen(4) integer :: ssize   character(len=50) :: donuts(4) = [ "iced", "jam", "plain", "something completely different" ]   ssize = choose( chosen, 2, 3 ) write(*,*) "Total = ", ssize   contains   recursive function choose( got, len, maxTypes, nChosen, at ) result ( output ) integer ...
Give a code snippet in #Fortran The set of combinations with repetitions is computed from a set, S {\displaystyle S} (of cardinality n {\displaystyle n} ), and a size of resulting selection, k {\displaystyle k} , by reporting the sets of cardinality k {\displaystyle k} where each member o...
christopher/rosetta-code
http://rosettacode.org/wiki/Julia_set
Julia set
Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
#Lua
Lua
local cmap = { [0]=" ", ".", ":", "-", "=", "+", "*", "#", "%", "$", "@" } for y = -1.0, 1.0, 0.05 do for x = -1.5, 1.5, 0.025 do local zr, zi, i = x, y, 0 while i < 100 do zr, zi = zr*zr - zi*zi - 0.79, zr * zi * 2 + 0.15 if (zr*zr + zi*zi > 4) then break else i = i + 1 end end io.write(c...
Give a code snippet in #Lua Task Generate and draw a Julia set. Related tasks   Mandelbrot Set
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#SETL
SETL
print({0..4} npow 3);
Give a code snippet in #SETL 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Nautical_bell
Nautical bell
Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off a scheduler, and it is per...
#Phix
Phix
with javascript_semantics constant watches = {"First","Middle","Morning","Forenoon","Afternoon","First dog","Last dog","First"}, watch_ends = {"00:00", "04:00", "08:00", "12:00", "16:00", "18:00", "20:00", "23:59"}, bells = {"One","Two","Three","Four","Five","Six","Seven","Eight"}, ding = "di...
Give a code snippet in #Phix Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave ...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#FreeBASIC
FreeBASIC
  Const alphanum = "0123456789abcdefghijklmnopqrstuvwxyz"   Function ToDecimal (cadena As String, base_ As Uinteger) As Uinteger Dim As Uinteger i, n, result = 0 Dim As Uinteger inlength = Len(cadena)   For i = 1 To inlength n = Instr(alphanum, Mid(Lcase(cadena),i,1)) - 1 n *= (base_^(inlen...
Give a code snippet in #FreeBASIC This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unenco...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance m...
#Objective-C
Objective-C
// Class [MyClass method:someParameter]; // or equivalently: id foo = [MyClass class]; [foo method:someParameter];   // Instance [myInstance method:someParameter];   // Method with multiple arguments [myInstance methodWithRed:arg1 green:arg2 blue:arg3];   // Method with no arguments [myInstance method];
Give a code snippet in #Objective-C In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a stat...
christopher/rosetta-code
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#8th
8th
\ assuming the var 'db' contains an opened database with a schema matching the problem: db @ "UPDATE players SET name=?1,score=?2,active=?3 WHERE jerseyNum=?4" db:prepare var, stmt   \ bind values to the statement: stmt @ 1 "Smith, Steve" db:bind 2 42 db:bind 3 true db:bind 4 99 db:bind   \ execut...
Give a code snippet in #8th SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don'...
christopher/rosetta-code
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#PureBasic
PureBasic
IncludeFile "Decimal.pbi"   ;- Declare the variables that will be used Define.Decimal *a Define n, L$, R$, out$, digits.s   ;- 4^3^2 is withing 32 bit range, so normal procedures can be used n=Pow(4,Pow(3,2))   ;- 5^n is larger then 31^2, so the same library call as in the "Long multiplication" task is used *a=PowerDec...
Give a code snippet in #PureBasic Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#VBScript
VBScript
  option explicit Class prio_queue private size private q   'adapt this function to your data private function out_of_order(f1,f2): out_of_order = f1(0)>f2(0):end function   function peek peek=q(1) end function   property get qty qty=size end property   property get isempty isempty=(size=...
Give a code snippet in #VBScript A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in p...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Erlang
Erlang
>lists:max([9,4,3,8,5]). 9
Give a code snippet in #Erlang Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#CFScript
CFScript
isNumeric(42)
Give a code snippet in #CFScript 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...
christopher/rosetta-code
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#C
C
#include <stdio.h> #include <ctype.h>   int can_make_words(char **b, char *word) { int i, ret = 0, c = toupper(*word);   #define SWAP(a, b) if (a != b) { char * tmp = a; a = b; b = tmp; }   if (!c) return 1; if (!b[0]) return 0;   for (i = 0; b[i] && !ret; i++) { if (b[i][0] != c && b[i][1] != c) continue; SWAP...
Give a code snippet in #C ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is...
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#C.2B.2B
C++
::Bool = False | True
Give a code snippet in #C.2B.2B Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Color_wheel
Color wheel
Task Write a function to draw a HSV color wheel completely with code. This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel   (as procedurally drawing is super slow). This does help you understand how color wheels work and ...
#Phix
Phix
-- -- demo\rosetta\Colour_wheel.exw -- ============================= -- -- Note: Made non-resizeable since maximising this is far too slow. -- with javascript_semantics include pGUI.e constant title = "Colour wheel" Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas function redraw_cb(Ihandle /*ih*/, integer /*posx*/,...
Give a code snippet in #Phix Task Write a function to draw a HSV color wheel completely with code. This is strictly for learning purposes only. It's highly recommended that you use an image in an actual application to actually draw the color wheel   (as procedurally drawing is super slow). This does help you underst...
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...
#Icon_and_Unicon
Icon and Unicon
procedure main() local i i := 1024 while write(0 < (i := i / 2)) end
Give a code snippet in #Icon_and_Unicon 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   Loo...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Amazing_Hopper
Amazing Hopper
  #include <hopper.h> main: first matrix=0, second matrix=0,a=-1 {5,2},rand array(a),mulby(10),ceil, cpy(first matrix), puts,{"\n"},puts {2,3},rand array(a),mulby(10),ceil, cpy(second matrix), puts,{"\n"},puts {first matrix,second matrix},mat mul, println exit(0)  
Give a code snippet in #Amazing_Hopper Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Iterated_digits_squaring
Iterated digits squaring
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lambda x: x if x in [1, 89] else i...
#Forth
Forth
  Tested for VFX Forth and GForth in Linux \ To explain the algorithm: Each iteration is performed in set-count-sumsq below. \ sum square of digits for 1 digit numbers are \ Base 1 2 3 4 5 6 7 8 9 \ Sumsq: 1 4 9 16 25 36 49 54 81 \ Adding 10 to the base adds 1 to the sumsq, \ Adding 20 to the base adds...
Give a code snippet in #Forth If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lam...
christopher/rosetta-code
http://rosettacode.org/wiki/Minesweeper_game
Minesweeper game
There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid...
#Haskell
Haskell
{-# LANGUAGE TemplateHaskell #-}   module MineSweeper ( Board , Cell(..) , CellState(..) , Pos -- lenses / prisms , pos , coveredLens , coveredFlaggedLens , coveredMinedLens , xCoordLens , yCoordLens -- Functions , emptyBoard , groupedByRows , displayCell , isLoss , isWin , expos...
Give a code snippet in #Haskell There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coo...
christopher/rosetta-code
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#EchoLisp
EchoLisp
  (require 'struct)   (struct TM (read-only: name states symbs final rules mem state-values: tape pos state))   (define-syntax-rule (rule-idx state symb numstates) (+ state (* symb numstates)))   (define-syntax-rule (make-TM name states symbs rules) (_make-TM name 'states 'symbs 'rules))   ;; a rule is (stat...
Give a code snippet in #EchoLisp One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing mach...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble 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 byToSort As Byte[] = [249, 28, 111, 36, 171, 98, 29, 448, 44, 147, 154, 46, 102, 183, 24, 120, 19, 123, 2, 17, 226, 11, 211, 25, 191, 205, 77] Dim byCount As Byte Dim bSorting As Boolean   Print "To sort: -" ShowWorking(byToSort) Print Repeat bSorting = False For byC...
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/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of...
#Wren
Wren
var egyptianDivide = Fn.new { |dividend, divisor| if (dividend < 0 || divisor <= 0) Fiber.abort("Invalid argument(s).") if (dividend < divisor) return [0, dividend] var powersOfTwo = [1] var doublings = [divisor] var doubling = divisor while (true) { doubling = 2 * doubling if (d...
Give a code snippet in #Wren Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, an...
christopher/rosetta-code
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task ...
#D
D
import std.stdio;   immutable PRIMES = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 2...
Give a code snippet in #D Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#R
R
  rotate_string <- function(x, forwards) {    nchx <- nchar(x)    if(forwards)    {                                         paste(substr(x, nchx, nchx), substr(x, 1, nchx - 1), sep = "")    } else    {                                                                 paste(substr(x, 2, nchx), substr(x, 1, 1), sep...
Give a code snippet in #R Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demons...
christopher/rosetta-code
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro...
#Prolog
Prolog
rpath([target|reversed_path], distance)
Give a code snippet in #Prolog This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the...
christopher/rosetta-code
http://rosettacode.org/wiki/Pinstripe/Printer
Pinstripe/Printer
The task is to demonstrate the creation of a series of 1 point wide vertical pinstripes with a sufficient number of pinstripes to span the entire width of the printed page (except for the last pinstripe). The pinstripes should alternate one point white, one point black. (Where the printer does not support producing gra...
#Racket
Racket
  #lang racket/gui   (define parts 4)   (define dc (new printer-dc%)) (send* dc (start-doc "Pinstripe") (start-page))   (define-values [W H] (send dc get-size)) (send dc set-pen "black" 0 'solid) (send dc set-brush "black" 'solid) (define H* (round (/ H parts))) (for ([row parts]) (define Y (* row H*)) (for ([X (in...
Give a code snippet in #Racket The task is to demonstrate the creation of a series of 1 point wide vertical pinstripes with a sufficient number of pinstripes to span the entire width of the printed page (except for the last pinstripe). The pinstripes should alternate one point white, one point black. (Where the printe...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Traversal
Singly-linked list/Traversal
Traverse from the beginning of a singly-linked list to the end. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked ...
#Axe
Axe
LINK(L₁,1)→A LINK(L₁+10,2)→B LINK(L₁+50,3)→C   INSERT(A,B) INSERT(A,C)   A→I While I≠0 Disp VALUE(I)▶Dec,i NEXT(I)→I End
Give a code snippet in #Axe Traverse from the beginning of a singly-linked list to the end. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definitio...
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#Elixir
Elixir
defmodule Harshad do def series, do: Stream.iterate(1, &(&1+1)) |> Stream.filter(&(number?(&1)))   def number?(n), do: rem(n, digit_sum(n, 0)) == 0   defp digit_sum(0, sum), do: sum defp digit_sum(n, sum), do: digit_sum(div(n, 10), sum + rem(n, 10)) end   IO.inspect Harshad.series |> Enum.take(20)   IO.inspect ...
Give a code snippet in #Elixir The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task...
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...
#Clojure
Clojure
(defn flip-at [n coll] (let [[x y] (split-at n coll)] (concat (reverse x) y )))   (def sorted '(1 2 3 4 5 6 7 8 9)) ; i.e. (range 1 10) (def unsorted? #(not= % sorted))   (loop [unsorted (first (filter unsorted? (iterate shuffle sorted))), steps 0] (if (= unsorted sorted) (printf "Done! That took you %d st...
Give a code snippet in #Clojure 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. R...
#Nim
Nim
import strutils   proc cline(n, x, y: int, cde: string) = echo cde[0..0].align n+1, repeat(cde[1], 9*x-1), cde[0], if cde.len > 2: cde[2..2].align y+1 else: ""   proc cuboid(x, y, z: int) = cline y+1, x, 0, "+-" for i in 1..y: cline y-i+1, x, i-1, "/ |" cline 0, x, y, "+-|" for i in 0..4*z-y-3: cl...
Give a code snippet in #Nim Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is a...
christopher/rosetta-code
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#REXX
REXX
/*REXX program displays results of probabilistic choices, gen random #s per probability.*/ parse arg trials digs seed . /*obtain the optional arguments from CL*/ if trials=='' | trials=="," then trials= +1e6 /*Not specified? Then use the default.*/ if digs=='' | digs=="," then digs= 15 ...
Give a code snippet in #REXX Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floa...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Find_unimplemented_tasks
Rosetta Code/Find unimplemented tasks
Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out about locally, here, or in Media...
#Phix
Phix
-- demo\rosetta\Find_unimplemented_tasks.exw without js -- (libcurl, file i/o, peek, progress..) constant language = "Phix", -- language = "Go", -- language = "Julia", -- language = "Python", -- language = "Wren", base_query = "http://rosettacode.org/mw/api.php?action=query"& ...
Give a code snippet in #Phix Task Given the name of a language on Rosetta Code, find all tasks which are not implemented in that language. Note: Implementations should allow for fetching more data than can be returned in one request to Rosetta Code. You'll need to use the Media Wiki API, which you can find out ab...
christopher/rosetta-code
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number...
#Wren
Wren
var mcnugget = Fn.new { |limit| var sv = List.filled(limit+1, false) var s = 0 while (s <= limit) { var n = s while (n <= limit) { var t = n while (t <= limit) { sv[t] = true t = t + 20 } n = n + 9 } ...
Give a code snippet in #Wren Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNug...
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...
#F.C5.8Drmul.C3.A6
Fōrmulæ
Dim As Integer fact(12), suma, d, j fact(0) = 1 For n As Integer = 1 To 11 fact(n) = fact(n-1) * n Next n For b As Integer = 9 To 12 Print "Los factoriones para base " & b & " son: " For i As Integer = 1 To 1499999 suma = 0 j = i While j > 0 d = j Mod b suma +...
Give a code snippet in #F.C5.8Drmul.C3.A6 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#E
E
def map(f, list) { var out := [] for x in list { out with= f(x) } return out }   ? map(fn x { x + x }, [1, "two"]) # value: [2, "twotwo"]   ? map(1.add, [5, 10, 20]) # value: [6, 11, 21]   ? def foo(x) { return -(x.size()) } > map(foo, ["", "a", "bc"]) # value: [0, -1, -2]
Give a code snippet in #E Task Pass a function     as an argument     to another function. Related task   First-class functions
christopher/rosetta-code
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on thei...
#Wren
Wren
import "/math" for Math   var Two = "Two circles." var R0 = "R == 0 does not describe circles." var Co = "Coincident points describe an infinite number of circles." var CoR0 = "Coincident points with r == 0 describe a degenerate circle." var Diam = "Points form a diameter and describe only a single circle." var Fa...
Give a code snippet in #Wren Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of ...
christopher/rosetta-code
http://rosettacode.org/wiki/IBAN
IBAN
This page uses content from Wikipedia. The original article was at IBAN. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   International Bank Account Number (IBAN)   is an internationally agree...
#Lua
Lua
local length= { AL=28, AD=24, AT=20, AZ=28, BH=22, BE=16, BA=20, BR=29, BG=22, CR=21, HR=21, CY=28, CZ=24, DK=18, DO=28, EE=20, FO=18, FI=18, FR=27, GE=22, DE=22, GI=23, GR=27, GL=18, GT=28, HU=28, IS=26, IE=22, IL=23, IT=27, JO=30, KZ=20, KW=30, LV=21, LB=28, LI=21, LT=20, LU=20, MK=19, MT=31, MR=27, MU=30, ...
Give a code snippet in #Lua This page uses content from Wikipedia. The original article was at IBAN. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   International Bank Account Number (IBAN) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Topic_variable
Topic variable
Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate h...
#BASIC256
BASIC256
function Sum (x, y) Sum = x + y # using name of function end function   function SumR (x, y) return x + y # using Return keyword which always returns immediately end function   print Sum (1, 2) print SumR(2, 3)
Give a code snippet in #BASIC256 Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic variable within the lan...
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...
#Sidef
Sidef
# Returns a copy of 's' with rot13 encoding. func rot13(s) { s.tr('A-Za-z', 'N-ZA-Mn-za-m'); }   # Perform rot13 on standard input. STDIN.each { |line| print rot13(line) }
Give a code snippet in #Sidef 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Concurrent_computing
Concurrent computing
Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
#Cind
Cind
  execute() { {# host.println("Enjoy"); # host.println("Rosetta"); # host.println("Code"); } }  
Give a code snippet in #Cind Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your la...
christopher/rosetta-code
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the i...
#Lua
Lua
-- Requires LuaSocket extension by Lua -- Created by James A. Donnell Jr. -- www.JamesDonnell.com   local baseURL = "http://api.macvendors.com/"   local function lookup(macAddress) http = require "socket.http" result, statuscode, content = http.request(baseURL .. macAddress) return result end   local macAddress = "F...
Give a code snippet in #Lua Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numer...
christopher/rosetta-code
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#Tcl
Tcl
set string alphaBETA   # three built-in case conversion commands string toupper $string ;# ==> ALPHABETA string tolower $string ;# ==> alphabeta string totitle $string ;# ==> Alphabeta   # not built-in proc swapcase {s} { foreach char [split $s ""] { if {$char eq [set CHAR [string toupper $char]]} { ...
Give a code snippet in #Tcl Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not rev...
christopher/rosetta-code
http://rosettacode.org/wiki/Concurrent_computing
Concurrent computing
Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
#Julia
Julia
words = ["Enjoy", "Rosetta", "Code"]   function sleepprint(s) sleep(rand()) println(s) end   @sync for word in words @async sleepprint(word) end
Give a code snippet in #Julia Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your l...
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...
#Quackery
Quackery
[ $ 'bigrat.qky' loadfile ] now!   [ [] swap times [ 20001 random 10000 - n->v 100 n->v v/ join nested join ] ] is makevector ( --> [ )   [ witheach [ unpack 2 point$ echo$ i 0 > if [ say ", " ] ] ] is echodecs ( [ --> )   [ dup size n->v rot...
Give a code snippet in #Quackery Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an e...
christopher/rosetta-code
http://rosettacode.org/wiki/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....
#BBC_BASIC
BBC BASIC
DIM x(9), y(9) 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.3, 180.0   ORIGIN 100,100 VDU 23,23,2;0;0;0; VDU 5   FOR x = 1 TO 9 GCOL 7 : LINE 100*x,720,100*x,0 GCOL 0 : PLOT 0,-10,-4 :...
Give a code snippet in #BBC_BASIC 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, 3...
christopher/rosetta-code
http://rosettacode.org/wiki/Snake
Snake
This page uses content from Wikipedia. The original article was at Snake_(video_game). 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) Snake is a game where the player maneuvers a line which grows i...
#Raku
Raku
use SDL2::Raw; use Cairo;   constant W = 1280; constant H = 960;   constant FIELDW = W div 32; constant FIELDH = H div 32;   SDL_Init(VIDEO);   my $window = SDL_CreateWindow( 'Snake', SDL_WINDOWPOS_CENTERED_MASK, SDL_WINDOWPOS_CENTERED_MASK, W, H, OPENGL );   my $render = SDL_CreateRenderer($window,...
Give a code snippet in #Raku This page uses content from Wikipedia. The original article was at Snake_(video_game). 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) Snake is a game where the player ...
christopher/rosetta-code