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/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 ...
#.D0.9C.D0.9A-61.2F52
МК-61/52
П0 1 lg Вx <-> + L0 03 С/П БП 03
Give a code snippet in #.D0.9C.D0.9A-61.2F52 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 recursiv...
christopher/rosetta-code
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#Raku
Raku
say ' type n n**n exp(n,n)'; say '-------- -------- -------- --------';   for 0, 0.0, FatRat.new(0), 0e0, 0+0i { printf "%8s  %8s  %8s  %8s\n", .^name, $_, $_**$_, exp($_,$_); }
Give a code snippet in #Raku Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic-geometric_mean
Arithmetic-geometric mean
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a function to compute the arithmetic-geomet...
#Quackery
Quackery
[ $ "bigrat.qky" loadfile ] now!   [ temp put [ 2over 2over temp share approx= iff 2drop done 2over 2over v* temp share vsqrt drop dip [ dip [ v+ 2 n->v v/ ] ] again ] base share temp take ** round ] is agm ( n/d n/d n --> n/d )   1 n->v 2 n->v 125 vsqrt drop 1/v 12...
Give a code snippet in #Quackery This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Write a functio...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#LiveCode
LiveCode
function lastFriday yyyy -- year,month num,day of month,hour in 24-hour time,minute,second,numeric day of week. convert the long date to dateitems put 1 into item 2 of it put 1 into item 3 of it put yyyy into item 1 of it put it into startDate convert startDate to dateItems repeat with m...
Give a code snippet in #LiveCode Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2...
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...
#FreeBASIC
FreeBASIC
Dim Shared As String texto, dividido()   texto = "In olden times when wishing still helped one, there lived a king " &_ "whose daughters were all beautiful, but the youngest was so beautiful "&_ "that the sun itself, which has seen so much, was astonished whenever "&_ "it shone-in-her-face. Close-by-the-king's castle ...
Give a code snippet in #FreeBASIC 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 ...
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
#Inform_6
Inform 6
let B be whether or not 123 is greater than 100;
Give a code snippet in #Inform_6 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/Stream_merge
Stream merge
2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was. N-strea...
#Scala
Scala
def mergeN[A : Ordering](is: Iterator[A]*): Iterator[A] = is.reduce((a, b) => merge2(a, b))   def merge2[A : Ordering](i1: Iterator[A], i2: Iterator[A]): Iterator[A] = { merge2Buffered(i1.buffered, i2.buffered) }   def merge2Buffered[A](i1: BufferedIterator[A], i2: BufferedIterator[A])(implicit ord: Ordering[A]): Ite...
Give a code snippet in #Scala 2-stream merge Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink. Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#Forth
Forth
: stack ( size -- ) create here cell+ , cells allot ;   : push ( n st -- ) tuck @ ! cell swap +! ; : pop ( st -- n ) -cell over +! @ @ ; : empty? ( st -- ? ) dup @ - cell+ 0= ;   10 stack st   1 st push 2 st push 3 st push st empty? . \ 0 (false) st pop . st pop . st pop . \ 3 2 1 st empty? . \ -1 (true)
Give a code snippet in #Forth Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is ac...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Break
Loops/Break
Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If the number 10 is never gener...
#Maxima
Maxima
/* To exit the innermost block, use return(<value>) */   block([n], do ( n: random(20), ldisp(n), if n = 10 then return(), n: random(20), ldisp(n) ) )$   /* To exit any level of block, use catch(...) and throw(<value>); they are not used for catching exceptions, but for non-local ret...
Give a code snippet in #Maxima Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Randomize Dim n As Integer = Int(Rnd * 20) + 1 Dim guess As Integer   Print "Guess which number I've chosen in the range 1 to 20" Print Do Input " Your guess : "; guess If guess > n AndAlso guess <= 20 Then Print "Your guess is higher than the chosen number, try again " ElseIf guess = n Th...
Give a code snippet in #FreeBASIC Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is:...
christopher/rosetta-code
http://rosettacode.org/wiki/Set_consolidation
Set consolidation
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input sets if they share a common item...
#Raku
Raku
multi consolidate() { () } multi consolidate(Set \this is copy, *@those) { gather { for consolidate |@those -> \that { if this ∩ that { this = this ∪ that } else { take that } } take this; } }   enum Elems <A B C D E F G H I J K>; say $_, "\n ==> ", c...
Give a code snippet in #Raku Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input se...
christopher/rosetta-code
http://rosettacode.org/wiki/Faces_from_a_mesh
Faces from a mesh
A mesh defining a surface has uniquely numbered vertices, and named, simple-polygonal faces described usually by an ordered list of edge numbers going around the face, For example: External image of two faces Rough textual version without edges: 1 17 7 A B ...
#Phix
Phix
with javascript_semantics function perequiv(sequence a, b) -- Works by aligning and rotating in one step, so theoretically much faster on massive sets. -- (ahem, faster than multiple rotates, index-only loops would obviously be even faster...) bool res = (length(a)==length(b)) if res and length(a)>0 then ...
Give a code snippet in #Phix A mesh defining a surface has uniquely numbered vertices, and named, simple-polygonal faces described usually by an ordered list of edge numbers going around the face, For example: External image of two faces Rough textual version without edges: 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#FreeBASIC
FreeBASIC
' FB 1.05.0   Sub sieve(n As Integer) If n < 2 Then Return Dim a(2 To n) As Integer For i As Integer = 2 To n : a(i) = i : Next Dim As Integer p = 2, q ' mark non-prime numbers by setting the corresponding array element to 0 Do For j As Integer = p * p To n Step p a(j) = 0 Next j ' look fo...
Give a code snippet in #FreeBASIC This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#REXX
REXX
a.1 = 10 a.2 = 22.7 a.7 = -12
Give a code snippet in #REXX Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/Cramer%27s_rule
Cramer's rule
linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1...
#Java
Java
  import java.util.ArrayList; import java.util.Arrays; import java.util.List;   public class CramersRule {   public static void main(String[] args) { Matrix mat = new Matrix(Arrays.asList(2d, -1d, 5d, 1d), Arrays.asList(3d, 2d, 2d, -6d), Arra...
Give a code snippet in #Java linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_...
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)
#Racket
Racket
  #lang racket ;; Assuming a device to provide random bits: (call-with-input-file* "/dev/random" (λ(i) (integer-bytes->integer (read-bytes 4 i) #f)))  
Give a code snippet in #Racket 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/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
originalMatrix = {{1, 1, 1, 1}, {2, 4, 8, 16}, {3, 9, 27, 81}, {4, 16, 64, 256}, {5, 25, 125, 625}} transposedMatrix = Transpose[originalMatrix]
Give a code snippet in #Mathematica.2FWolfram_Language Transpose an arbitrarily sized rectangular Matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Python
Python
next = str(int('123') + 1)
Give a code snippet in #Python Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT file="rosetta.txt" ERROR/STOP OPEN (file,READ,-std-) modified=MODIFIED (file) PRINT "file ",file," last modified: ",modified  
Give a code snippet in #TUSCRIPT Task Get and set the modification time of a file.
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#AutoHotkey
AutoHotkey
  #NoEnv ; Do not try to use environment variables SetBatchLines, -1 ; Execute as quickly as you can   StartCount := A_TickCount Narc := Narc(25) Elapsed := A_TickCount - StartCount   MsgBox, Finished in %Elapsed%ms`n%Narc% return   Narc(m) { Found := 0, Lower := 0 Progress, B2 Loop { Max := 10 ** Digits:=A_Index...
Give a code snippet in #AutoHotkey A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaysty...
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
#Toka
Toka
[ ." First\n" ] is first [ invoke ] is second ` first second
Give a code snippet in #Toka Task Pass a function     as an argument     to another function. Related task   First-class functions
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...
#Kotlin
Kotlin
// version 1.1.2   import java.net.URLDecoder   fun main(args: Array<String>) { val encoded = arrayOf("http%3A%2F%2Ffoo%20bar%2F", "google.com/search?q=%60Abdu%27l-Bah%C3%A1") for (e in encoded) println(URLDecoder.decode(e, "UTF-8")) }
Give a code snippet in #Kotlin 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#TI-83_BASIC
TI-83 BASIC
19→M 1→N For(E,2,M) If E=2 Then:0→S Else:4→S End (N+1)*2-1→N For(I,1,E-2) Reminder(S*S-2,N)→S End If S=0 Then:Disp E End End
Give a code snippet in #TI-83_BASIC Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#Ceylon
Ceylon
import ceylon.random { DefaultRandom }   class Rational(shared Integer numerator, shared Integer denominator = 1) satisfies Numeric<Rational> {   assert (denominator != 0);   Integer gcd(Integer a, Integer b) => if (b == 0) then a else gcd(b, a % b);   shared Rational inverted => Rational(denominator, numerator);  ...
Give a code snippet in #Ceylon The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four d...
christopher/rosetta-code
http://rosettacode.org/wiki/Latin_Squares_in_reduced_form
Latin Squares in reduced form
A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin S...
#Kotlin
Kotlin
typealias Matrix = MutableList<MutableList<Int>>   fun dList(n: Int, sp: Int): Matrix { val start = sp - 1 // use 0 basing   val a = generateSequence(0) { it + 1 }.take(n).toMutableList() a[start] = a[0].also { a[0] = a[start] } a.subList(1, a.size).sort()   val first = a[1] // recursive closure...
Give a code snippet in #Kotlin A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element w...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#Erlang
Erlang
  -import(lists). -export([pascal/1]).   pascal(1)-> [[1]]; pascal(N) -> L = pascal(N-1), [H|_] = L, [lists:zipwith(fun(X,Y)->X+Y end,[0]++H,H++[0])|L].  
Give a code snippet in #Erlang Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is eithe...
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...
#Factor
Factor
USING: io sequences splitting ; IN: rosetta-code.reverse-words   "---------- Ice and Fire ------------   fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I   ... elided paragraph last ...   Frost Robert -----------------------"   "\n" split [ " " spli...
Give a code snippet in #Factor 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 spa...
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...
#Picat
Picat
go => S = "Big fjords vex quick waltz nymph!", println(S), println(rot13(S)), println(rot13(rot13(S))), nl.   % Rot 13 using a map rot13(S) = S2 => lower(Lower), upper(Upper), M = create_map(Lower, Upper),  % If a char is not in a..zA..z then show it as it is. S2 := [M.get(C,C) : C in S].   create_ma...
Give a code snippet in #Picat 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/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.
#Oz
Oz
declare fun {Maximum X|Xr} %% pattern-match on argument to make sure the list is not empty {FoldL Xr Value.max X} %% fold the binary function Value.max over the list end in {Show {Maximum [1 2 3 4 3]}}
Give a code snippet in #Oz 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/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#jq
jq
range(1;101) | if . % 15 == 0 then "FizzBuzz" elif . % 5 == 0 then "Buzz" elif . % 3 == 0 then "Fizz" else . end
Give a code snippet in #jq Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Elementary_cellular_automaton/Random_Number_Generator
Elementary cellular automaton/Random Number Generator
Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed positi...
#11l
11l
V n = 64   F pow2(x) R UInt64(1) << x   F evolve(UInt64 =state; rule) L 10 V b = UInt64(0) L(q) (7 .. 0).step(-1) V st = state b [|]= (st [&] 1) << q state = 0 L(i) 0 .< :n V t = ((st >> (i - 1)) [|] (st << (:n + 1 - i))) [&] 7 I (rule [&] po...
Give a code snippet in #11l Rule 30 is considered to be chaotic enough to generate good pseudo-random numbers. As a matter of fact, rule 30 is used by the Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting succ...
christopher/rosetta-code
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#VBScript
VBScript
  str = "IT WAS THE BEST OF TIMES, IT WAS THE WORST OF TIMES."   Wscript.Echo str Wscript.Echo Rotate(str,5) Wscript.Echo Rotate(Rotate(str,5),-5)   'Rotate (Caesar encrypt/decrypt) test <numpos> positions. ' numpos < 0 - rotate left ' numpos > 0 - rotate right 'Left rotation is converted to equivalent right ...
Give a code snippet in #VBScript Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z...
christopher/rosetta-code
http://rosettacode.org/wiki/Fairshare_between_two_and_more
Fairshare between two and more
The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour t...
#Perl
Perl
use strict; use warnings; use Math::AnyNum qw(sum polymod);   sub fairshare { my($b, $n) = @_; sprintf '%3d'x$n, map { sum ( polymod($_, $b, $b )) % $b } 0 .. $n-1; }   for (<2 3 5 11>) { printf "%3s:%s\n", $_, fairshare($_, 25); }
Give a code snippet in #Perl The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs f...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The ...
#ALGOL_68
ALGOL 68
INT base=10; MODE FIXED = LONG REAL; # numbers in the format 9,999.999 #   #IF build abstract syntax tree and then EVAL tree # MODE AST = UNION(NODE, FIXED); MODE NUM = REF AST; MODE NODE = STRUCT(NUM a, PROC (FIXED,FIXED)FIXED op, NUM b);   OP EVAL = (NUM ast)FIXED:( CASE ast IN (FIXED num): num, (NODE fork)...
Give a code snippet in #ALGOL_68 Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a...
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...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols nobinary   parse arg fileNames   rdr = BufferedReader   do if fileNames.length > 0 then do loop n_ = 1 for fileNames.words fileName = fileNames.word(n_) rdr = BufferedReader(FileReader(File(fileName))) encipher(rdr) ...
Give a code snippet in #NetRexx 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-...
christopher/rosetta-code
http://rosettacode.org/wiki/Death_Star
Death Star
Task Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction. (This will basically produce a shape like a "death star".) Related tasks draw a sphere draw a cuboid draw a rotating cube write language name in 3D ASCII
#Haskell
Haskell
import Data.List (genericLength)   shades = ".:!*oe%#&@" n = genericLength shades dot a b = sum $ zipWith (*) a b normalize x = (/ sqrt (x `dot` x)) <$> x   deathStar r k amb = unlines $ [ [ if x*x + y*y <= r*r then let vec = normalize $ normal x y b = (light `dot` vec) ** k + amb ...
Give a code snippet in #Haskell Task Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction. (This will basically produce a shape like a "death star".) Related tasks draw a sphere draw a cuboid draw a rotating cube write language ...
christopher/rosetta-code
http://rosettacode.org/wiki/Base64_decode_data
Base64 decode data
See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously...
#Ruby
Ruby
require 'base64'   raku_example =' VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY2 9tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g= ' puts Base64.decode64 raku_example
Give a code snippet in #Ruby See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output wit...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#Common_Lisp
Common Lisp
>(= 727 #b1011010111) T >(= 727 #o1327) T >(= 727 #x2d7) T >(= 727 #20r1g7) T
Give a code snippet in #Common_Lisp Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but sho...
christopher/rosetta-code
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#Action.21
Action!
PROC ShowMode(BYTE m,split,gr CARD w, BYTE h, CARD size, CHAR ARRAY descr) BYTE CH=$02FC CARD i BYTE POINTER ptr   Graphics(0) PrintF("Next video mode: %B%E",m) IF split THEN PrintF("Split video mode%E%EUpper part:%E") FI   IF gr THEN Print("Graphics") ...
Give a code snippet in #Action.21 The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
christopher/rosetta-code
http://rosettacode.org/wiki/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#COBOL
COBOL
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. towers-of-hanoi.   PROCEDURE DIVISION. CALL "move-disk" USING 4, 1, 2, 3 . END PROGRAM towers-of-hanoi.   IDENTIFICATION DIVISION. PROGRAM-ID. move-disk RECURSIVE.   DATA DIVISION. LINKAGE SECTION. 01 n PIC 9 USAGE COMP. 01 from...
Give a code snippet in #COBOL Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Find_Chess960_starting_position_identifier
Find Chess960 starting position identifier
As described on the Chess960 page, Chess960 (a.k.a Fischer Random Chess, Chess9LX) is a variant of chess where the array of pieces behind the pawns is randomized at the start of the game to minimize the value of opening theory "book knowledge". That task is to generate legal starting positions, and some of the solution...
#Python
Python
  # optional, but task function depends on it as written def validate_position(candidate: str): assert ( len(candidate) == 8 ), f"candidate position has invalide len = {len(candidate)}"   valid_pieces = {"R": 2, "N": 2, "B": 2, "Q": 1, "K": 1} assert { piece for piece in candidate } ...
Give a code snippet in #Python As described on the Chess960 page, Chess960 (a.k.a Fischer Random Chess, Chess9LX) is a variant of chess where the array of pieces behind the pawns is randomized at the start of the game to minimize the value of opening theory "book knowledge". That task is to generate legal starting pos...
christopher/rosetta-code
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#J
J
positive =: >&0 unique =: -.@:e. condition =: (positive@:] *. unique~) ({: - #) NB. with the agenda set by the condition, add or subtract tail with tally recaman_term =: ({: + #)`({: - #)@.condition NB. generate four hundred thousand terms and display the first 15 15 {. R=:(, recaman_term)^:4000...
Give a code snippet in #J The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task ...
christopher/rosetta-code
http://rosettacode.org/wiki/Shoelace_formula_for_polygonal_area
Shoelace formula for polygonal area
Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs returns the absolute value) Task Write ...
#360_Assembly
360 Assembly
* SHOELACE 25/02/2019 SHOELACE CSECT USING SHOELACE,R15 base register MVC SUPS(8),POINTS x(nt+1)=x(1); y(nt+1)=y(1) LA R9,0 area=0 LA R7,POINTS @x(1) LA R6,NT do i=1 to nt LOOP L R...
Give a code snippet in #360_Assembly Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by: abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) - (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N]) ) / 2 (Where abs ret...
christopher/rosetta-code
http://rosettacode.org/wiki/Atomic_updates
Atomic updates
Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the t...
#Haskell
Haskell
module AtomicUpdates (main) where   import Control.Concurrent (forkIO, threadDelay) import Control.Concurrent.MVar (MVar, newMVar, readMVar, modifyMVar_) import Control.Monad (forever, forM_) import Data.IntMap (IntMap, (!), toAscList, fromList, adjust) import System.Random (randomRIO) import Text.Printf (printf)   ---...
Give a code snippet in #Haskell Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of all ...
christopher/rosetta-code
http://rosettacode.org/wiki/Polymorphic_copy
Polymorphic copy
An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were unknown, then y could not be d...
#Raku
Raku
my Cool $x = 22/7 but role Fink { method brag { say "I'm a cool {self.WHAT.raku}!" }} my Cool $y = $x.clone; $y.brag;
Give a code snippet in #Raku An object is polymorphic when its specific type may vary. The types a specific value may take, is called class. It is trivial to copy an object if its type is known: int x; int y = x; Here x is not polymorphic, so y is declared of same type (int) as x. But if the specific type of x were ...
christopher/rosetta-code
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square r...
#Idris
Idris
module Main   import Data.Vect   Matrix : Nat -> Nat -> Type -> Type Matrix m n t = Vect m (Vect n t)     zeros : (m : Nat) -> (n : Nat) -> Matrix m n Double zeros m n = replicate m (replicate n 0.0)     indexM : (Fin m, Fin n) -> Matrix m n t -> t indexM (i, j) a = index j (index i a)     replaceAtM : (Fin m, Fin n) -...
Give a code snippet in #Idris Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interp...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Nim
Nim
var # fixed size arrays x = [1,2,3,4,5,6,7,8,9,10] # type and size automatically inferred y: array[1..5, int] = [1,2,3,4,5] # starts at 1 instead of 0 z: array['a'..'z', int] # indexed using characters   x[0] = x[1] + 1 echo x[0] echo z['d']   x[7..9] = y[3..5] # copy part of array   var # variable size sequences...
Give a code snippet in #Nim This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retriev...
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...
#Coq
Coq
Require Import List.   Fixpoint rep {A} (a : A) n := match n with | O => nil | S n' => a::(rep a n') end.   Fixpoint flip (l : list bool) (n k : nat) : list bool := match l with | nil => nil | cons h t => match k with | O => (negb h) :: (flip t n n) | S k' => h :: (...
Give a code snippet in #Coq 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/Undefined_values
Undefined values
#Smalltalk
Smalltalk
Smalltalk includesKey: #FooBar myNamespace includesKey: #Baz
Give a code snippet in #Smalltalk
christopher/rosetta-code
http://rosettacode.org/wiki/Get_system_command_output
Get system command output
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
#Raku
Raku
say run($command, $arg1, $arg2, :out).out.slurp;
Give a code snippet in #Raku Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). Related task Execute a system command
christopher/rosetta-code
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Action.21
Action!
proc MAIN() char array STRING open (1,"D:FILE.TXT",4,0) inputsd(1,STRING) close(1) return    
Give a code snippet in #Action.21 Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished i...
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_partitions
Ordered partitions
In this task we want to find the ordered partitions into fixed-size blocks. This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task. p a r t i t i o n s ( a r g 1 , a r g 2 , ...
#Perl
Perl
use Thread 'async'; use Thread::Queue;   sub make_slices { my ($n, @avail) = (shift, @{ +shift });   my ($q, @part, $gen); $gen = sub { my $pos = shift; # where to start in the list if (@part == $n) { # we accumulated enough for a pa...
Give a code snippet in #Perl In this task we want to find the ordered partitions into fixed-size blocks. This task is related to Combinations in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task. p a r t i t i o n s ( a r...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Rust
Rust
fn main(){}
Give a code snippet in #Rust Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Window_management
Window management
Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of interest may or may not have b...
#Raku
Raku
use X11::libxdo;   my $xdo = Xdo.new;   say 'Visible windows:'; printf "Class: %-21s ID#: %10d pid: %5d Name: %s\n", $_<class ID pid name> for $xdo.get-windows.sort(+*.key)».value; sleep 2;   my $id = $xdo.get-active-window;   my ($w, $h ) = $xdo.get-window-size( $id ); my ($wx, $wy) = $xdo.get-window-location( ...
Give a code snippet in #Raku Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort
Sorting algorithms/Patience 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 ...
#PHP
PHP
<?php class PilesHeap extends SplMinHeap { public function compare($pile1, $pile2) { return parent::compare($pile1->top(), $pile2->top()); } }   function patience_sort(&$n) { $piles = array(); // sort into piles foreach ($n as $x) { // binary search $low = 0; $high = count($p...
Give a code snippet in #PHP 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/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...
#Java
Java
  import java.util.ArrayList; import java.util.List;   public class EgyptianDivision {   /** * Runs the method and divides 580 by 34 * * @param args not used */ public static void main(String[] args) {   divide(580, 34);   }   /** * Divides <code>dividend</code> by <code...
Give a code snippet in #Java 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/Singly-linked_list/Element_insertion
Singly-linked list/Element insertion
Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Trav...
#FreeBASIC
FreeBASIC
sub insert_ll_int( anchor as ll_int ptr, ins as ll_int ptr) ins->nxt = anchor->nxt anchor->nxt = ins end sub
Give a code snippet in #FreeBASIC Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element defin...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#PARI.2FGP
PARI/GP
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
Give a code snippet in #PARI.2FGP The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algo...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#JavaScript
JavaScript
<html><head><title>Permutations</title></head> <body><pre id="result"></pre> <script type="text/javascript"> var d = document.getElementById('result');   function perm(list, ret) { if (list.length == 0) { var row = document.createTextNode(ret.join(' ') + '\n'); d.appendChild(row); return; ...
Give a code snippet in #JavaScript Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations  ...
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...
#Ring
Ring
  # Project: Rosetta Code/Find unimplemented tasks   load "stdlib.ring" ros= download("http://rosettacode.org/wiki/Category:Programming_Tasks") lang = "Ring" pos = 1 num = 0 totalros = 0 rosname = "" rostitle = "" see "Tasks not implemented in " + lang + " language:" + nl for n = 1 to len(ros) nr = searchstrin...
Give a code snippet in #Ring 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/Terminal_control/Unicode_output
Terminal control/Unicode output
The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised. Note that it is permissible to use sys...
#BaCon
BaCon
' Determine if the terminal supports Unicode ' if so display delta, if not display error message LET lc$ = GETENVIRON$("LANG") IF INSTR(LCASE$(lc$), "utf8") != 0 THEN PRINT UTF8$(0x25B3) ELSE EPRINT "Sorry, terminal is not testing as unicode ready" END IF
Give a code snippet in #BaCon The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised. Note th...
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...
#REXX
REXX
/* REXX *************************************************************** * 11.05.2013 Walter Pachl * 14.05.2013 Walter Pachl extend to show additional rep-strings **********************************************************************/ Call repstring '1001110011' Call repstring '1110111011' Call repstring '0010010010' Ca...
Give a code snippet in #REXX 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_string_challenge
Longest string challenge
Background This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through th...
#Java
Java
import java.io.File; import java.util.Scanner;   public class LongestStringChallenge {   public static void main(String[] args) throws Exception { String lines = "", longest = ""; try (Scanner sc = new Scanner(new File("lines.txt"))) { while(sc.hasNext()) { String line = ...
Give a code snippet in #Java Background This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challeng...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#MAD
MAD
VECTOR VALUES HELLO = $11HHELLO WORLD*$ PRINT FORMAT HELLO END OF PROGRAM
Give a code snippet in #MAD Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   ...
christopher/rosetta-code
http://rosettacode.org/wiki/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
#Latitude
Latitude
  > 'true true > 'false false > (or 'false 'false) false > (or 'false 'true) true  
Give a code snippet in #Latitude 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/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" o...
#Common_Lisp
Common Lisp
#1=(PRINT (EQUAL (WRITE-TO-STRING '#1# :CIRCLE 1) (READ-LINE *STANDARD-INPUT*)))
Give a code snippet in #Common_Lisp Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth ...
#Kotlin
Kotlin
// Version 1.3.21   const val MAX = 15   fun countDivisors(n: Int): Int { var count = 0 var i = 1 while (i * i <= n) { if (n % i == 0) { count += if (i == n / i) 1 else 2 } i++ } return count }   fun main() { println("The first $MAX terms of the sequence are:"...
Give a code snippet in #Kotlin Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with ex...
christopher/rosetta-code
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#Go
Go
package main   import "fmt"   func main() { fs := make([]func() int, 10) for i := range fs { i := i fs[i] = func() int { return i * i } } fmt.Println("func #0:", fs[0]()) fmt.Println("func #3:", fs[3]()) }
Give a code snippet in #Go Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you ...
#XPL0
XPL0
int Deck(10000), Deck0(10000); int Cases, Count, Test, Size, I;   proc Shuffle; \Do perfect shuffle of Deck0 into Deck int DeckLeft, DeckRight; int I; [DeckLeft:= Deck0; DeckRight:= Deck0 + Size*4/2; \4 bytes per integer for I:= 0 to Size-1 do Deck(I):= if I&1 then DeckRight(...
Give a code snippet in #XPL0 A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠...
christopher/rosetta-code
http://rosettacode.org/wiki/Base64_decode_data
Base64 decode data
See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously...
#Common_Lisp
Common Lisp
(eval-when (:load-toplevel :compile-toplevel :execute) (ql:quickload "cl-base64"))   ;; * The package definition (defpackage :base64-decode (:use :common-lisp :cl-base64)) (in-package :base64-decode)   ;; * The encoded data (defvar *base64-data* "AAABAAIAEBAAAAAAAABoBQAAJgAAACAgAAAAAAAAqAgAAI4FAAAoAAAAEAAAACAAAAA...
Give a code snippet in #Common_Lisp See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed out...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#Ursa
Ursa
while true out "SPAM" endl console end while
Give a code snippet in #Ursa Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_factors
Count in factors
Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would be shown as   2 × 3 {\di...
#R
R
  #initially I created a function which returns prime factors then I have created another function counts in the factors and #prints the values.   findfactors <- function(num) { x <- c() p1<- 2 p2 <- 3 everyprime <- num while( everyprime != 1 ) { while( everyprime%%p1 == 0 ) { x <- c(x, p1) e...
Give a code snippet in #R Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would be ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body...
#6502_Assembly
6502 Assembly
;An OS/hardware specific routine that is setup to display the Ascii character ;value contained in the Accumulator Send = $9000 ;routine not implemented here PrintNewLine = $9050 ;routine not implemented here   *= $8000 ;set base address Start PHA ;push Accumulator and Y register onto stack TYA PHA ...
Give a code snippet in #6502_Assembly Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loop...
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#Go
Go
package main   import ( "bufio" "fmt" "os" "strconv" "strings" )   func main() { fmt.Println(`Cows and bulls/player You think of four digit number of unique digits in the range 1 to 9. I guess. You score my guess: A correct digit but not in the correct place is a cow. A correct digit in...
Give a code snippet in #Go Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#blz
blz
print("Hello world!")
Give a code snippet in #blz Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#Turbo_Pascal
Turbo Pascal
program quine;   const apos: Char = Chr(39); comma: Char = Chr(44); lines: Array[1..17] of String[80] = ( 'program quine;', '', 'const', ' apos: Char = Chr(39);', ' comma: Char = Chr(44);', ' lines: Array[1..17] of String[80] = (', ' );', '', 'var', ' num: Integer;', '', 'begin', ' ...
Give a code snippet in #Turbo_Pascal A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer pro...
christopher/rosetta-code
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#Python
Python
print("""\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """)
Give a code snippet in #Python A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) follow...
christopher/rosetta-code
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#BQN
BQN
Dgts ← •Fmt-'0'˙ IsMnch ← ⊢=+´∘(⋆˜ Dgts) IsMnch¨⊸/ 1+↕5000
Give a code snippet in #BQN A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see T...
christopher/rosetta-code
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a...
#Java
Java
import java.util.ArrayList; import java.util.List;   public class Bell { private static class BellTriangle { private List<Integer> arr;   BellTriangle(int n) { int length = n * (n + 1) / 2; arr = new ArrayList<>(length); for (int i = 0; i < length; ++i) { ...
Give a code snippet in #Java Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Tonelli-Shanks_algorithm
Tonelli-Shanks algorithm
This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computational number theory, the Tonelli–Shanks algor...
#FreeBASIC
FreeBASIC
' version 11-04-2017 ' compile with: fbc -s console ' maximum for p is 17 digits to be on the save side   ' TRUE/FALSE are built-in constants since FreeBASIC 1.04 ' But we have to define them for older versions. #Ifndef TRUE #Define FALSE 0 #Define TRUE Not FALSE #EndIf   Function mul_mod(a As ULongInt, b As UL...
Give a code snippet in #FreeBASIC This page uses content from Wikipedia. The original article was at Tonelli-Shanks algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In computational numb...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the vall...
#Liberty_BASIC
Liberty BASIC
'This example requires the Windows API NoMainWin WindowWidth = 267.5 WindowHeight = 292.5 UpperLeftX=int((DisplayWidth-WindowWidth)/2) UpperLeftY=int((DisplayHeight-WindowHeight)/2)   Global hDC : hDC = GetDC(0) Struct point, x As long, y As long Struct RGB, Red As long, Green As long, Blue As long Struct rect, left As...
Give a code snippet in #Liberty_BASIC Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_ladder
Word ladder
Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the following: A boy can be made into ...
#Perl
Perl
use strict; use warnings;   my %dict;   open my $handle, '<', 'unixdict.txt'; while (my $word = <$handle>) { chomp($word); my $len = length $word; if (exists $dict{$len}) { push @{ $dict{ $len } }, $word; } else { my @words = ( $word ); $dict{$len} = \@words; } } close $handl...
Give a code snippet in #Perl Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the follo...
christopher/rosetta-code
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt...
#Ring
Ring
  # Project : Substitution Cipher   plaintext = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ciphertext = "ZEBRASCDFGHIJKLMNOPQTUVWXY" test = "flee at once. we are discovered!" encrypt = "SIAA ZQ LKBA. VA ZOA RFPBLUAOAR!"   see "Plaintext : " + plaintext + nl see "Ciphertext : " + ciphertext + nl see "Test : " + test + nl see "Encoded...
Give a code snippet in #Ring Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then aga...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#Oforth
Oforth
: factors(n) // ( aInteger -- aList ) | k p | ListBuffer new 2 ->k n nsqrt ->p while( k p <= ) [ n k /mod swap ifZero: [ dup ->n nsqrt ->p k over add continue ] drop k 1+ ->k ] n 1 > ifTrue: [ n over add ] dup freeze ;
Give a code snippet in #Oforth The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the...
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#AWK
AWK
function ord(c) { return chmap[c] } BEGIN { for(i=0; i < 256; i++) { chmap[sprintf("%c", i)] = i } print ord("a"), ord("b") printf "%c %c\n", 97, 98 s = sprintf("%c%c", 97, 98) print s }
Give a code snippet in #AWK Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conver...
christopher/rosetta-code
http://rosettacode.org/wiki/First_power_of_2_that_has_leading_decimal_digits_of_12
First power of 2 that has leading decimal digits of 12
(This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   1208925819614629174706176. Define ...
#Kotlin
Kotlin
import kotlin.math.ln import kotlin.math.pow   fun main() { runTest(12, 1) runTest(12, 2) runTest(123, 45) runTest(123, 12345) runTest(123, 678910) }   private fun runTest(l: Int, n: Int) { // System.out.printf("p(%d, %d) = %,d%n", l, n, p(l, n)) println("p($l, $n) = %,d".format(p(l, n))) }  ...
Give a code snippet in #Kotlin (This task is taken from a   Project Euler   problem.) (All numbers herein are expressed in base ten.) 27   =   128   and   7   is the first power of   2   whose leading decimal digits are   12. The next power of   2   whose leading decimal digits are   12   is   80, 280   =   12089...
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...
#BASIC
BASIC
SUB truncateFile (file AS STRING, length AS LONG) IF LEN(DIR$(file)) THEN DIM f AS LONG, c AS STRING f = FREEFILE OPEN file FOR BINARY AS f IF length > LOF(f) THEN CLOSE f ERROR 62 'Input past end of file ELSE c = SPACE$(length) ...
Give a code snippet in #BASIC 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 creatin...
christopher/rosetta-code
http://rosettacode.org/wiki/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ......
#Icon_and_Unicon
Icon and Unicon
procedure pi (q, r, t, k, n, l) first := "yes" repeat { # infinite loop if (4*q+r-t < n*t) then { suspend n if (\first) := &null then suspend "." # compute and update variables for next cycle nr := 10*(r-n*t) n := ((10*(3*q+r)) / t) - 10*n q *:= 10 r := nr } else { ...
Give a code snippet in #Icon_and_Unicon Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a de...
christopher/rosetta-code
http://rosettacode.org/wiki/Percolation/Bond_percolation
Percolation/Bond percolation
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Given an M × N...
#zkl
zkl
// cell states const FILLED=1; // and odd const RWALL =2; // right wall const BWALL =4; // bottom wall fcn P(p,wall){ (0.0).random(1)<p and wall or 0 }   fcn makeGrid(m,n,p){ // Allocate two addition rows to avoid checking bounds. // Bottom row is also required by drippage grid:=Data(m*(n+2)); do(m){ grid...
Give a code snippet in #zkl Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluste...
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 ...
#Scala
Scala
"asdf".reverse
Give a code snippet in #Scala Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of thi...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Const whitespace = !" \t\n\v\f\r"   Dim s As String = !" \tRosetta Code \v\f\r\n" Dim s1 As String = LTrim (s, Any whitespace) Dim s2 As String = RTrim (s, Any whitespace) Dim s3 As String = Trim (s, Any whitespace)   ' Under Windows console : ' "vertical tab" displays as ♂ ' "form feed" display...
Give a code snippet in #FreeBASIC Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespac...
christopher/rosetta-code
http://rosettacode.org/wiki/ASCII_art_diagram_converter
ASCII art diagram converter
Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string: http://www.ietf.org/rfc/rfc1035.txt +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RC...
#Tcl
Tcl
* using dictionaries, taking advantage of their ordering properties * the binary command * using (semi-)structured text as part of your source code
Give a code snippet in #Tcl Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string: http://www.ietf.org/rfc/rfc1035.txt +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#Smalltalk
Smalltalk
| d | d := Date today. d printFormat: #(3 2 1 $- 1 1 2). (d weekday asString), ', ', (d monthName), ' ', (d dayOfMonth asString), ', ', (d year asString)
Give a code snippet in #Smalltalk This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task...
#Kotlin
Kotlin
typealias matrix = MutableList<MutableList<Int>>   fun printSquare(latin: matrix) { for (row in latin) { println(row) } println() }   fun latinSquare(n: Int) { if (n <= 0) { println("[]") return }   val latin = MutableList(n) { MutableList(n) { it } } // first row ...
Give a code snippet in #Kotlin A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#360_Assembly
360 Assembly
* Bead Sort 11/05/2016 BEADSORT CSECT USING BEADSORT,R13 base register SAVEAR B STM-SAVEAR(R15) skip savearea DC 17F'0' savearea STM STM R14,R12,12(R13) prolog ST R13,4(R15) " ST R15,8(R13) "...
Give a code snippet in #360_Assembly 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 | Q...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_prototype
Function prototype
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions for prototype declarations A p...
#JavaScript
JavaScript
  // A prototype declaration for a function that does not require arguments function List() {}   List.prototype.push = function() { return [].push.apply(this, arguments); };   List.prototype.pop = function() { return [].pop.call(this); };   var l = new List(); l.push(5); l.length; // 1 l[0]; 5 l.pop(); // 5 l.lengt...
Give a code snippet in #JavaScript Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrict...
christopher/rosetta-code
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the objec...
#Go
Go
package main   import ( "fmt" "math" )   // note: exponent not limited to ints func newPowGen(e float64) func() float64 { var i float64 return func() (r float64) { r = math.Pow(i, e) i++ return } }   // given two functions af, bf, both monotonically increasing, return a // ne...
Give a code snippet in #Go A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_to_Windows_event_log
Write to Windows event log
Task Write script status to the Windows Event Log
#Scala
Scala
object RegisterWinLogEvent extends App {   import sys.process._   def eventCreate= Seq("EVENTCREATE", "/T", "SUCCESS", "/id", "123", "/l", "APPLICATION", "/so", "Scala RegisterWinLogEvent", "/d", "Rosetta Code Example" ).!!   println(eventCreate)   println(s"\nSuccessfully completed without errors. [total ${sc...
Give a code snippet in #Scala Task Write script status to the Windows Event Log
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...
#Maxima
Maxima
collatz(n) := block([L], L: [n], while n > 1 do (n: if evenp(n) then n/2 else 3*n + 1, L: endcons(n, L)), L)$   collatz_length(n) := block([m], m: 1, while n > 1 do (n: if evenp(n) then n/2 else 3*n + 1, m: m + 1), m)$   collatz_max(n) := block([j, m, p], m: 0, for i from 1 thru n do (p: collatz_length(i), if p > m ...
Give a code snippet in #Maxima 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Munchausen_numbers
Munchausen numbers
A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see The OEIS entry: A046253 The ...
#Swift
Swift
import Foundation   func isMünchhausen(_ n: Int) -> Bool { let nums = String(n).map(String.init).compactMap(Int.init)   return Int(nums.map({ pow(Double($0), Double($0)) }).reduce(0, +)) == n }   for i in 1...5000 where isMünchhausen(i) { print(i) }
Give a code snippet in #Swift A Munchausen number is a natural number n the sum of whose digits (in base 10), each raised to the power of itself, equals n. (Munchausen is also spelled: Münchhausen.) For instance:   3435 = 33 + 44 + 33 + 55 Task Find all Munchausen numbers between   1   and   5000. Also see ...
christopher/rosetta-code