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
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#Nim
Nim
import random import imageman   const Size = 400 # Area size. MaxXY = Size - 1 # Maximum possible value for x and y. NPart = 25_000 # Number of particles. Background = ColorRGBU [byte 0, 0, 0] # Background color. Fo...
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Factor
Factor
USING: accessors assocs combinators fry grouping hashtables kernel locals math math.parser math.ranges random sequences strings io ascii ;   IN: bullsncows   TUPLE: score bulls cows ; : <score> ( -- score ) 0 0 score boa ;   TUPLE: cow ; : <cow> ( -- cow ) cow new ;   TUPLE: bull ; : <bull> ( -- bull ) bu...
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...
#Dart
Dart
class Caesar { int _key;   Caesar(this._key);   int _toCharCode(String s) { return s.charCodeAt(0); }   String _fromCharCode(int ch) { return new String.fromCharCodes([ch]); }   String _process(String msg, int offset) { StringBuffer sb=new StringBuffer(); for(int i=0;i<msg.length;i++) { ...
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#R
R
  options(digits=22) cat("e =",sum(rep(1,20)/factorial(0:19)))  
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Quackery
Quackery
$ "bigrat.qky" loadfile   [ swap number$ tuck size - times sp echo$ ] is echo-rj ( n n --> )   [ 2dup swap say " First " echo say " approximations of e by sum of 1/n! displayed to " echo say " decimal places." cr cr temp put 1 n->v rot 1 swap times [ i^ 1+ * ...
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...
#Shale
Shale
#!/usr/local/bin/shale   maths library file library string library   lista var listb var firstTimeThrough var guess var guess0 var guess1 var guess2 var guess3 var bulls var cows var   init dup var { count a:: var count b:: var } =   randomDigit dup var { random maths::() 18 >> 9 % 1 + } =   makeGuess dup var { ...
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to al...
#XLISP
XLISP
(SETQ YR 1969) (SETQ M #("JANUARY" "FEBRUARY" "MARCH" "APRIL" "MAY" "JUNE" "JULY" "AUGUST" "SEPTEMBER" "OCTOBER" "NOVEMBER" "DECEMBER")) (SETQ ML #(31 28 31 30 31 30 31 31 30 31 30 31)) (SETQ WD #("SU" "MO" "TU" "WE" "TH" "FR" "SA")) (IF (AND (= (REM YR 4) 0) (OR (/= (REM YR 100) 0) (= (REM YR 400) 0))) (VECTOR-SET! ML...
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#i
i
//The type of the function argument determines whether or not the value is passed by reference or not. //Eg. numbers are passed by value and lists/arrays are passed by reference.   software { print() //Calling a function with no arguments. print("Input a number!") //Calling a function with fixed arguments. prin...
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#Maxima
Maxima
/* The following is an array function, hence the square brackets. It uses memoization automatically */ cata[n] := sum(cata[i]*cata[n - 1 - i], i, 0, n - 1)$ cata[0]: 1$   cata2(n) := binomial(2*n, n)/(n + 1)$   makelist(cata[n], n, 0, 14);   makelist(cata2(n), n, 0, 14);   /* both return [1, 1, 2, 5, 14, 42, 132, 429, ...
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#Rust
Rust
const OPEN_CHAR: char = '{'; const CLOSE_CHAR: char = '}'; const SEPARATOR: char = ','; const ESCAPE: char = '\\';   #[derive(Debug, PartialEq, Clone)] enum Token { Open, Close, Separator, Payload(String), Branches(Branches), }   impl From<char> for Token { fn from(ch: char) -> Token { m...
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#Scala
Scala
  import collection.mutable.ListBuffer case class State(isChild: Boolean, alts: ListBuffer[String], rem: List[Char]) def expand(s: String): Seq[String] = { def parseGroup(s: State): State = s.rem match { case Nil => s.copy(alts = ListBuffer("{" + s.alts.mkString(","))) case ('{' | ',')::sp => val newS ...
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
brazilianQ[n_Integer /; n>6 ] := AnyTrue[ Range[2, n-2], MatchQ[IntegerDigits[n, #], {x_ ...}] & ] Select[Range[100], brazilianQ, 20] Select[Range[100], brazilianQ@# && OddQ@# &, 20] Select[Range[10000], brazilianQ@# && PrimeQ@# &, 20]  
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#JavaScript
JavaScript
/** * Given a width, return a function that takes a string, and * pads it at both ends to the given width * @param {number} width * @returns {function(string): string} */ const printCenter = width => s => s.padStart(width / 2 + s.length / 2, ' ').padEnd(width);   /** * Given an locale string and options, retu...
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#OCaml
OCaml
let world_width = 400 let world_height = 400 let num_particles = 20_000   let () = assert(num_particles > 0); assert(world_width * world_height > num_particles); ;;   let dla ~world = (* put the tree seed *) world.(world_height / 2).(world_width / 2) <- 1;   for i = 1 to num_particles do (* looping helpe...
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Fan
Fan
** ** Bulls and cows. A game pre-dating, and similar to, Mastermind. ** class BullsAndCows {   Void main() { digits := [1,2,3,4,5,6,7,8,9] size := 4 chosen := [,] size.times { chosen.add(digits.removeAt(Int.random(0..<digits.size))) }   echo("I've chosen $size unique digits from 1 to 9 at random...
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...
#Delphi
Delphi
func Char.Encrypt(code) { if !this.IsLetter() { return this } var offset = (this.IsUpper() ? 'A' : 'a').Order() return Char((this.Order() + code - offset) % 26 + offset) }   func String.Encrypt(code) { var xs = [] for c in this { xs.Add(c.Encrypt(code)) } return String.Co...
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Racket
Racket
#lang racket (require math/number-theory)   (define (calculate-e (terms 20)) (apply + (map (compose / factorial) (range terms))))   (module+ main (let ((e (calculate-e))) (displayln e) (displayln (real->decimal-string e 20)) (displayln (real->decimal-string (- (exp 1) e) 20))))
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Raku
Raku
# If you need high precision: Sum of a Taylor series method. # Adjust the terms parameter to suit. Theoretically the # terms could be ∞. Practically, calculating an infinite # series takes an awfully long time so limit to 500.   sub postfix:<!> (Int $n) { (constant f = 1, |[\*] 1..*)[$n] } sub 𝑒 (Int $terms) { sum map...
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...
#Sidef
Sidef
# Build a list of all possible solutions. The regular expression weeds # out numbers containing zeroes or repeated digits. var candidates = (1234..9876 -> grep {|n| !("#{n}" =~ /0 | (\d) .*? \1 /x) }.map{.digits});   # Repeatedly prompt for input until the user supplies a reasonable score. # The regex validates the us...
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to al...
#zkl
zkl
VAR [CONST] D=TIME.DATE, DAYS="SU MO TU WE TH FR SA";   FCN CENTER(TEXT,M) { STRING(" "*((M-TEXT.LEN())/2),TEXT) }   FCN ONEMONTH(YEAR,MONTH){ DAY1:=D.ZELLER(YEAR,MONTH,1); //1969-1-1 -->3 (WED, ISO 8601) DAYZ:=D.DAYSINMONTH(YEAR,MONTH); //1969-1 -->31 LIST(CENTER(D.MONTHNAMES[MONTH],DAYS.LEN()),DAYS).EXT...
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Icon_and_Unicon
Icon and Unicon
procedure main() # demonstrate and describe function calling syntax and semantics   # normal procedure/function calling   f() # no arguments, also command context f(x) # fixed number of arguments f(x,h,w) # variable number of arguments (varargs) y...
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#Modula-2
Modula-2
MODULE CatalanNumbers; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE binomial(m,n : LONGCARD) : LONGCARD; VAR r,d : LONGCARD; BEGIN r := 1; d := m - n; IF d>n THEN n := d; d := m - n; END; WHILE m>n DO r := r * m; ...
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#Scheme
Scheme
  (define (parse-brackets str) ;; We parse the bracketed strings using an accumulator and a stack ;; ;; lst is the stream of tokens ;; acc is the accumulated list of "bits" in this branch ;; stk is a list of partially completed accumulators ;; (let go ((lst (string->list str)) (acc '()) ...
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Nim
Nim
proc isPrime(n: Positive): bool = ## Check if a number is prime. if n mod 2 == 0: return n == 2 if n mod 3 == 0: return n == 3 var d = 5 while d * d <= n: if n mod d == 0: return false if n mod (d + 2) == 0: return false inc d, 6 result = true   proc sameDigits(n, b: Positive...
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#Julia
Julia
  using Dates   const pagesizes = Dict( "lpr" => [132, 66], "tn3270" => [80, 43])   pagefit(prn) = haskey(pagesizes, prn) ? [div(pagesizes[prn][1], 22), div(pagesizes[prn][2], 12)] : [1, 1] pagecols(prn) = haskey(pagesizes, prn) ? pagesizes[prn][1] : 20   function centerobject(x, cols) content = string(x) r...
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#Octave
Octave
function r = browniantree(xsize, ysize = xsize, numparticle = 1000) r = zeros(xsize, ysize, "uint8"); r(unidrnd(xsize), unidrnd(ysize)) = 1;   for i = 1:numparticle px = unidrnd(xsize-1)+1; py = unidrnd(ysize-1)+1; while(1) dx = unidrnd(2) - 1; dy = unidrnd(2) - 1; if ( (dx+px < 1) |...
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#FOCAL
FOCAL
01.10 T %1,"BULLS AND COWS"!"----- --- ----"!! 01.20 S T=0;D 3 01.30 D 2;D 5;S T=T+1;T "BULLS",B," COWS",C,!! 01.40 I (B-4)1.3 01.50 T "YOU WON! GUESSES",%4,T,!! 01.60 Q   02.10 A "GUESS",A 02.20 F X=0,3;S B=FITR(A/10);S G(3-X)=A-B*10;S A=B 02.30 S A=1 02.40 F X=0,3;S A=A*G(X) 02.50 I (-A)2.6;T "NEED FOUR NONZERO DIGIT...
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...
#Dyalect
Dyalect
func Char.Encrypt(code) { if !this.IsLetter() { return this } var offset = (this.IsUpper() ? 'A' : 'a').Order() return Char((this.Order() + code - offset) % 26 + offset) }   func String.Encrypt(code) { var xs = [] for c in this { xs.Add(c.Encrypt(code)) } return String.Co...
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#REXX
REXX
╔═══════════════════════════════════════════════════════════════════════════════════════╗ ║ ║ ║ 1 1 1 1 1 1 1 ║ ║ e = ─── + ─── + ─── + ─── ...
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Ring
Ring
  # Project : Calculating the value of e   decimals(14)   for n = 1 to 100000 e = pow((1 + 1/n),n) next see "Calculating the value of e with method #1:" + nl see "e = " + e + nl   e = 0 for n = 0 to 12 e = e + (1 / factorial(n)) next see "Calculating the value of e with method #2:" + nl see "e = " + e + nl   ...
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...
#Tcl
Tcl
package require struct::list package require struct::set   proc scorecalc {guess chosen} { set bulls 0 set cows 0 foreach g $guess c $chosen { if {$g eq $c} { incr bulls } elseif {$g in $chosen} { incr cows } } return [list $bulls $cows] }   # Allow override on command line set size [ex...
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#J
J
verb noun noun verb noun
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#Nim
Nim
import math import strformat   proc catalan1(n: int): int = binom(2 * n, n) div (n + 1)   proc catalan2(n: int): int = if n == 0: return 1 for i in 0..<n: result += catalan2(i) * catalan2(n - 1 - i)   proc catalan3(n: int): int = if n > 0: 2 * (2 * n - 1) * catalan3(n - 1) div (1 + n) else: 1   for i ...
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: expandBraces (in string: stri) is func local var boolean: escaped is FALSE; var integer: depth is 0; var array integer: bracePoints is 0 times 0; var array integer: bracesToParse is 0 times 0; var string: prefix is ""; var string: suffix is ""; var s...
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Pascal
Pascal
program brazilianNumbers;   {$IFDEF FPC} {$MODE DELPHI}{$OPTIMIZATION ON,All} {$CODEALIGN proc=32,loop=4} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF} uses SysUtils;   const //Must not be a prime PrimeMarker = 0; SquareMarker = PrimeMarker + 1; //MAX = 110468;// 1E5 brazilian //MAX = 1084566;// 1E6 brazil...
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#Kotlin
Kotlin
import java.io.PrintStream import java.text.DateFormatSymbols import java.text.MessageFormat import java.util.Calendar import java.util.GregorianCalendar import java.util.Locale   internal fun PrintStream.printCalendar(year: Int, nCols: Byte, locale: Locale?) { if (nCols < 1 || nCols > 12) throw IllegalArgu...
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#PARI.2FGP
PARI/GP
  \\ 2 old plotting helper functions 3/2/16 aev \\ insm(): Check if x,y are inside matrix mat (+/- p deep). insm(mat,x,y,p=0)={my(xz=#mat[1,],yz=#mat[,1]); return(x+p>0 && x+p<=xz && y+p>0 && y+p<=yz && x-p>0 && x-p<=xz && y-p>0 && y-p<=yz)} \\ plotmat(): Simple plotting using a square matrix mat (filled with 0/1). p...
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Forth
Forth
include random.fs   create hidden 4 allot   : ok? ( str -- ? ) dup 4 <> if 2drop false exit then 1 9 lshift 1- -rot bounds do i c@ '1 - dup 0 9 within 0= if 2drop false leave then 1 swap lshift over and dup 0= if nip leave then xor loop 0<> ;   : init begin hidden 4 bounds do 9 random ...
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...
#EDSAC_order_code
EDSAC order code
  [Caesar cipher for Rosetta Code. EDSAC program, Initial Orders 2.]   [Table for converting alphabetic position 0..25 to EDSAC code. The EDSAC code is in the high 5 bits.] T 54 K [access table via C parameter] P 56 F T 56 K AFBFCFDFEFFFGFHFIFJFKFLFMFNFOFPFQFRFSFTFU...
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Ruby
Ruby
  fact = 1 e = 2 e0 = 0 n = 2   until (e - e0).abs < Float::EPSILON do e0 = e fact *= n n += 1 e += 1.0 / fact end   puts e  
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...
#VBA
VBA
  Option Explicit   Sub Main_Bulls_And_Cows_Player() Dim collSoluces As New Collection, Elem As Variant, Soluce As String Dim strNumber As String, cpt As Byte, p As Byte Dim i As Byte, Bulls() As Boolean, NbBulls As Byte, Cows As Byte, Poss As Long Const NUMBER_OF_DIGITS As Byte = 4   strNumber = CreateNb(NUMBE...
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Java
Java
myMethod()
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#OCaml
OCaml
let imp_catalan n = let return = ref 1 in for i = 1 to n do return := !return * 2 * (2 * i - 1) / (i + 1) done; !return   let rec catalan = function | 0 -> 1 | n -> catalan (n - 1) * 2 * (2 * n - 1) / (n + 1)   let memoize f = let cache = Hashtbl.create 20 in fun n -> match Hashtbl.find_opt cach...
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#Sidef
Sidef
func brace_expand (input) { var current = [''] var stack = [[current]]   loop { var t = input.match( /\G ((?:[^\\{,}]++ | \\(?:.|\z))++ | . )/gx )[0] \\ break   if (t == '{') { stack << [current = ['']] } elsif ((t == ',') && (stack.len > 1)) {...
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Perl
Perl
use strict; use warnings; use ntheory qw<is_prime>; use constant Inf => 1e10;   sub is_Brazilian { my($n) = @_; return 1 if $n > 6 && 0 == $n%2; LOOP: for (my $base = 2; $base < $n - 1; ++$base) { my $digit; my $nn = $n; while (1) { my $x = $nn % $base; $digi...
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#Liberty_BASIC
Liberty BASIC
  rem Adapted from LB examples included with software [start] prompt "Enter year(yyyy)?";year if year<1900 then notice "1900 or later":goto [start] ax=1:gx=8:ay=3:gy=10 locate 52,1:print year for mr = 0 to 3 for mc = 0 to 2 mt=mt+1 aDate$ = str$(mt)+"/01/"+str$(year) ...
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#Perl
Perl
sub PI() { atan2(1,1) * 4 } # The, er, pi sub STEP() { .5 } # How far does the particle move each step. Affects # both speed and accuracy greatly sub STOP_RADIUS() { 100 } # When the tree reaches this far from center, end   # At each step, move this much tow...
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Fortran
Fortran
module bac implicit none   contains   subroutine Gennum(n) integer, intent(out) :: n(4) integer :: i, j real :: r   call random_number(r) n(1) = int(r * 9.0) + 1 i = 2   outer: do while (i <= 4) call random_number(r) n(i) = int(r * 9.0) + 1 inner: do j = i-1 , 1, -1 ...
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...
#Eiffel
Eiffel
  class APPLICATION   inherit ARGUMENTS   create make   feature {NONE} -- Initialization   make -- Run application. local s: STRING_32 do s := "The tiny tiger totally taunted the tall Till." print ("%NString to encode: " + s) print ("%NEncoded string: " + encode (s, 12)) print ("%NDecoded stri...
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Rust
Rust
const EPSILON: f64 = 1e-15;   fn main() { let mut fact: u64 = 1; let mut e: f64 = 2.0; let mut n: u64 = 2; loop { let e0 = e; fact *= n; n += 1; e += 1.0 / fact as f64; if (e - e0).abs() < EPSILON { break; } } println!("e = {:.15}", e);...
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Scala
Scala
import scala.annotation.tailrec   object CalculateE extends App { private val ε = 1.0e-15   @tailrec def iter(fact: Long, ℯ: Double, n: Int, e0: Double): Double = { val newFact = fact * n val newE = ℯ + 1.0 / newFact if (math.abs(newE - ℯ) < ε) ℯ else iter(newFact, newE, n + 1, ℯ) }   println(...
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...
#Wren
Wren
import "random" for Random   var countBullsAndCows = Fn.new { |guess, answer| var bulls = 0 var cows = 0 var i = 0 for (d in guess) { if (answer[i] == d) { bulls = bulls + 1 } else if (answer.contains(d)) { cows = cows + 1 } i = i + 1 } ret...
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#JavaScript
JavaScript
var foo = function() { return arguments.length }; foo() // 0 foo(1, 2, 3) // 3
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#Oforth
Oforth
: catalan( n -- m ) n ifZero: [ 1 ] else: [ catalan( n 1- ) 2 n * 1- * 2 * n 1+ / ] ;
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#Simula
Simula
CLASS ARRAYLISTS; BEGIN   CLASS ITEM;;   CLASS ITEMARRAY(N); INTEGER N; BEGIN REF(ITEM) ARRAY DATA(1:N);  ! OUTTEXT("NEW ITEMARRAY WITH ");!OUTINT(N, 0);!OUTTEXT(" ELEMENTS");  ! OUTIMAGE; END;   CLASS ARRAYLIST; BEGIN   PROCEDURE EXPAND(N); INTEGER N; BEGIN INTEGER I;...
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#Tailspin
Tailspin
  templates braceExpansion composer braceParse [ <part|'[{}\\,]'>* ] // This is not simply <production> because there may be unbalanced special chars rule production: [ <part>* ] rule part: <alternation|balancedBraces|escapedCharacter|'[^{}\\,]+'>+ rule alternation: (<='{'>) [ <production> <alternate>...
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Phix
Phix
with javascript_semantics function same_digits(integer n, b) integer f = remainder(n,b) n = floor(n/b) while n>0 do if remainder(n,b)!=f then return false end if n = floor(n/b) end while return true end function function is_brazilian(integer n) if n>=7 then if remainder...
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#Lingo
Lingo
---------------------------------------- -- @desc Class "Calendar" -- @file parent script "Calendar" ---------------------------------------- property _months property _weekdayStr property _refDateObj property _year property _calStr   on new (me) me._months = ["January", "February", "March", "April", "May",...
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#Phix
Phix
-- demo\rosetta\BrownianTree.exw include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas function redraw_cb(Ihandle /*ih*/, integer /*posx*/, integer /*posy*/) integer x,y,ox,oy integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE") sequence grid = repeat(repeat(0,width),height) integer xy = floor(width...
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#F.23
F#
  open System   let generate_number targetSize = let rnd = Random() let initial = Seq.initInfinite (fun _ -> rnd.Next(1,9)) initial |> Seq.distinct |> Seq.take(targetSize) |> Seq.toList   let countBulls guess target = let hits = List.map2 (fun g t -> if g = t then true else false) guess target List....
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...
#Ela
Ela
open number char monad io string   chars = "ABCDEFGHIJKLMOPQRSTUVWXYZ"   caesar _ _ [] = "" caesar op key (x::xs) = check shifted ++ caesar op key xs where orig = indexOf (string.upper $ toString x) chars shifted = orig `op` key check val | orig == -1 = x | val > 24 = trans $ val - 2...
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Scheme
Scheme
  (import (rnrs))   (define (e) (sum (map (lambda (x) (/ 1.0 x)) (scanl (lambda (a x) (* a x)) 1 (enum-from-to 1 20)))))   (define (enum-from-to m n) (if (>= n m) (iterate-until (lambda (x) (>= x n)) (lambda (x) (+ 1 x)) m) '()))   (define (iterate-until p f x) ...
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...
#Yabasic
Yabasic
  clear screen   guesses = 0   void = ran()   while(len(secret$) < 4) // zero not allowed n$ = chr$(int(ran(1) * 9) + 49) if not(instr(secret$, n$)) secret$ = secret$ + n$ wend   print " Secretly, my opponent just chose a number. But she didn't tell anyone!\n\t\t\t\t", secret$, "." print " I can howev...
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#jq
jq
  # Calling a function that requires no arguments: f() = print("Hello world!") f()     # Calling a function with a fixed number of arguments: function f(x, y, z) x*y - z^2 end   f(3, 4, 2)     # Calling a function with optional arguments: # Note Julia uses multiple dispatch based on argument number and type, so...
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#ooRexx
ooRexx
loop i = 0 to 15 say "catI("i") =" .catalan~catI(i) say "catR1("i") =" .catalan~catR1(i) say "catR2("i") =" .catalan~catR2(i) end   -- This is implemented as static members on a class object -- so that the code is able to keep state information between calls. This -- memoization will speed up things like f...
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#Tcl
Tcl
package require Tcl 8.6   proc combine {cases1 cases2 {insert ""}} { set result {} foreach c1 $cases1 { foreach c2 $cases2 { lappend result $c1$insert$c2 } } return $result } proc expand {string *expvar} { upvar 1 ${*expvar} expanded set a {} set result {} set depth 0 foreach ...
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Python
Python
'''Brazilian numbers'''   from itertools import count, islice     # isBrazil :: Int -> Bool def isBrazil(n): '''True if n is a Brazilian number, in the sense of OEIS:A125134. ''' return 7 <= n and ( 0 == n % 2 or any( map(monoDigit(n), range(2, n - 1)) ) )     # monoDi...
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#Lua
Lua
function print_cal(year) local months={"JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE", "JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"} local daysTitle="MO TU WE TH FR SA SU" local daysPerMonth={31,28,31,30,31,30,31,31,30,31,30,31} local startday=((year-1)*365+math.floor((year-1)/...
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#PicoLisp
PicoLisp
(load "@lib/simul.l")   (de brownianTree (File Size Cnt) (let Img (grid Size Size) (put Img (/ Size 2) (/ Size 2) 'pix T) (use (P Q) (do Cnt (setq P (get Img (rand 1 Size) (rand 1 Size))) (loop (setq Q ((if2 (rand T) (rand T) north east south west) P)) ...
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#FreeBASIC
FreeBASIC
function get_digit( num as uinteger, ps as uinteger ) as uinteger return (num mod 10^(ps+1))\10^ps end function   function is_malformed( num as uinteger ) as boolean if num > 9876 then return true dim as uinteger i, j for i = 0 to 2 for j = i+1 to 3 if get_digit( num, j ) = get_digit...
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...
#Elena
Elena
import system'routines; import system'math; import extensions; import extensions'text;   const string Letters = "abcdefghijklmnopqrstuvwxyz"; const string BigLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const string TestText = "Pack my box with five dozen liquor jugs."; const int Key = 12;   class Encrypting : Enumerat...
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const float: EPSILON is 1.0e-15;   const proc: main is func local var integer: fact is 1; var float: e is 2.0; var float: e0 is 0.0; var integer: n is 2; begin repeat e0 := e; fact *:= n; incr(n); e +:= 1.0 / flt(fact); ...
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Sidef
Sidef
func calculate_e(n=50) { sum(0..n, {|k| 1/k! }) }   say calculate_e() say calculate_e(69).as_dec(100)
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...
#zkl
zkl
d9:="123456789"; choices:=Walker.cproduct(d9,d9,d9,d9).pump(List,// lazy,-->3024, order is important fcn(list){ s:=list.concat(); (s.unique().len()==4) and s or Void.Skip }); do{ guess:=choices[(0).random(choices.len())]; score:=ask("My guess is %s. How many bulls and cows? ".fmt(guess)).strip(); bulls,cows...
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Julia
Julia
  # Calling a function that requires no arguments: f() = print("Hello world!") f()     # Calling a function with a fixed number of arguments: function f(x, y, z) x*y - z^2 end   f(3, 4, 2)     # Calling a function with optional arguments: # Note Julia uses multiple dispatch based on argument number and type, so...
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#PARI.2FGP
PARI/GP
catalan(n)=binomial(2*n,n+1)/n
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function GetGroup(s As String, depth As Integer) As Tuple(Of List(Of String), String) Dim out As New List(Of String) Dim comma = False While Not String.IsNullOrEmpty(s) Dim gs = GetItem(s, depth) Dim g = gs.Item1 s = gs.Item2 I...
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Racket
Racket
#lang racket   (require math/number-theory)   (define (repeat-digit? n base d-must-be-1?) (call-with-values (λ () (quotient/remainder n base)) (λ (q d) (and (or (not d-must-be-1?) (= d 1)) (let loop ((n q)) (if (zero? n) d (call-...
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#M2000_Interpreter
M2000 Interpreter
  Module Calendar (Year, LocaleId) { Function GetMax(Year, Month) { a=date(str$(Year)+"-"+str$(Month)+"-1") max=32 do { max-- m=val(str$(cdate(a,0,0,max), "m")) } until m=Month =max+1 } Function Skip...
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#Processing
Processing
boolean SIDESTICK = false; boolean[][] isTaken;   void setup() { size(512, 512); background(0); isTaken = new boolean[width][height]; isTaken[width/2][height/2] = true; }   void draw() { int x = floor(random(width)); int y = floor(random(height)); if (isTaken[x][y]) { return; } while (true) { ...
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Frink
Frink
  // Bulls and Cows - Written in Frink println["Welcome to Bulls and Cows!"]   // Put 4 random digits into target array digits = array[1 to 9] target = new array for i = 0 to 3 { target@i = digits.removeRandom[] }   // Game variables guessCount = 0 solved = 0   while solved == 0 { // Round variables bulls = 0 ...
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...
#Elixir
Elixir
defmodule Caesar_cipher do defp set_map(map, range, key) do org = Enum.map(range, &List.to_string [&1]) {a, b} = Enum.split(org, key) Enum.zip(org, b ++ a) |> Enum.into(map) end   def encode(text, key) do map = Map.new |> set_map(?a..?z, key) |> set_map(?A..?Z, key) String.graphemes(text) |> E...
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Standard_ML
Standard ML
fun calcEToEps() = let val eps = 1.0e~15 fun calcToEps'(eest: real, prev: real, denom, i) = if Real.abs(eest - prev) < eps then eest else let val denom' = denom * i; val prev' = eest in calcToEps'(eest + 1.0/denom', prev', denom', i + 1.0) ...
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Swift
Swift
import Foundation     func calculateE(epsilon: Double = 1.0e-15) -> Double { var fact: UInt64 = 1 var e = 2.0, e0 = 0.0 var n = 2   repeat { e0 = e fact *= UInt64(n) n += 1 e += 1.0 / Double(fact) } while fabs(e - e0) >= epsilon   return e }   print(String(format: "e = %.15f\n", arguments: [...
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Kotlin
Kotlin
// version 1.0.6   fun fun1() = println("No arguments")   fun fun2(i: Int) = println("One argument = $i")   fun fun3(i: Int, j: Int = 0) = println("One required argument = $i, one optional argument = $j")   fun fun4(vararg v: Int) = println("Variable number of arguments = ${v.asList()}")   fun fun5(i: Int) = i * i   fu...
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#Pascal
Pascal
Program CatalanNumbers(output);   function catalanNumber1(n: integer): double; begin if n = 0 then catalanNumber1 := 1.0 else catalanNumber1 := double(4 * n - 2) / double(n + 1) * catalanNumber1(n-1); end;   var number: integer;   begin writeln('Catalan Numbers'); writeln('Recursion with ...
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#Wren
Wren
var getGroup // forward declaration   var getItem = Fn.new { |s, depth| var out = [""] while (s != "") { var c = s[0] if (depth > 0 && (c == "," || c == "}")) return [out, s] var cont = false if (c == "{") { var x = getGroup.call(s[1..-1], depth+1) if (!x[...
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Raku
Raku
multi is-Brazilian (Int $n where $n %% 2 && $n > 6) { True }   multi is-Brazilian (Int $n) { LOOP: loop (my int $base = 2; $base < $n - 1; ++$base) { my $digit; for $n.polymod( $base xx * ) { $digit //= $_; next LOOP if $digit != $_; } return True } Fa...
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
DataGrid[ rowHeights:{__Integer}, colWidths:{__Integer}, spacings:{_Integer,_Integer}, borderWidths:{{_Integer,_Integer},{_Integer,_Integer}}, options_Association, data:{__List?MatrixQ}]:= With[ (*Need to make sure we have sensible defaults for the decoration options.*) {alignment=Lookup[options,"...
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#PureBasic
PureBasic
#Window1 = 0 #Image1 = 0 #ImgGadget = 0   #NUM_PARTICLES = 3000 #width = 200 #height = 200 #xmax = #width -3 #ymax = #height -3 Define.i Event ,i ,x,y   If OpenWindow(#Window1, 0, 0, #width, #height, "Brownian Tree PureBasic Example", #PB_Window_SystemMenu ) If CreateImage(#Ima...
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Go
Go
package main   import ( "bufio" "bytes" "fmt" "math/rand" "os" "strings" "time" )   func main() { fmt.Println(`Cows and Bulls Guess four digit number of unique digits in the range 1 to 9. A correct digit but not in the correct place is a cow. A correct digit in the correct place is a bul...
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...
#Erlang
Erlang
  %% Ceasar cypher in Erlang for the rosetta code wiki. %% Implemented by J.W. Luiten   -module(ceasar). -export([main/2]).   %% rot: rotate Char by Key places rot(Char,Key) when (Char >= $A) and (Char =< $Z) or (Char >= $a) and (Char =< $z) -> Offset = $A + Char band 32, N = Char - Offset, Off...
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Tcl
Tcl
  set ε 1.0e-15 set fact 1 set e 2.0 set e0 0.0 set n 2   while {[expr abs($e - $e0)] > ${ε}} { set e0 $e set fact [expr $fact * $n] incr n set e [expr $e + 1.0/$fact] } puts "e = $e"
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#TI-83_BASIC
TI-83 BASIC
0->D 2->N 2->E 1->F 1.0E-12->Z While abs(E-D)>Z F*N->F N+1->N E->D E+1/F->E End Disp E  
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Lambdatalk
Lambdatalk
    The command   replace  :a0 :a1 ... an-1 in expression containing some occurences of :ai by v0 v1 ... vp-1   is rewritten in a prefixed parenthesized form   {{lambda {:a0 :a1 ... an-1} expression containing some occurences of :ai} v0 v1 ... vp-1}   so called IIFE (Immediately Invok...
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#Perl
Perl
sub factorial { my $f = 1; $f *= $_ for 2 .. $_[0]; $f; } sub catalan { my $n = shift; factorial(2*$n) / factorial($n+1) / factorial($n); }   print "$_\t@{[ catalan($_) ]}\n" for 0 .. 20;
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#zkl
zkl
fcn eyeball(code,ps=L(),brace=False){ //-->indexes of valid braces & commas cs:=L(); foreach c in (code){ // start fresh or continue (if recursing) switch(c){ case("\\"){ __cWalker.next(); } case(",") { if(brace) cs.append(__cWalker.n); } // maybe valid case("{") { // this is real only if there is ma...
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#REXX
REXX
/*REXX pgm finds: 1st N Brazilian #s; odd Brazilian #s; prime Brazilian #s; ZZZth #.*/ parse arg t.1 t.2 t.3 t.4 . /*obtain optional arguments from the CL*/ if t.4=='' | t.4=="," then t.4= 0 /*special test case of Nth Brazilian #.*/ hdr.1= 'first'; hdr.2= "first odd"; hdr.3= ...
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#Overview
Overview
DataGrid[ rowHeights:{__Integer}, colWidths:{__Integer}, spacings:{_Integer,_Integer}, borderWidths:{{_Integer,_Integer},{_Integer,_Integer}}, options_Association, data:{__List?MatrixQ}]:= With[ (*Need to make sure we have sensible defaults for the decoration options.*) {alignment=Lookup[options,"...
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#Python
Python
import pygame, sys, os from pygame.locals import * from random import randint pygame.init()   MAXSPEED = 15 SIZE = 3 COLOR = (45, 90, 45) WINDOWSIZE = 400 TIMETICK = 1 MAXPART = 50   freeParticles = pygame.sprite.Group() tree = pygame.sprite.Group()   window = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE)) pygame.di...