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/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 randomly chosen number, and the program ends. A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number. A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position. Related tasks   Bulls and cows/Player   Guess the number   Guess the number/With Feedback   Mastermind
#Golo
Golo
#!/usr/bin/env golosh ---- This module is the Bulls and Cows game. ---- module Bullsandcows   import gololang.Decorators import gololang.Functions import gololang.IO import java.util   function main = |args| { while true { let secret = create4RandomNumbers() println("Welcome to Bulls And Cows") while true { println("Please enter a 4 digit number") println("(with only the digits 1 to 9 and no repeated digits, for example 2537)") let guess = readln("guess: ") let result = validateGuess(guess) if result: isValid() { let bulls, cows = bullsAndOrCows(result: digits(), secret) if bulls is 4 { println("You win!") break } println("bulls: " + bulls) println("cows: " + cows) } else { println(result: message()) } } } }   function create4RandomNumbers = { let numbers = vector[1, 2, 3, 4, 5, 6, 7, 8, 9] Collections.shuffle(numbers) let shuffled = numbers: subList(0, 4) return shuffled }   union Result = { Valid = { digits } Invalid = { message } }   @checkArguments(isString()) function validateGuess = |guess| { var digits = [] try { let number = guess: toInt() digits = number: digits() if digits: exists(|d| -> d is 0) { return Result.Invalid("No zeroes please") } if digits: size() isnt 4 { return Result.Invalid("Four digits please") } let digitSet = set[ digit foreach digit in digits ] if digitSet: size() < digits: size() { return Result.Invalid("No duplicate numbers please") } } catch(e) { return Result.Invalid("Numbers only please") } return Result.Valid(digits) }   let is4Vector = |arg| -> arg oftype java.util.List.class and arg: size() is 4   @checkArguments(is4Vector, is4Vector) function bullsAndOrCows = |guess, secret| { var bulls = 0 var cows = 0 foreach i in [0..4] { let guessNum = guess: get(i) let secretNum = secret: get(i) if guessNum is secretNum { bulls = bulls + 1 } else if secret: exists(|num| -> guessNum is num) { cows = cows + 1 } } return [bulls, cows] }   augment java.lang.Integer {   function digits = |this| { var remaining = this let digits = vector[] while remaining > 0 { digits: prepend(remaining % 10) remaining = remaining / 10 } return digits } }  
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 "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#ERRE
ERRE
  PROGRAM CAESAR   !$INCLUDE="PC.LIB"   PROCEDURE CAESAR(TEXT$,KY%->CY$) LOCAL I%,C% FOR I%=1 TO LEN(TEXT$) DO C%=ASC(MID$(TEXT$,I%)) IF (C% AND $1F)>=1 AND (C% AND $1F)<=26 THEN C%=(C% AND $E0) OR (((C% AND $1F)+KY%-1) MOD 26+1) CHANGE(TEXT$,I%,CHR$(C%)->TEXT$) END IF END FOR CY$=TEXT$ END PROCEDURE   BEGIN RANDOMIZE(TIMER) PLAINTEXT$="Pack my box with five dozen liquor jugs" PRINT(PLAINTEXT$)   KY%=1+INT(25*RND(1))  ! generates random between 1 and 25 CAESAR(PLAINTEXT$,KY%->CYPHERTEXT$) PRINT(CYPHERTEXT$)   CAESAR(CYPHERTEXT$,26-KY%->DECYPHERED$) PRINT(DECYPHERED$)   END PROGRAM  
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
#VBScript
VBScript
e0 = 0 : e = 2 : n = 0 : fact = 1 While (e - e0) > 1E-15 e0 = e n = n + 1 fact = fact * 2*n * (2*n + 1) e = e + (2*n + 2)/fact Wend   WScript.Echo "Computed e = " & e WScript.Echo "Real e = " & Exp(1) WScript.Echo "Error = " & (Exp(1) - e) WScript.Echo "Number of iterations = " & n
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
#Verilog
Verilog
module main; real n, n1; real e1, e;   initial begin n = 1.0; n1 = 1.0; e1 = 0.0; e = 1.0;   while (e != e1) begin e1 = e; e = e + (1.0 / n); n1 = n1 + 1; n = n * n1; end $display("The value of e = ", e); $finish ; end endmodule
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   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#langur
langur
.x() # call user-defined function
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_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#Phix
Phix
with javascript_semantics -- returns inf/-nan for n>85, and needs the rounding for n>=14, accurate to n=29 function catalan1(integer n) return floor(factorial(2*n)/(factorial(n+1)*factorial(n))+0.5) end function -- returns inf for n>519, accurate to n=30: function catalan2(integer n) -- NB: very slow! atom res = not n n -= 1 for i=0 to n do res += catalan2(i)*catalan2(n-i) end for return res end function -- returns inf for n>514, accurate to n=30: function catalan3(integer n) if n=0 then return 1 end if return 2*(2*n-1)/(1+n)*catalan3(n-1) end function sequence res = repeat(repeat(0,4),16), times = repeat(0,3) for t=1 to 4 do atom t0 = time() for i=0 to 15 do switch t do case 1: res[i+1][2] = catalan1(i) case 2: res[i+1][3] = catalan2(i) case 3: res[i+1][4] = catalan3(i) case 4: res[i+1][1] = i; printf(1,"%2d: %10d %10d %10d\n",res[i+1]) end switch end for if t=4 then exit end if times[t] = elapsed(time()-t0) end for printf(1,"times:%8s %10s %10s\n",times)
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 representation of N in base B has all equal digits. E.G. 1, 2 & 3 can not be Brazilian; there is no base B that satisfies the condition 1 < B < N-1. 4 is not Brazilian; 4 in base 2 is 100. The digits are not all the same. 5 is not Brazilian; 5 in base 2 is 101, in base 3 is 12. There is no representation where the digits are the same. 6 is not Brazilian; 6 in base 2 is 110, in base 3 is 20, in base 4 is 12. There is no representation where the digits are the same. 7 is Brazilian; 7 in base 2 is 111. There is at least one representation where the digits are all the same. 8 is Brazilian; 8 in base 3 is 22. There is at least one representation where the digits are all the same. and so on... All even integers 2P >= 8 are Brazilian because 2P = 2(P-1) + 2, which is 22 in base P-1 when P-1 > 2. That becomes true when P >= 4. More common: for all all integers R and S, where R > 1 and also S-1 > R, then R*S is Brazilian because R*S = R(S-1) + R, which is RR in base S-1 The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. All prime integers, that are brazilian, can only have the digit 1. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of 111 to base Integer(sqrt(prime number)). Must be an odd count of 1 to stay odd like primes > 2 Task Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page; the first 20 Brazilian numbers; the first 20 odd Brazilian numbers; the first 20 prime Brazilian numbers; See also OEIS:A125134 - Brazilian numbers OEIS:A257521 - Odd Brazilian numbers OEIS:A085104 - Prime Brazilian numbers
#Ring
Ring
  load "stdlib.ring"   decList = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] baseList = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"] brazil = [] brazilOdd = [] brazilPrime = [] num1 = 0 num2 = 0 num3 = 0 limit = 20   see "working..." + nl for n = 1 to 2802 for m = 2 to 16 flag = 1 basem = decimaltobase(n,m) for p = 1 to len(basem)-1 if basem[p] != basem[p+1] flag = 0 exit ok next if flag = 1 and m < n - 1 add(brazil,n) delBrazil(brazil) ok if flag = 1 and m < n - 1 and n % 2 = 1 add(brazilOdd,n) delBrazil(brazilOdd) ok if flag = 1 and m < n - 1 and isprime(n) add(brazilPrime,n) delBrazil(brazilPrime) ok next next   see "2 <= base <= 16" + nl see "first 20 brazilian numbers:" + nl showarray(brazil) see "first 20 odd brazilian numbers:" + nl showarray(brazilOdd) see "first 11 brazilian prime numbers:" + nl showarray(brazilPrime)   see "done..." + nl   func delBrazil(brazil) for z = len(brazil) to 2 step -1 if brazil[z] = brazil[z-1] del(brazil,z) ok next   func decimaltobase(nr,base) binList = [] binary = 0 remainder = 1 while(nr != 0) remainder = nr % base ind = find(decList,remainder) rem = baseList[ind] add(binList,rem) nr = floor(nr/base) end binlist = reverse(binList) binList = list2str(binList) binList = substr(binList,nl,"") return binList   func showArray(array) txt = "" if len(array) < limit limit = len(array) ok for n = 1 to limit txt = txt + array[n] + "," next txt = left(txt,len(txt)-1) see txt + nl  
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 formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43. (Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.) Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar. This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983. THE REAL PROGRAMMER'S NATURAL HABITAT "Taped to the wall is a line-printer Snoopy calender for the year 1969." For further Kudos see task CALENDAR, where all code is to be in UPPERCASE. For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. Related task   Five weekends
#1._Grid_structure_functions
1. Grid structure functions
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,"alignment",{0,0}], background=Lookup[options,"background"," "], dividers=Lookup[options,"dividers",{" "," "," "}], border=Lookup[options,"border"," "], dims={Length[rowHeights],Length[colWidths]}}, (*Pad the data so that it will fit into the specified rectangle (list of lists).*) With[{augmentedData=PadRight[data,Times@@dims,{{{background}}}]}, (*Create a matrix of dimensions based on desired rectangle. Once we have a matrix of cells we can "thread" these two matrices and use that data to coerce each cell into its final dimensions.*) With[{cellDims=ArrayReshape[Outer[List,rowHeights,colWidths],{Times@@dims,2}]}, (*MatrixAlign, defined below, rescales and aligns each cell's data.*) With[{undecoratedGrid=Partition[MapThread[MatrixAlign[alignment,#1,background][#2]&, {cellDims,augmentedData}],dims[[2]]]}, (*Add the spacing to each row.*) With[{dividedRows=MapThread[Transpose[Riffle[#2,{ConstantArray[dividers[[2]],{#1,spacings[[2]]}]},{2,-2,2}]]&, {rowHeights,undecoratedGrid}]}, (*Add the spacing between rows.*) With[{dividedColumn=Riffle[dividedRows,{Transpose[Riffle[ConstantArray[dividers[[1]],{spacings[[1]],#}]&/@colWidths,{ConstantArray[dividers[[3]],spacings]},{2,-2,2}]]},{2,-2,2}]}, (*Assemble all cell rows into actual character rows. We now have one large matrix.*) With[{dividedGrid=Catenate[Map[Flatten,dividedColumn,{2}]]}, (*Add borders.*) ArrayPad[dividedGrid,borderWidths,border]]]]]]]];   DataGrid[dims:{_Integer,_Integer},spacings_,borderWidths_,options_,data:{__List?MatrixQ}]:= (*Calculate the max height for each row and max width for each column, and then just call the previous DataGrid function above.*) With[ {rowHeights=Flatten@BlockMap[Max[Part[#,All,All,1]]&,ArrayReshape[Dimensions/@data,Append[dims,2],1],{1,dims[[2]]}], colWidths=Flatten@BlockMap[Max[Part[#,All,All,2]]&,ArrayReshape[Dimensions/@data,Append[dims,2],1],{dims[[1]],1}]}, DataGrid[rowHeights,colWidths,spacings,borderWidths,options,data]];   (*This could probably be simplified, but I like having all of the aligment options explicit and separate for testability.*) MatrixAlign[{-1,-1},dims_,pad_]:=PadRight[#,dims,pad]&; MatrixAlign[{-1,0},dims_,pad_]:=PadRight[CenterArray[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&; MatrixAlign[{-1,1},dims_,pad_]:=PadRight[PadLeft[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&; MatrixAlign[{0,-1},dims_,pad_]:=CenterArray[PadRight[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&; MatrixAlign[{0,0},dims_,pad_]:=CenterArray[#,dims,pad]&; MatrixAlign[{0,1},dims_,pad_]:=CenterArray[PadLeft[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&; MatrixAlign[{1,-1},dims_,pad_]:=PadLeft[PadRight[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&; MatrixAlign[{1,0},dims_,pad_]:=PadLeft[CenterArray[#,{Dimensions[#][[1]],dims[[2]]},pad],dims,pad]&; MatrixAlign[{1,1},dims_,pad_]:=PadLeft[#,dims,pad]&;   (*While the grid functions make no assumptions about the format of the data, we will be using them with string/character data, and we will eventually want to output a calendar as a single large string. AsString gives us a standard method for transforming a matrix of characters into a string with rows delimited by newlines.*) AsString[matrix_List?MatrixQ]:=StringRiffle[matrix,"\n",""];
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 within the field. Where is not particularly important; it could be randomized, or it could be a fixed point. Particles are injected into the field, and are individually given a (typically random) motion pattern. When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree. Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
#R
R
  # plotmat(): Simple plotting using a square matrix mat (filled with 0/1). v. 8/31/16 # Where: mat - matrix; fn - file name; clr - color; ttl - plot title; # dflg - writing dump file flag (0-no/1-yes): psz - picture size. plotmat <- function(mat, fn, clr, ttl, dflg=0, psz=600) { m <- nrow(mat); d <- 0; X=NULL; Y=NULL; pf = paste0(fn, ".png"); df = paste0(fn, ".dmp"); for (i in 1:m) { for (j in 1:m) {if(mat[i,j]==0){next} else {d=d+1; X[d] <- i; Y[d] <- j;} } }; cat(" *** Matrix(", m,"x",m,")", d, "DOTS\n"); # Dumping if requested (dflg=1). if (dflg==1) {dump(c("X","Y"), df); cat(" *** Dump file:", df, "\n")}; # Plotting plot(X,Y, main=ttl, axes=FALSE, xlab="", ylab="", col=clr, pch=20); dev.copy(png, filename=pf, width=psz, height=psz); # Cleaning dev.off(); graphics.off(); }   # plotv2(): Simple plotting using 2 vectors (dumped into ".dmp" file by plotmat()). # Where: fn - file name; clr - color; ttl - plot title; psz - picture size. # v. 8/31/16 plotv2 <- function(fn, clr, ttl, psz=600) { cat(" *** START:", date(), "clr=", clr, "psz=", psz, "\n"); cat(" *** File name -", fn, "\n"); pf = paste0(fn, ".png"); df = paste0(fn, ".dmp"); source(df); d <- length(X); cat(" *** Source dump-file:", df, d, "DOTS\n"); cat(" *** Plot file -", pf, "\n"); # Plotting plot(X, Y, main=ttl, axes=FALSE, xlab="", ylab="", col=clr, pch=20); # Writing png-file dev.copy(png, filename=pf, width=psz, height=psz); # Cleaning dev.off(); graphics.off(); cat(" *** END:", date(), "\n"); }  
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 randomly chosen number, and the program ends. A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number. A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position. Related tasks   Bulls and cows/Player   Guess the number   Guess the number/With Feedback   Mastermind
#Groovy
Groovy
class BullsAndCows { static void main(args) { def inputReader = System.in.newReader() def numberGenerator = new Random() def targetValue while (targetValueIsInvalid(targetValue = numberGenerator.nextInt(9000) + 1000)) continue def targetStr = targetValue.toString() def guessed = false def guesses = 0 while (!guessed) { def bulls = 0, cows = 0 print 'Guess a 4-digit number with no duplicate digits: ' def guess = inputReader.readLine() if (guess.length() != 4 || !guess.isInteger() || targetValueIsInvalid(guess.toInteger())) { continue } guesses++ 4.times { if (targetStr[it] == guess[it]) { bulls++ } else if (targetStr.contains(guess[it])) { cows++ } } if (bulls == 4) { guessed = true } else { println "$cows Cows and $bulls Bulls." } } println "You won after $guesses guesses!" }   static targetValueIsInvalid(value) { def digitList = [] while (value > 0) { if (digitList[value % 10] == 0 || digitList[value % 10]) { return true } digitList[value % 10] = true value = value.intdiv(10) } false } }    
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 "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Euphoria
Euphoria
  --caesar cipher for Rosetta Code wiki --User:Lnettnay   --usage eui caesar ->default text, key and encode flag --usage eui caesar 'Text with spaces and punctuation!' 5 D --If text has imbedded spaces must use apostophes instead of quotes so all punctuation works --key = integer from 1 to 25, defaults to 13 --flag = E (Encode) or D (Decode), defaults to E --no error checking is done on key or flag   include std/get.e include std/types.e     sequence cmd = command_line() sequence val -- default text for encryption sequence text = "The Quick Brown Fox Jumps Over The Lazy Dog." atom key = 13 -- default to Rot-13 sequence flag = "E" -- default to Encrypt atom offset atom num_letters = 26 -- number of characters in alphabet   --get text if length(cmd) >= 3 then text = cmd[3] end if   --get key value if length(cmd) >= 4 then val = value(cmd[4]) key = val[2] end if   --get Encrypt/Decrypt flag if length(cmd) = 5 then flag = cmd[5] if compare(flag, "D") = 0 then key = 26 - key end if end if   for i = 1 to length(text) do if t_alpha(text[i]) then if t_lower(text[i]) then offset = 'a' else offset = 'A' end if text[i] = remainder(text[i] - offset + key, num_letters) + offset end if end for   printf(1,"%s\n",{text})    
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
#Visual_Basic_.NET
Visual Basic .NET
Imports System, System.Numerics, System.Math, System.Console   Module Program Function CalcE(ByVal nDigs As Integer) As String Dim pad As Integer = Round(Log10(nDigs)), n = 1, f As BigInteger = BigInteger.Pow(10, nDigs + pad), e = f + f Do : n+= 1 : f /= n : e += f : Loop While f > n Return (e / BigInteger.Pow(10, pad + 1)).ToString().Insert(1, ".") End Function   Sub Main() WriteLine(Exp(1)) ' double precision built-in function WriteLine(CalcE(100)) ' arbitrary precision result Dim st As DateTime = DateTime.Now, qmil As Integer = 250_000, es As String = CalcE(qmil) ' large arbitrary precision result string WriteLine("{0:n0} digits in {1:n3} seconds.", qmil, (DateTime.Now - st).TotalSeconds) WriteLine("partial: {0}...{1}", es.Substring(0, 46), es.Substring(es.Length - 45)) End Sub End Module
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   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#Latitude
Latitude
foo (1, 2, 3). ; (1) Ordinary call foo ().  ; (2) No arguments foo.  ; (3) Equivalent to (2) foo (1).  ; (4) Single-argument function foo 1.  ; (5) Equivalent to (4) foo (bar).  ; (6) Parentheses necessary here since bar is not a literal foo: 1, 2, 3.  ; (7) Alternative syntax, equivalent to (1)
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_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#PHP
PHP
<?php   class CatalanNumbersSerie { private static $cache = array(0 => 1);   private function fill_cache($i) { $accum = 0; $n = $i-1; for($k = 0; $k <= $n; $k++) { $accum += $this->item($k)*$this->item($n-$k); } self::$cache[$i] = $accum; } function item($i) { if (!isset(self::$cache[$i])) { $this->fill_cache($i); } return self::$cache[$i]; } }   $cn = new CatalanNumbersSerie(); for($i = 0; $i <= 15;$i++) { $r = $cn->item($i); echo "$i = $r\r\n"; } ?>
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 representation of N in base B has all equal digits. E.G. 1, 2 & 3 can not be Brazilian; there is no base B that satisfies the condition 1 < B < N-1. 4 is not Brazilian; 4 in base 2 is 100. The digits are not all the same. 5 is not Brazilian; 5 in base 2 is 101, in base 3 is 12. There is no representation where the digits are the same. 6 is not Brazilian; 6 in base 2 is 110, in base 3 is 20, in base 4 is 12. There is no representation where the digits are the same. 7 is Brazilian; 7 in base 2 is 111. There is at least one representation where the digits are all the same. 8 is Brazilian; 8 in base 3 is 22. There is at least one representation where the digits are all the same. and so on... All even integers 2P >= 8 are Brazilian because 2P = 2(P-1) + 2, which is 22 in base P-1 when P-1 > 2. That becomes true when P >= 4. More common: for all all integers R and S, where R > 1 and also S-1 > R, then R*S is Brazilian because R*S = R(S-1) + R, which is RR in base S-1 The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. All prime integers, that are brazilian, can only have the digit 1. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of 111 to base Integer(sqrt(prime number)). Must be an odd count of 1 to stay odd like primes > 2 Task Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page; the first 20 Brazilian numbers; the first 20 odd Brazilian numbers; the first 20 prime Brazilian numbers; See also OEIS:A125134 - Brazilian numbers OEIS:A257521 - Odd Brazilian numbers OEIS:A085104 - Prime Brazilian numbers
#Ruby
Ruby
def sameDigits(n,b) f = n % b while (n /= b) > 0 do if n % b != f then return false end end return true end   def isBrazilian(n) if n < 7 then return false end if n % 2 == 0 then return true end for b in 2 .. n - 2 do if sameDigits(n, b) then return true end end return false end   def isPrime(n) if n < 2 then return false end if n % 2 == 0 then return n == 2 end if n % 3 == 0 then return n == 3 end d = 5 while d * d <= n do if n % d == 0 then return false end d = d + 2   if n % d == 0 then return false end d = d + 4 end return true end   def main for kind in ["", "odd ", "prime "] do quiet = false bigLim = 99999 limit = 20 puts "First %d %sBrazilian numbers:" % [limit, kind] c = 0 n = 7 while c < bigLim do if isBrazilian(n) then if not quiet then print "%d " % [n] end c = c + 1 if c == limit then puts puts quiet = true end end if quiet and kind != "" then next end if kind == "" then n = n + 1 elsif kind == "odd " then n = n + 2 elsif kind == "prime " then loop do n = n + 2 if isPrime(n) then break end end else raise "Unexpected" end end if kind == "" then puts "The %dth Brazillian number is: %d" % [bigLim + 1, n] puts end end end   main()
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 formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43. (Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.) Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar. This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983. THE REAL PROGRAMMER'S NATURAL HABITAT "Taped to the wall is a line-printer Snoopy calender for the year 1969." For further Kudos see task CALENDAR, where all code is to be in UPPERCASE. For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. Related task   Five weekends
#2._Calendar_data_functions
2. Calendar data functions
(*Mathematica makes it easy to get month names and day names for several standard calendars.*) MonthNames[]:=MonthNames["Gregorian"]; MonthNames[calType_]:=Lookup[CalendarData[calType,"PropertyAssociation"],"MonthNames"];   WeekdayNames[]:=WeekdayNames["Gregorian"]; WeekdayNames[calType_]:=Lookup[CalendarData[calType,"PropertyAssociation"],"DayNames"];   (*Since month boundaries don't align with week boundaries on most calendars, we need to pad month data with empty cells. I was tempted to create a function that would generate offsets for a given year on a given calendar, but even that required too many decisions on the part of the calendar maker to be feasible. So, I removed all of the calendar semantics. If you provide the fixed small group length (week length), the initial offset, and the list of the large group lengths (month lengths), this function will give you the offsets you need for each large group (month).*) Offsets[groupLength_,firstOffset_,lengths_List]:=FoldPairList[{#1,Mod[#1+#2,groupLength]}&,firstOffset,lengths];
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 within the field. Where is not particularly important; it could be randomized, or it could be a fixed point. Particles are injected into the field, and are individually given a (typically random) motion pattern. When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree. Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
#Racket
Racket
#lang racket (require 2htdp/image)   ;; The unsafe fixnum ops are faster than the checked ones, ;; but if you get anything wrong with them, they'll bite. ;; If you experience any problems reactivate the ;; (require racket/fixnum) and instead of the unsafe requirement ;; below...   ;; we have tested this... #;(require racket/fixnum) ;; so we can use this... (require racket/require (only-in racket/fixnum make-fxvector in-fxvector) (filtered-in (? (name) (regexp-replace #rx"unsafe-" name "")) racket/unsafe/ops))   ;;; This implementation uses a 1d, mutable, fixnum vector ;;; there's a lot of work done making the tree, so this optimisation ;;; at the expense of clarity has been made. Sorry, guys! (define (brownian-tree w h collisions n-particles seed-tree generate-particle walk-particle) (define w*h (fx* w h)) (define V (make-fxvector w*h)) (define (collision? x.y) (fx> (fxvector-ref V x.y) 0))    ;; The main loop (define (inner-b-t collisions particles) (cond [(fx= 0 collisions) V] [else (define-values (new-particles new-collisions) (for/fold ((prtcls null) (clsns 0)) ((x.y particles) #:break (fx= collisions clsns)) (define new-particle (walk-particle x.y w h w*h)) (cond [(not new-particle) ; it died! (values (cons (generate-particle V w h w*h) prtcls) clsns)] [(collision? new-particle) (fxvector-set! V x.y 1) (values (cons (generate-particle V w h w*h) prtcls) (add1 clsns))] [else (values (cons new-particle prtcls) clsns)]))) (when (fx> new-collisions 0) (define remain (fx- collisions new-collisions)) (unless (fx= (exact-floor (* 10 (log collisions))) (exact-floor (* 10 (log (fxmax 1 remain))))) (eprintf "~a (e^~a)~%" remain (log (fxmax 1 remain)))) (log-info "~a new collisions: ~a remain~%" new-collisions remain)) (inner-b-t (fxmax 0 (fx- collisions new-collisions)) new-particles)]))    ;; Seed the tree (seed-tree V w h) (inner-b-t collisions (build-list n-particles (lambda (x) (generate-particle V w h w*h)))))   ;; See below for why we do the (fxremainder ...) test (define (uniform-particle-generator v w h w*h) (define x.y (random w*h)) (define valid-x.y? (and (fx= (fxvector-ref v x.y) 0) ; start on empty cell (fx> (fxremainder x.y w) 0))) ; not on left edge  ; if it's valid take it otherwise regenerate (if valid-x.y? x.y (uniform-particle-generator v w h w*h)))   ;; The boundaries to the walker are to remain within the limits of ;; the vector... however, unless we stop particles going off the ;; east/west edges, the tree will be formed on a cylinder as the ;; particles wrap. So we kill particles that reach the left edge ;; either by decrement from the right or by incrementing and wrapping. ;; This is is tested with (= 0 (remainder x.y w)). (define (brownian-particle-walker x.y w h w*h) (define dx (fx- (random 3) 1)) (define dy (fx- (random 3) 1)) (define new-x.y (fx+ x.y (fx+ dx (fx* w dy)))) (and (fx> new-x.y 0) (fx< new-x.y w*h) (fx> (fxremainder new-x.y w) 0) new-x.y))   ;; These seed functions modify v however you want! (define (seed-middle v w h) (fxvector-set! v (+ (quotient w 2) (* w (quotient h 2))) 1))   (define (seed-circle v w h) (for ((a (in-range 0 360 120))) (define x (exact-floor (* w 1/8 (+ 4 (sin (* pi 1/180 a)))))) (define y (exact-floor (* h 1/8 (+ 4 (cos (* pi 1/180 a)))))) (fxvector-set! v (+ x (* w y)) 1)))   ;; SCALE is a general purpose knob for modifying the size of the problem ;; complexity increases with the sqaure of SCALE (at least) (define SCALE 1) (define tree-W (* SCALE 320)) (define tree-H (* SCALE 240)) (define tree-W.H (* tree-W tree-H)) ;; play with tree-PARTICLES -- small values will lead to a smaller tree ;; as the tree moves towards the edges, more particles might affect its shape (define tree-PARTICLES (quotient tree-W.H 4)) ;; these are the particles that are bimbling around at any one time. If it's ;; too low, you might get bored waiting for a collision... if it's too high ;; you might get inappropriate collisions (define working-PARTICLES (quotient tree-W.H 300))   (define b-t (time (brownian-tree tree-W tree-H tree-PARTICLES working-PARTICLES seed-middle uniform-particle-generator brownian-particle-walker)))   (define (b-t-value->color c) (case c ((1) "black") (else "white"))) (define img (color-list->bitmap (for*/list ((x (in-fxvector b-t))) (b-t-value->color x)) tree-W tree-H))   img (save-image img "brownian-tree.png")
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 within the field. Where is not particularly important; it could be randomized, or it could be a fixed point. Particles are injected into the field, and are individually given a (typically random) motion pattern. When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree. Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
#Raku
Raku
constant size = 100; constant particlenum = 1_000;     constant mid = size div 2;   my $spawnradius = 5; my @map;   sub set($x, $y) { @map[$x][$y] = True; }   sub get($x, $y) { return @map[$x][$y] || False; }   set(mid, mid); my @blocks = " ","\c[UPPER HALF BLOCK]", "\c[LOWER HALF BLOCK]","\c[FULL BLOCK]";   sub infix:<█>($a, $b) { @blocks[$a + 2 * $b] }   sub display { my $start = 0; my $end = size; say (for $start, $start + 2 ... $end -> $y { (for $start..$end -> $x { if abs(($x&$y) - mid) < $spawnradius { get($x, $y) █ get($x, $y+1); } else { " " } }).join }).join("\n") }   for ^particlenum -> $progress { my Int $x; my Int $y; my &reset = { repeat { ($x, $y) = (mid - $spawnradius..mid + $spawnradius).pick, (mid - $spawnradius, mid + $spawnradius).pick; ($x, $y) = ($y, $x) if (True, False).pick(); } while get($x,$y); } reset;   while not get($x-1|$x|$x+1, $y-1|$y|$y+1) { $x = ($x-1, $x, $x+1).pick; $y = ($y-1, $y, $y+1).pick; if (False xx 3, True).pick { $x = $x >= mid ?? $x - 1 !! $x + 1; $y = $y >= mid ?? $y - 1 !! $y + 1; } if abs(($x | $y) - mid) > $spawnradius { reset; } } set($x,$y); if $spawnradius < mid && abs(($x|$y) - mid) > $spawnradius - 5 { $spawnradius = $spawnradius + 1; } }   display;
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 randomly chosen number, and the program ends. A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number. A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position. Related tasks   Bulls and cows/Player   Guess the number   Guess the number/With Feedback   Mastermind
#Haskell
Haskell
import Data.List (partition, intersect, nub) import Control.Monad import System.Random (StdGen, getStdRandom, randomR) import Text.Printf   numberOfDigits = 4 :: Int   main = bullsAndCows   bullsAndCows :: IO () bullsAndCows = do digits <- getStdRandom $ pick numberOfDigits ['1' .. '9'] putStrLn "Guess away!" loop digits   where loop digits = do input <- getLine if okay input then let (bulls, cows) = score digits input in if bulls == numberOfDigits then putStrLn "You win!" else do printf "%d bulls, %d cows.\n" bulls cows loop digits else do putStrLn "Malformed guess; try again." loop digits   okay :: String -> Bool okay input = length input == numberOfDigits && input == nub input && all legalchar input where legalchar c = '1' <= c && c <= '9'   score :: String -> String -> (Int, Int) score secret guess = (length bulls, cows) where (bulls, nonbulls) = partition (uncurry (==)) $ zip secret guess cows = length $ uncurry intersect $ unzip nonbulls   pick :: Int -> [a] -> StdGen -> ([a], StdGen) {- Randomly selects items from a list without replacement. -} pick n l g = f n l g (length l - 1) [] where f 0 _ g _ ps = (ps, g) f n l g max ps = f (n - 1) (left ++ right) g' (max - 1) (picked : ps) where (i, g') = randomR (0, max) g (left, picked : right) = splitAt i l
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 "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#F.23
F#
module caesar = open System   let private cipher n s = let shift c = if Char.IsLetter c then let a = (if Char.IsLower c then 'a' else 'A') |> int (int c - a + n) % 26 + a |> char else c String.map shift s   let encrypt n = cipher n let decrypt n = cipher (26 - n)
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
#Vlang
Vlang
import math const epsilon = 1.0e-15   fn main() { mut fact := u64(1) mut e := 2.0 mut n := u64(2) for { e0 := e fact *= n n++ e += 1.0 / f64(fact) if math.abs(e - e0) < epsilon { break } } println("e = ${e:.15f}") }
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
#Wren
Wren
var epsilon = 1e-15 var fact = 1 var e = 2 var n = 2 while (true) { var e0 = e fact = fact * n n = n + 1 e = e + 1/fact if ((e - e0).abs < epsilon) break } System.print("e = %(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   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#LFE
LFE
  (defun my-func() (: io format '"I get called with NOTHING!~n"))  
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_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#Picat
Picat
  table factorial(0) = 1.   factorial(N) = N * factorial(N - 1).   catalan1(N) = factorial(2 * N) // (factorial(N + 1) * factorial(N)).   catalan2(0) = 1.   catalan2(N) = 2 * (2 * N - 1) * catalan2(N - 1) // (N + 1).   main => foreach (I in 0..14) printf("%d. %d = %d\n", I, catalan1(I), catalan2(I)) end.  
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 representation of N in base B has all equal digits. E.G. 1, 2 & 3 can not be Brazilian; there is no base B that satisfies the condition 1 < B < N-1. 4 is not Brazilian; 4 in base 2 is 100. The digits are not all the same. 5 is not Brazilian; 5 in base 2 is 101, in base 3 is 12. There is no representation where the digits are the same. 6 is not Brazilian; 6 in base 2 is 110, in base 3 is 20, in base 4 is 12. There is no representation where the digits are the same. 7 is Brazilian; 7 in base 2 is 111. There is at least one representation where the digits are all the same. 8 is Brazilian; 8 in base 3 is 22. There is at least one representation where the digits are all the same. and so on... All even integers 2P >= 8 are Brazilian because 2P = 2(P-1) + 2, which is 22 in base P-1 when P-1 > 2. That becomes true when P >= 4. More common: for all all integers R and S, where R > 1 and also S-1 > R, then R*S is Brazilian because R*S = R(S-1) + R, which is RR in base S-1 The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. All prime integers, that are brazilian, can only have the digit 1. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of 111 to base Integer(sqrt(prime number)). Must be an odd count of 1 to stay odd like primes > 2 Task Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page; the first 20 Brazilian numbers; the first 20 odd Brazilian numbers; the first 20 prime Brazilian numbers; See also OEIS:A125134 - Brazilian numbers OEIS:A257521 - Odd Brazilian numbers OEIS:A085104 - Prime Brazilian numbers
#Rust
Rust
  fn same_digits(x: u64, base: u64) -> bool { let f = x % base; let mut n = x; while n > 0 { if n % base != f { return false; } n /= base; }   true } fn is_brazilian(x: u64) -> bool { if x < 7 { return false; }; if x % 2 == 0 { return true; };   for base in 2..(x - 1) { if same_digits(x, base) { return true; } } false }   fn main() { let mut counter = 0; let limit = 20; let big_limit = 100_000; let mut big_result: u64 = 0; let mut br: Vec<u64> = Vec::new(); let mut o: Vec<u64> = Vec::new(); let mut p: Vec<u64> = Vec::new();   for x in 7.. { if is_brazilian(x) { counter += 1; if br.len() < limit { br.push(x); } if o.len() < limit && x % 2 == 1 { o.push(x); } if p.len() < limit && primes::is_prime(x) { p.push(x); } if counter == big_limit { big_result = x; break; } } } println!("First {} Brazilian numbers:", limit); println!("{:?}", br); println!("\nFirst {} odd Brazilian numbers:", limit); println!("{:?}", o); println!("\nFirst {} prime Brazilian numbers:", limit); println!("{:?}", p);   println!("\nThe {}th Brazilian number: {}", big_limit, big_result); }  
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 formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43. (Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.) Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar. This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983. THE REAL PROGRAMMER'S NATURAL HABITAT "Taped to the wall is a line-printer Snoopy calender for the year 1969." For further Kudos see task CALENDAR, where all code is to be in UPPERCASE. For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. Related task   Five weekends
#3._Output_configuration
3. Output configuration
WidestFitDimensions[ targetWidth_Integer, columnSpacings_Integer, leftRightBorderWidths:{_Integer,_Integer}, data:{__List?MatrixQ}]:= With[ {widths=Last/@Dimensions/@data, fullWidthOfRow=Total[ArrayPad[Riffle[#,columnSpacings],leftRightBorderWidths,1]]&}, With[ {fullWidthOfGrid=Max[fullWidthOfRow/@#]&}, With[ {isTooLarge=(targetWidth<fullWidthOfGrid[#])&}, With[ {bestFitGrid= NestWhile[Partition[widths,-1+Last@Dimensions@#,-1+Last@Dimensions@#,{1,1},0]&, {widths},isTooLarge[#]&,1,-1+Length@widths]}, <|"dimensions"->Dimensions@bestFitGrid,"width"->fullWidthOfGrid@bestFitGrid|>]]]];  
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 within the field. Where is not particularly important; it could be randomized, or it could be a fixed point. Particles are injected into the field, and are individually given a (typically random) motion pattern. When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree. Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
#REXX
REXX
/*REXX program animates and displays Brownian motion of dust in a field (with one seed).*/ mote = '·' /*character for a loose mote (of dust).*/ hole = ' ' /* " " an empty spot in field.*/ seedPos = 0 /*if =0, then use middle of the field.*/ /* " -1, " " a random placement.*/ /*otherwise, place the seed at seedPos.*/ /*use RANDSEED for RANDOM repeatability*/ parse arg sd sw motes tree randSeed . /*obtain optional arguments from the CL*/ if sd=='' | sd=="," then sd= 0 /*Not specified? Then use the default.*/ if sw=='' | sw=="," then sw= 0 /* " " " " " " */ if motes=='' | motes=="," then motes= '18%' /*The  % dust motes in the field, */ /* [↑] either a # ─or─ a # with a %.*/ if tree=='' | tree==mote then tree= "*" /*the character used to show the tree. */ if length(tree)==2 then tree=x2c(tree) /*tree character was specified in hex. */ if datatype(randSeed,'W') then call random ,,randSeed /*if an integer, use the seed.*/ /* [↑] set the first random number. */ if sd==0 | sw==0 then _= scrsize() /*Note: not all REXXes have SCRSIZE BIF*/ if sd==0 then sd= word(_, 1) - 2 /*adjust usable depth for the border.*/ if sw==0 then sw= word(_, 2) - 1 /* " " width " " " */ seedAt= seedPos /*assume a seed position (initial pos).*/ if seedPos== 0 then seedAt= (sw % 2) (sd % 2) /*if it's a zero, start in the middle.*/ if seedPos==-1 then seedAt= random(1, sw) random(1,sd) /*if negative, use random.*/ parse var seedAt xs ys . /*obtain the X and Y seed coördinates*/ /* [↓] if right─most ≡ '%', then use %*/ if right(motes, 1)=='%' then motes= sd * sw * strip(motes, , '%')  % 100 @.= hole /*create the Brownian field, all empty.*/ do j=1 for motes /*sprinkle a # of dust motes randomly.*/ rx= random(1, sw); ry= random(1, sd); @.rx.ry= mote end /*j*/ /* [↑] place a mote at random in field*/ /*plant a seed from which the tree will grow from*/ @.xs.ys= tree /*dust motes that affix themselves to the tree. */ call show; loX= 1; hiX= sw /*show field before we mess it up again*/ loY= 1; hiY= sd /*used to optimize the mote searching.*/ /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ soooo, this is Brownian motion.*/ do Brownian=1 until \motion; call show /*show Brownion motion until no motion.*/ minx= loX; maxX= hiX; loX= sw; hiX= 1 /*as the tree grows, the search for the*/ minY= loY; maxY= hiY; loY= sd; hiy= 1 /*dust motes gets faster due to croping*/ call BM /*invoke the Brownian movement routine.*/ if loX>1 & hiX<sw & loY>1 & hiY<sd then iterate /*Need cropping? No, then keep moving*/ call crop /*delete motes (moved off petri field).*/ end /*Brownian*/ /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ crop: do yc=-1 to sd+1 by sd+2; do xc=-1 to sw+1; @.xc.yc= hole; end /*xc*/ end /*yc*/ do xc=-1 to sw+1 by sw+2; do yc=-1 to sd+1; @.xc.yc= hole; end /*yc*/ end /*xc*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ show: 'CLS'; motion= 0; do ys=sd for sd by -1; aRow= do xs=1 for sw; aRow= aRow || @.xs.ys end /*xs*/ say aRow end /*ys*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ BM: do x =minX to maxX; xm= x - 1; xp= x + 1 /*two handy─dandy values. */ do y=minY to maxY; if @.x.y\==mote then iterate /*Not a mote: keep looking.*/ if x<loX then loX=x; if x>hiX then hiX= x /*faster than hiX=max(X,hiX)*/ if y<loY then loY=y; if y>hiY then hiY= y /* " " hiY=max(y,hiY)*/ if @.xm.y ==tree then do; @.x.y= tree; iterate; end /*there a neighbor of tree? */ if @.xp.y ==tree then do; @.x.y= tree; iterate; end /* " " " " " */ ym= y - 1 if @.x.ym ==tree then do; @.x.y= tree; iterate; end /* " " " " " */ if @.xm.ym==tree then do; @.x.y= tree; iterate; end /* " " " " " */ if @.xp.ym==tree then do; @.x.y= tree; iterate; end /* " " " " " */ yp = y + 1 if @.x.yp ==tree then do; @.x.y= tree; iterate; end /* " " " " " */ if @.xm.yp==tree then do; @.x.y= tree; iterate; end /* " " " " " */ if @.xp.yp==tree then do; @.x.y= tree; iterate; end /* " " " " " */ motion= 1 /* [↓] Brownian motion is coming. */ xb= x + random(1, 3) - 2 /* apply Brownian motion for X. */ yb= y + random(1, 3) - 2 /* " " " " Y. */ if @.xb.yb\==hole then iterate /*can the mote actually move to there ?*/ @.x.y= hole /*"empty out" the old mote position. */ @.xb.yb= mote /*move the mote (or possibly not). */ if xb<loX then loX= max(1, xb); if xb>hiX then hiX= min(sw, xb) if yb<loY then loY= max(1, yb); if yb>hiY then hiY= min(sd, yb) end /*y*/ /* [↑] limit mote's movement to field.*/ end /*x*/; return
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 randomly chosen number, and the program ends. A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number. A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position. Related tasks   Bulls and cows/Player   Guess the number   Guess the number/With Feedback   Mastermind
#Hy
Hy
(import random)   (def +size+ 4) (def +digits+ "123456789") (def +secret+ (random.sample +digits+ +size+))   (while True (while True (setv guess (list (distinct (raw-input "Enter a guess: ")))) (when (and (= (len guess) +size+) (all (map (fn [c] (in c +digits+)) guess))) (break)) (print "Malformed guess; try again")) (setv bulls 0) (setv cows 0) (for [i (range +size+)] (cond [(= (get guess i) (get +secret+ i)) (setv bulls (inc bulls))] [(in (get guess i) +secret+) (setv cows (inc cows))])) (when (= bulls +size+) (break)) (print (.format "{} bull{}, {} cows" bulls (if (= bulls 1) "" "s") cows (if (= cows 1) "" "s"))))   (print "A winner is you!")
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 "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Factor
Factor
USING: io kernel locals math sequences unicode.categories ; IN: rosetta-code.caesar-cipher   :: cipher ( n s -- s' ) [| c | c Letter? [ c letter? CHAR: a CHAR: A ? :> a c a - n + 26 mod a + ] [ c ] if ] :> shift s [ shift call ] map ;   : encrypt ( n s -- s' ) cipher ; : decrypt ( n s -- s' ) [ 26 swap - ] dip cipher ;   11 "Esp bftnv mczhy qzi ufxapo zgpc esp wlkj ozr." decrypt print 11 "The quick brown fox jumped over the lazy dog." encrypt print
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
#XPL0
XPL0
real N, E, E0, F; \index, Euler numbers, factorial [Format(1, 16); \show 16 places after decimal point N:= 1.0; E:= 1.0; F:= 1.0; loop [E0:= E; E:= E + 1.0/F; if E = E0 then quit; N:= N + 1.0; F:= F*N; ]; RlOut(0, E); CrLf(0); IntOut(0, fix(N)); Text(0, " iterations"); ]
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
#Zig
Zig
  const std = @import("std"); const math = std.math; const stdout = std.io.getStdOut().writer();   pub fn main() !void { var n: u32 = 0; var state: u2 = 0; var p0: u64 = 0; var q0: u64 = 1; var p1: u64 = 1; var q1: u64 = 0; while (true) { var a: u64 = undefined; switch (state) { 0 => { a = 2; state = 1; }, 1 => { a = 1; state = 2; }, 2 => { n += 2; a = n; state = 3; }, 3 => { a = 1; state = 1; }, } var p2: u64 = undefined; var q2: u64 = undefined; if (@mulWithOverflow(u64, a, p1, &p2) or @addWithOverflow(u64, p2, p0, &p2) or @mulWithOverflow(u64, a, q1, &q2) or @addWithOverflow(u64, q2, q0, &q2)) { break; } try stdout.print("e ~= {d:>19} / {d:>19} = ", .{p2, q2}); try dec_print(stdout, p2, q2, 36); try stdout.writeByte('\n'); p0 = p1; p1 = p2; q0 = q1; q1 = q2; } }   fn dec_print(ostream: anytype, num: u64, den: u64, prec: usize) !void { // print out integer part. try ostream.print("{}.", .{num / den});   // arithmetic with the remainders is done with u128, as the // multiply by 10 could potentially overflow a u64. // const m = @intCast(u128, den); var r = @as(u128, num) % m; var dec: usize = 0; // decimal place we're in. while (dec < prec and r > 0) { const n = 10 * r; r = n % m; dec += 1; const ch = @intCast(u8, n / m) + '0'; try ostream.writeByte(ch); } }  
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   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#Liberty_BASIC
Liberty BASIC
  'Call a function - Liberty BASIC   'First, function result could not be discarded ' that is, you cannot do "f(x)" as a separate statement   'Calling a function that requires no arguments res = f() 'brackets required   'Calling a function with a fixed number of arguments res = g(x) res = h(x,y) 'Calling a function with optional arguments 'impossible for user-defined functions 'Some build-in functions ex. INSTR and MID$ could be called with last argument omitted 'Calling a function with a variable number of arguments 'impossible 'Calling a function with named arguments 'impossible 'Using a function in statement context 'impossible (see starting notice) 'Using a function in first-class context within an expression 'impossible 'Obtaining the return value of a function res = g(x) 'Distinguishing built-in functions and user-defined functions 'I would say impossible. Though built-in functions could be EVAL'ed, 'while user-defined would not be called (tries address array instead). 'Still cannot distinguish user-defined function from array. 'Distinguishing subroutines and functions 'then defined, subroutines and functions defined with words 'SUB and FUNCTION (case incensitive) 'Then used, function used as expression (with return value), res = g(x) 'while subroutines called with special keyword CALL and without brackets call test x, y 'Stating whether arguments are passed by value or by reference 'Variables passed as arguments into functions and subs are passed "by value" by default 'parameters could be passed "by reference" if formal parameter in sub/function definition uses the "byref" specifier 'Then calling a function, you can prevent pass by reference by changing variable to expression ' like x+0, x$+"" or just (x), (x$) 'Is partial application possible and how 'impossible  
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_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#PicoLisp
PicoLisp
# Factorial (de fact (N) (if (=0 N) 1 (* N (fact (dec N))) ) )   # Directly (de catalanDir (N) (/ (fact (* 2 N)) (fact (inc N)) (fact N)) )   # Recursively (de catalanRec (N) (if (=0 N) 1 (cache '(NIL) N # Memoize (sum '((I) (* (catalanRec I) (catalanRec (- N I 1)))) (range 0 (dec N)) ) ) ) )   # Alternatively (de catalanAlt (N) (if (=0 N) 1 (*/ 2 (dec (* 2 N)) (catalanAlt (dec N)) (inc N)) ) )   # Test (for (N 0 (> 15 N) (inc N)) (tab (2 4 8 8 8) N " => " (catalanDir N) (catalanRec N) (catalanAlt N) ) )
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 representation of N in base B has all equal digits. E.G. 1, 2 & 3 can not be Brazilian; there is no base B that satisfies the condition 1 < B < N-1. 4 is not Brazilian; 4 in base 2 is 100. The digits are not all the same. 5 is not Brazilian; 5 in base 2 is 101, in base 3 is 12. There is no representation where the digits are the same. 6 is not Brazilian; 6 in base 2 is 110, in base 3 is 20, in base 4 is 12. There is no representation where the digits are the same. 7 is Brazilian; 7 in base 2 is 111. There is at least one representation where the digits are all the same. 8 is Brazilian; 8 in base 3 is 22. There is at least one representation where the digits are all the same. and so on... All even integers 2P >= 8 are Brazilian because 2P = 2(P-1) + 2, which is 22 in base P-1 when P-1 > 2. That becomes true when P >= 4. More common: for all all integers R and S, where R > 1 and also S-1 > R, then R*S is Brazilian because R*S = R(S-1) + R, which is RR in base S-1 The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. All prime integers, that are brazilian, can only have the digit 1. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of 111 to base Integer(sqrt(prime number)). Must be an odd count of 1 to stay odd like primes > 2 Task Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page; the first 20 Brazilian numbers; the first 20 odd Brazilian numbers; the first 20 prime Brazilian numbers; See also OEIS:A125134 - Brazilian numbers OEIS:A257521 - Odd Brazilian numbers OEIS:A085104 - Prime Brazilian numbers
#Scala
Scala
object BrazilianNumbers { private val PRIME_LIST = List( 2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 169, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 247, 251, 257, 263, 269, 271, 277, 281, 283, 293, 299, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 377, 379, 383, 389, 397, 401, 403, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 481, 487, 491, 499, 503, 509, 521, 523, 533, 541, 547, 557, 559, 563, 569, 571, 577, 587, 593, 599, 601, 607, 611, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 689, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 767, 769, 773, 787, 793, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 871, 877, 881, 883, 887, 907, 911, 919, 923, 929, 937, 941, 947, 949, 953, 967, 971, 977, 983, 991, 997 )   def isPrime(n: Int): Boolean = { if (n < 2) { return false }   for (prime <- PRIME_LIST) { if (n == prime) { return true } if (n % prime == 0) { return false } if (prime * prime > n) { return true } }   val bigDecimal = BigInt.int2bigInt(n) bigDecimal.isProbablePrime(10) }   def sameDigits(n: Int, b: Int): Boolean = { var n2 = n val f = n % b var done = false while (!done) { n2 /= b if (n2 > 0) { if (n2 % b != f) { return false } } else { done = true } } true }   def isBrazilian(n: Int): Boolean = { if (n < 7) { return false } if (n % 2 == 0) { return true } for (b <- 2 until n - 1) { if (sameDigits(n, b)) { return true } } false }   def main(args: Array[String]): Unit = { for (kind <- List("", "odd ", "prime ")) { var quiet = false var bigLim = 99999 var limit = 20 println(s"First $limit ${kind}Brazilian numbers:") var c = 0 var n = 7 while (c < bigLim) { if (isBrazilian(n)) { if (!quiet) { print(s"$n ") } c = c + 1 if (c == limit) { println() println() quiet = true } } if (!quiet || kind == "") { if (kind == "") { n = n + 1 } else if (kind == "odd ") { n = n + 2 } else if (kind == "prime ") { do { n = n + 2 } while (!isPrime(n)) } else { throw new AssertionError("Oops") } } } if (kind == "") { println(s"The ${bigLim + 1}th Brazilian number is: $n") println() } } } }
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 formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43. (Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.) Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar. This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983. THE REAL PROGRAMMER'S NATURAL HABITAT "Taped to the wall is a line-printer Snoopy calender for the year 1969." For further Kudos see task CALENDAR, where all code is to be in UPPERCASE. For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. Related task   Five weekends
#Nim
Nim
import times import strformat   proc printCalendar(year, nCols: int) = var rows = 12 div nCols var date = initDateTime(1, mJan, year, 0, 0, 0, utc()) if rows mod nCols != 0: inc rows var offs = getDayOfWeek(date.monthday, date.month, date.year).int var mons: array[12, array[8, string]] for m in 0..11: mons[m][0] = &"{$date.month:^21}" mons[m][1] = " Su Mo Tu We Th Fr Sa" var dim = getDaysInMonth(date.month, date.year) for d in 1..42: var day = d > offs and d <= offs + dim var str = if day: &" {d-offs:2}" else: " " mons[m][2 + (d - 1) div 7] &= str offs = (offs + dim) mod 7 date = date + months(1) var snoopyString, yearString: string formatValue(snoopyString, "[Snoopy Picture]", "^" & $(nCols * 24 + 4)) formatValue(yearString, $year, "^" & $(nCols * 24 + 4)) echo snoopyString, "\n" , yearString, "\n" for r in 0..<rows: var s: array[8, string] for c in 0..<nCols: if r * nCols + c > 11: break for i, line in mons[r * nCols + c]: s[i] &= &" {line}" for line in s: if line == "": break echo line echo ""   printCalendar(1969, 3)
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 within the field. Where is not particularly important; it could be randomized, or it could be a fixed point. Particles are injected into the field, and are individually given a (typically random) motion pattern. When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree. Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
#Ring
Ring
  # Project : Brownian tree   load "stdlib.ring" load "guilib.ring"   paint = null   new qapp { win1 = new qwidget() { setwindowtitle("") setgeometry(100,100,800,600) label1 = new qlabel(win1) { setgeometry(10,10,800,600) settext("") } new qpushbutton(win1) { setgeometry(150,500,100,30) settext("draw") setclickevent("draw()") } show() } exec() }   func draw p1 = new qpicture() color = new qcolor() { setrgb(0,0,255,255) } pen = new qpen() { setcolor(color) setwidth(1) } paint = new qpainter() { begin(p1) color = new qcolor() color.setrgb(255,0,0,255) pen = new qpen() { setcolor(color) setwidth(1)} setpen(pen)   browniantree()   endpaint() } label1 { setpicture(p1) show() } return   func browniantree() numparticles = 3000 canvas = newlist(210,210) canvas[randomf() * 100][randomf() * 200] = 1 for i = 1 to numparticles x = floor((randomf() * 199)) + 1 y = floor((randomf() * 199)) + 1 if x = 1 x = 2 ok if y = 1 y = 2 ok while canvas[x+1][y+1]+canvas[x][y+1]+canvas[x+1][y]+canvas[x-1][y-1]+canvas[x-1][y]+canvas[x][y-1] = 0 x = x + floor((randomf() * 2)) + 1 y = y + floor((randomf() * 2)) + 1 if x = 1 x = 2 ok if y = 1 y = 2 ok if x < 1 or x > 200 or y < 1 or y > 200 x = floor((randomf() * 199)) + 1 y = floor((randomf() * 199)) + 1 if x = 1 x = 2 ok if y = 1 y = 2 ok ok end canvas[x][y] = 1 paint.drawpoint(x,y) paint.drawpoint(x,y+1) paint.drawpoint(x,y+2) next   func randomf() decimals(10) str = "0." for i = 1 to 10 nr = random(9) str = str + string(nr) next return number(str)  
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 randomly chosen number, and the program ends. A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number. A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position. Related tasks   Bulls and cows/Player   Guess the number   Guess the number/With Feedback   Mastermind
#Icon_and_Unicon
Icon and Unicon
procedure main() digits := "123456789" every !digits :=: ?digits num := digits[1+:4] repeat if score(num, getGuess(num)) then break write("Good job.") end   procedure getGuess(num) repeat { writes("Enter a guess: ") guess := read() | stop("Quitter!") if *(guess ** '123456789') == *num then return guess write("Malformed guess: ",guess,". Try again.") } end   procedure score(num, guess) bulls := 0 cows := *(num ** guess) every (num[i := 1 to *num] == guess[i], bulls +:= 1, cows -:= 1) write("\t",bulls," bulls and ",cows," cows") return (bulls = *num) end
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 "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Fantom
Fantom
  class Main { static Int shift (Int char, Int key) { newChar := char + key if (char >= 'a' && char <= 'z') { if (newChar - 'a' < 0) { newChar += 26 } if (newChar - 'a' >= 26) { newChar -= 26 } } else if (char >= 'A' && char <= 'Z') { if (newChar - 'A' < 0) { newChar += 26 } if (newChar - 'A' >= 26) { newChar -= 26 } } else // not alphabetic, so keep as is { newChar = char } return newChar }   static Str shiftStr (Str msg, Int key) { res := StrBuf() msg.each { res.addChar (shift(it, key)) } return res.toStr }   static Str encode (Str msg, Int key) { return shiftStr (msg, key) }   static Str decode (Str msg, Int key) { return shiftStr (msg, -key) }   static Void main (Str[] args) { if (args.size == 2) { msg := args[0] key := Int(args[1])   echo ("$msg with key $key") echo ("Encode: ${encode(msg, key)}") echo ("Decode: ${decode(encode(msg, key), key)}") } } }  
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
#zkl
zkl
const EPSILON=1.0e-15; fact,e,n := 1, 2.0, 2; do{ e0:=e; fact*=n; n+=1; e+=1.0/fact; }while((e - e0).abs() >= EPSILON); println("e = %.15f".fmt(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
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET p=13: REM precision, or the number of terms in the Taylor expansion, from 0 to 33... 20 LET k=1: REM ...the Spectrum's maximum expressible precision is reached at p=13, while... 30 LET e=0: REM ...the factorial can't go any higher than 33 40 FOR x=1 TO p 50 LET e=e+1/k 60 LET k=k*x 70 NEXT x 80 PRINT e 90 PRINT e-EXP 1: REM the Spectrum ROM uses Chebyshev polynomials to evaluate EXP x = e^x
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   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#Lingo
Lingo
foo() -- or alternatively: call(#foo, _movie)
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_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#PL.2FI
PL/I
catalan: procedure options (main); /* 23 February 2012 */ declare (i, n) fixed;   put skip list ('How many catalan numbers do you want?'); get list (n);   do i = 0 to n; put skip list (c(i)); end;   c: procedure (n) recursive returns (fixed decimal (15)); declare n fixed;   if n <= 1 then return (1);   return ( 2*(2*n-1) * c(n-1) / (n + 1) ); end c;   end catalan;
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 representation of N in base B has all equal digits. E.G. 1, 2 & 3 can not be Brazilian; there is no base B that satisfies the condition 1 < B < N-1. 4 is not Brazilian; 4 in base 2 is 100. The digits are not all the same. 5 is not Brazilian; 5 in base 2 is 101, in base 3 is 12. There is no representation where the digits are the same. 6 is not Brazilian; 6 in base 2 is 110, in base 3 is 20, in base 4 is 12. There is no representation where the digits are the same. 7 is Brazilian; 7 in base 2 is 111. There is at least one representation where the digits are all the same. 8 is Brazilian; 8 in base 3 is 22. There is at least one representation where the digits are all the same. and so on... All even integers 2P >= 8 are Brazilian because 2P = 2(P-1) + 2, which is 22 in base P-1 when P-1 > 2. That becomes true when P >= 4. More common: for all all integers R and S, where R > 1 and also S-1 > R, then R*S is Brazilian because R*S = R(S-1) + R, which is RR in base S-1 The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. All prime integers, that are brazilian, can only have the digit 1. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of 111 to base Integer(sqrt(prime number)). Must be an odd count of 1 to stay odd like primes > 2 Task Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page; the first 20 Brazilian numbers; the first 20 odd Brazilian numbers; the first 20 prime Brazilian numbers; See also OEIS:A125134 - Brazilian numbers OEIS:A257521 - Odd Brazilian numbers OEIS:A085104 - Prime Brazilian numbers
#Sidef
Sidef
func is_Brazilian_prime(q) {   static L = Set() static M = 0   return true if L.has(q) return false if (q < M)   var N = (q<1000 ? 1000 : 2*q)   for K in (primes(3, ilog2(N+1))) { for n in (2 .. iroot(N-1, K-1)) { var p = (n**K - 1)/(n-1) L << p if (p<N && p.is_prime) } }   M = (L.max \\ 0) return L.has(q) }   func is_Brazilian(n) {   if (!n.is_prime) { n.is_square || return (n>6) var m = n.isqrt return (m>3 && (!m.is_prime || m==11)) }   is_Brazilian_prime(n) }     with (20) {|n| say "First #{n} Brazilian numbers:" say (^Inf -> lazy.grep(is_Brazilian).first(n))   say "\nFirst #{n} odd Brazilian numbers:" say (^Inf -> lazy.grep(is_Brazilian).grep{.is_odd}.first(n))   say "\nFirst #{n} prime Brazilian numbers" say (^Inf -> lazy.grep(is_Brazilian).grep{.is_prime}.first(n)) }
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 formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43. (Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.) Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar. This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983. THE REAL PROGRAMMER'S NATURAL HABITAT "Taped to the wall is a line-printer Snoopy calender for the year 1969." For further Kudos see task CALENDAR, where all code is to be in UPPERCASE. For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. Related task   Five weekends
#OCaml
OCaml
#load "unix.cma"   let lang = "en" (* language: English *)   let usage () = Printf.printf "Usage:\n%s\n" Sys.argv.(0)   let month_pattern = [ [ 0; 4; 8 ]; [ 1; 5; 9 ]; [ 2; 6; 10 ]; [ 3; 7; 11 ];   (* [ 0; 1; 2; 3; 4; 5 ]; [ 6; 7; 8; 9; 10; 11 ];   [ 0; 1; 2; 3 ]; [ 4; 5; 6; 7 ]; [ 8; 9; 10; 11 ]; *) ]   let month_langs = [ "en", [| "January"; "February"; "March"; "April"; "May"; "June"; "July"; "August"; "September"; "October"; "November"; "December"; |]; "fr", [| "janvier"; "février"; "mars"; "avril"; "mai"; "juin"; "juillet"; "août"; "septembre"; "octobre"; "novembre"; "décembre"; |]; ]   let days_lang = [ "en", [| "Monday"; "Tuesday"; "Wednesday"; "Thursday"; "Friday"; "Saturday"; "Sunday" |]; "fr", [| "lundi"; "mardi"; "mercredi"; "jeudi"; "vendredi"; "samedi"; "dimanche" |]; ]   let titles_lang = [ "en", "( Snoopy's best pic )"; "fr", "( Le meilleur profil de Snoopy )"; ]   let days = List.assoc lang days_lang let month = List.assoc lang month_langs let title = List.assoc lang titles_lang   let monday_first = 6, [| 0; 1; 2; 3; 4; 5; 6 |] let sunday_first = 0, [| 6; 0; 1; 2; 3; 4; 5 |]   let off, days_order = sunday_first let off, days_order = monday_first     let shorten n s = let len = String.length s in if n >= len then s else let n = if s.[n-1] = '\xC3' then n+1 else n in if n >= len then s else (String.sub s 0 n)     let pad size c s = let len = String.length s in let n1 = (size - len) / 2 in let n2 = size - len - n1 in String.make n1 c ^ s ^ String.make n2 c     let days = Array.map (shorten 2) days     let indices ofs = (ofs / 7, ofs mod 7)     let t_same t1 t2 = ( t1.Unix.tm_year = t2.Unix.tm_year && t1.Unix.tm_mon = t2.Unix.tm_mon && t1.Unix.tm_mday = t2.Unix.tm_mday )     let current_year () = let t = Unix.localtime (Unix.time ()) in (t.Unix.tm_year + 1900)     let make_month t year month = let empty_day = 0 in let m = Array.make_matrix 6 7 empty_day in let ofs = ref 0 in for day = 1 to 31 do let tm = { t with Unix.tm_year = year - 1900; Unix.tm_mon = month; Unix.tm_mday = day; } in let _, this = Unix.mktime tm in if !ofs = 0 then ofs := (this.Unix.tm_wday + off) mod 7; if t_same this tm then let i, j = indices !ofs in m.(i).(j) <- day; incr ofs; done; (m)     let cal ~year = let empty = [| [| |] |] in let months = Array.make 12 empty in let t = Unix.gmtime 0.0 in for mon = 0 to 11 do months.(mon) <- make_month t year mon; done; (months)     let print_month_label mp = List.iter (fun i -> let mon = pad 20 ' ' month.(i) in Printf.printf " %s " mon ) mp; print_newline ()     let print_day_label mp = List.iter (fun _ -> Array.iter (fun i -> Printf.printf " %s" days.(i) ) days_order ; print_string " " ) mp; print_newline ()     let print_mon m mp = print_month_label mp; print_day_label mp; for w = 0 to pred 6 do print_string begin String.concat " " begin List.map (fun i -> let b = Buffer.create 132 in for d = 0 to pred 7 do match m.(i).(w).(d) with | 0 -> Buffer.add_string b " " | d -> Printf.kprintf (Buffer.add_string b) " %2d" d done; (Buffer.contents b) ) mp end end ; print_string "\n" done     let print_cal ~y:m = List.iter (fun mon_row -> print_mon m mon_row ) month_pattern     let print_header lbl = let n = List.length (List.hd month_pattern) in let year_lbl = pad (23*n-7) ' ' lbl in Printf.printf " %s\n" year_lbl     let print_calendar ~year = print_header title; print_header (string_of_int year); print_cal (cal ~year)     let () = let args = List.tl (Array.to_list Sys.argv) in match args with | [] -> let year = current_year () in print_calendar ~year   | ["--year"; _year] -> let year = int_of_string _year in print_calendar ~year   | _ -> usage ()
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 within the field. Where is not particularly important; it could be randomized, or it could be a fixed point. Particles are injected into the field, and are individually given a (typically random) motion pattern. When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree. Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
#Ruby
Ruby
require 'rubygems' require 'RMagick'   NUM_PARTICLES = 1000 SIZE = 800   def draw_brownian_tree world # set the seed world[rand SIZE][rand SIZE] = 1   NUM_PARTICLES.times do # set particle's position px = rand SIZE py = rand SIZE   loop do # randomly choose a direction dx = rand(3) - 1 dy = rand(3) - 1   if dx + px < 0 or dx + px >= SIZE or dy + py < 0 or dy + py >= SIZE # plop the particle into some other random location px = rand SIZE py = rand SIZE elsif world[py + dy][px + dx] != 0 # bumped into something world[py][px] = 1 break else py += dy px += dx end end end end   world = Array.new(SIZE) { Array.new(SIZE, 0) } srand Time.now.to_i   draw_brownian_tree world   img = Magick::Image.new(SIZE, SIZE) do self.background_color = "black" end   draw = Magick::Draw.new draw.fill "white"   world.each_with_index do |row, y| row.each_with_index do |colour, x| draw.point x, y if colour != 0 end end   draw.draw img img.write "brownian_tree.bmp"
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 randomly chosen number, and the program ends. A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number. A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position. Related tasks   Bulls and cows/Player   Guess the number   Guess the number/With Feedback   Mastermind
#J
J
require 'misc'   plural=: conjunction define (":m),' ',n,'s'#~1~:m )   bullcow=:monad define number=. 1+4?9 whilst. -.guess-:number do. guess=. 0 "."0 prompt 'Guess my number: ' if. (4~:#guess)+.(4~:#~.guess)+.0 e.guess e.1+i.9 do. if. 0=#guess do. smoutput 'Giving up.' return. end. smoutput 'Guesses must be four different non-zero digits' continue. end. bulls=. +/guess=number cows=. (+/guess e.number)-bulls smoutput bulls plural 'bull',' and ',cows plural 'cow','.' end. smoutput 'you win' )
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 "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Fhidwfe
Fhidwfe
  lowers = ['a','z'] uppers = ['A','Z'] function void caesar_encode(message:ptr key:uint) { len = strlen$ message for uint [0u,len) with index { temp = deref_ubyte$ + message index if in temp lowers { temp = + temp key// shift lowercase letters if > temp 'z' { temp = - temp 26ub } ; } { if in temp uppers { temp = + temp key// shift uppercase letters if > temp 'Z' { temp = - temp 26ub } ; } ;//don't shift other characters } put_ubyte$ + message index temp } } function void caesar_decode(message:ptr key:uint) { caesar_encode$ message - 26u key }   key = 1u response = malloc$ 256u puts$ "plaintext: " getline$ response caesar_encode$ response key puts$ "cyphertext: " puts$ response putln$ caesar_decode$ response key puts$ "decoded: " puts$ response free$ response free$ lowers // ranges are objects and must be freed free$ uppers   //this compiles with only 6 warnings!  
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   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#Little
Little
// Calling a function that requires no arguments void foo() {puts("Calling a function with no arguments");} foo();   // Calling a function with a fixed number of arguments abs(-36);   // Calling a function with optional arguments puts(nonewline: "nonewline is an optional argument"); puts("\n");   // Calling a function with a variable number of arguments void var_arg_func(...args) { puts(length(args)); } var_arg_func(1, 2); var_arg_func(1, 2, 3);   // Obtaining the return value of a function int s = clock("seconds"); //current time in seconds // Calling a function with named arguments // format is a named argument in Clock_format int str = Clock_format(s, format: "%B"); puts(str);   // Stating whether arguments are passed by value or by reference void f(int a, int &b) { a++; b++; } { int a = 0; int b = 0;   f(a, &b); puts (a); puts (b); }
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_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#Plain_TeX
Plain TeX
\newcount\n \newcount\r \newcount\x \newcount\ii   \def\catalan#1{% \n#1\advance\n by1\ii1\r1% \loop{% \x\ii% \multiply\x by 2 \advance\x by -1 \multiply\x by 2% \global\multiply\r by\x% \global\advance\ii by1% \global\divide\r by\ii% } \ifnum\number\ii<\n\repeat% \the\r }   \rightskip=0pt plus1fil\parindent=0pt \loop{${\rm Catalan}(\the\x) = \catalan{\the\x}$\hfil\break}% \advance\x by 1\ifnum\x<15\repeat   \bye
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 representation of N in base B has all equal digits. E.G. 1, 2 & 3 can not be Brazilian; there is no base B that satisfies the condition 1 < B < N-1. 4 is not Brazilian; 4 in base 2 is 100. The digits are not all the same. 5 is not Brazilian; 5 in base 2 is 101, in base 3 is 12. There is no representation where the digits are the same. 6 is not Brazilian; 6 in base 2 is 110, in base 3 is 20, in base 4 is 12. There is no representation where the digits are the same. 7 is Brazilian; 7 in base 2 is 111. There is at least one representation where the digits are all the same. 8 is Brazilian; 8 in base 3 is 22. There is at least one representation where the digits are all the same. and so on... All even integers 2P >= 8 are Brazilian because 2P = 2(P-1) + 2, which is 22 in base P-1 when P-1 > 2. That becomes true when P >= 4. More common: for all all integers R and S, where R > 1 and also S-1 > R, then R*S is Brazilian because R*S = R(S-1) + R, which is RR in base S-1 The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. All prime integers, that are brazilian, can only have the digit 1. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of 111 to base Integer(sqrt(prime number)). Must be an odd count of 1 to stay odd like primes > 2 Task Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page; the first 20 Brazilian numbers; the first 20 odd Brazilian numbers; the first 20 prime Brazilian numbers; See also OEIS:A125134 - Brazilian numbers OEIS:A257521 - Odd Brazilian numbers OEIS:A085104 - Prime Brazilian numbers
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function sameDigits(ByVal n As Integer, ByVal b As Integer) As Boolean Dim f As Integer = n Mod b : n \= b : While n > 0 If n Mod b <> f Then Return False Else n \= b End While : Return True End Function   Function isBrazilian(ByVal n As Integer) As Boolean If n < 7 Then Return False If n Mod 2 = 0 Then Return True For b As Integer = 2 To n - 2 If sameDigits(n, b) Then Return True Next : Return False End Function   Function isPrime(ByVal n As Integer) As Boolean If n < 2 Then Return False If n Mod 2 = 0 Then Return n = 2 If n Mod 3 = 0 Then Return n = 3 Dim d As Integer = 5 While d * d <= n If n Mod d = 0 Then Return False Else d += 2 If n Mod d = 0 Then Return False Else d += 4 End While : Return True End Function   Sub Main(args As String()) For Each kind As String In {" ", " odd ", " prime "} Console.WriteLine("First 20{0}Brazilian numbers:", kind) Dim Limit As Integer = 20, n As Integer = 7 Do If isBrazilian(n) Then Console.Write("{0} ", n) : Limit -= 1 Select Case kind Case " " : n += 1 Case " odd " : n += 2 Case " prime " : Do : n += 2 : Loop Until isPrime(n) End Select Loop While Limit > 0 Console.Write(vbLf & vbLf) Next End Sub   End Module
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 formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43. (Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.) Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar. This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983. THE REAL PROGRAMMER'S NATURAL HABITAT "Taped to the wall is a line-printer Snoopy calender for the year 1969." For further Kudos see task CALENDAR, where all code is to be in UPPERCASE. For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. Related task   Five weekends
#Perl
Perl
#!/usr/bin/perl -l   use strict; # https://rosettacode.org/wiki/Calendar use warnings; use Time::Local;   my $year = shift // 1969; my $width = shift // 80; my $columns = int +($width + 2) / 22 or die "width too short at $width"; print map { center($_, $width), "\n" } '<reserved for snoopy>', $year; my @months = qw( January February March April May June July August September October November December ); my @days = qw( 31 28 31 30 31 30 31 31 30 31 30 31 ); (gmtime 86400 + timegm 1,1,1,28,1,$year)[3] == 29 and $days[1]++; my @blocks = map # block per month { my $m = center($months[$_], 20) . "\nSu Mo Tu We Th Fr Sa\n" . "00 00 00 00 00 00 00\n" x 6; $m =~ s/00/ / for 1 .. (gmtime timegm 1,1,1,1,$_,$year )[6]; # day of week $m =~ s/00/ center($_, 2) /e for 1 .. $days[$_]; $m =~ s/00/ /g; [ split /\n/, $m ] } 0 .. 11; while( my @row = splice @blocks, 0, $columns ) # print by rows of months { print center(join(' ', map shift @$_, @row), $width) for 1 .. @{$row[0]}; }   sub center { my ($string, $w) = @_; sprintf "%${w}s", $string . ' ' x ($w - length($string) >> 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 within the field. Where is not particularly important; it could be randomized, or it could be a fixed point. Particles are injected into the field, and are individually given a (typically random) motion pattern. When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree. Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
#Run_BASIC
Run BASIC
numParticles = 3000 dim canvas(201,201) graphic #g, 200,200 #g fill("blue") canvas(rnd(1) * 100 , rnd(1) * 200) = 1 'start point for i = 1 To numParticles x = (rnd(1) * 199) + 1 y = (rnd(1) * 199) + 1 while canvas(x+1, y+1)+canvas(x, y+1)+canvas(x+1, y)+canvas(x-1, y-1)+canvas(x-1, y)+canvas(x, y-1) = 0 x = x + (rnd(1)* 2) + 1 y = y + (rnd(1)* 2) + 1 If x < 1 Or x > 200 Or y < 1 Or y > 200 then x = (rnd(1) * 199) + 1 y = (rnd(1) * 199) + 1 end if wend canvas(x,y) = 1 #g "color green ; set "; x; " "; y next i render #g #g "flush"
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 randomly chosen number, and the program ends. A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number. A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position. Related tasks   Bulls and cows/Player   Guess the number   Guess the number/With Feedback   Mastermind
#Java
Java
import java.util.InputMismatchException; import java.util.Random; import java.util.Scanner;   public class BullsAndCows{ public static void main(String[] args){ Random gen= new Random(); int target; while(hasDupes(target= (gen.nextInt(9000) + 1000))); String targetStr = target +""; boolean guessed = false; Scanner input = new Scanner(System.in); int guesses = 0; do{ int bulls = 0; int cows = 0; System.out.print("Guess a 4-digit number with no duplicate digits: "); int guess; try{ guess = input.nextInt(); if(hasDupes(guess) || guess < 1000) continue; }catch(InputMismatchException e){ continue; } guesses++; String guessStr = guess + ""; for(int i= 0;i < 4;i++){ if(guessStr.charAt(i) == targetStr.charAt(i)){ bulls++; }else if(targetStr.contains(guessStr.charAt(i)+"")){ cows++; } } if(bulls == 4){ guessed = true; }else{ System.out.println(cows+" Cows and "+bulls+" Bulls."); } }while(!guessed); System.out.println("You won after "+guesses+" guesses!"); }   public static boolean hasDupes(int num){ boolean[] digs = new boolean[10]; while(num > 0){ if(digs[num%10]) return true; digs[num%10] = true; num/= 10; } return false; } }
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 "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Forth
Forth
: ceasar ( c n -- c ) over 32 or [char] a - dup 0 26 within if over + 25 > if 26 - then + else 2drop then ;   : ceasar-string ( n str len -- ) over + swap do i c@ over ceasar i c! loop drop ;   : ceasar-inverse ( n -- 'n ) 26 swap - 26 mod ;   2variable test s" The five boxing wizards jump quickly!" test 2!   3 test 2@ ceasar-string test 2@ cr type   3 ceasar-inverse test 2@ ceasar-string test 2@ cr type
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   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#Lua
Lua
-- Lua functions accept any number of arguments; missing arguments are nil-padded, extras are dropped. function fixed (a, b, c) print(a, b, c) end fixed() --> nil nil nil fixed(1, 2, 3, 4, 5) --> 1 2 3   -- True vararg functions include a trailing ... parameter, which captures all additional arguments as a group of values. function vararg (...) print(...) end vararg(1, 2, 3, 4, 5) -- 1 2 3 4 5   -- Lua also allows dropping the parentheses if table or string literals are used as the sole argument print "some string" print { foo = "bar" } -- also serves as a form of named arguments   -- First-class functions in expression context print(("this is backwards uppercase"):gsub("%w+", function (s) return s:upper():reverse() end))   -- Functions can return multiple values (including none), which can be counted via select() local iter, obj, start = ipairs { 1, 2, 3 } print(select("#", (function () end)())) --> 0 print(select("#", unpack { 1, 2, 3, 4 })) --> 4   -- Partial application function prefix (pre) return function (suf) return pre .. suf end end   local prefixed = prefix "foo" print(prefixed "bar", prefixed "baz", prefixed "quux")   -- nil, booleans, and numbers are always passed by value. Everything else is always passed by reference. -- There is no separate notion of subroutines -- Built-in functions are not easily distinguishable from user-defined functions  
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_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#PowerShell
PowerShell
  function Catalan([uint64]$m) { function fact([bigint]$n) { if($n -lt 2) {[bigint]::one} else{2..$n | foreach -Begin {$prod = [bigint]::one} -Process {$prod = [bigint]::Multiply($prod,$_)} -End {$prod}} } $fact = fact $m $fact1 = [bigint]::Multiply($m+1,$fact) [bigint]::divide((fact (2*$m)), [bigint]::Multiply($fact,$fact1)) } 0..15 | foreach {"catalan($_): $(catalan $_)"}  
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 representation of N in base B has all equal digits. E.G. 1, 2 & 3 can not be Brazilian; there is no base B that satisfies the condition 1 < B < N-1. 4 is not Brazilian; 4 in base 2 is 100. The digits are not all the same. 5 is not Brazilian; 5 in base 2 is 101, in base 3 is 12. There is no representation where the digits are the same. 6 is not Brazilian; 6 in base 2 is 110, in base 3 is 20, in base 4 is 12. There is no representation where the digits are the same. 7 is Brazilian; 7 in base 2 is 111. There is at least one representation where the digits are all the same. 8 is Brazilian; 8 in base 3 is 22. There is at least one representation where the digits are all the same. and so on... All even integers 2P >= 8 are Brazilian because 2P = 2(P-1) + 2, which is 22 in base P-1 when P-1 > 2. That becomes true when P >= 4. More common: for all all integers R and S, where R > 1 and also S-1 > R, then R*S is Brazilian because R*S = R(S-1) + R, which is RR in base S-1 The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. All prime integers, that are brazilian, can only have the digit 1. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of 111 to base Integer(sqrt(prime number)). Must be an odd count of 1 to stay odd like primes > 2 Task Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page; the first 20 Brazilian numbers; the first 20 odd Brazilian numbers; the first 20 prime Brazilian numbers; See also OEIS:A125134 - Brazilian numbers OEIS:A257521 - Odd Brazilian numbers OEIS:A085104 - Prime Brazilian numbers
#Vlang
Vlang
fn same_digits(nn int, b int) bool { f := nn % b mut n := nn/b for n > 0 { if n%b != f { return false } n /= b } return true }   fn is_brazilian(n int) bool { if n < 7 { return false } if n%2 == 0 && n >= 8 { return true } for b in 2..n-1 { if same_digits(n, b) { return true } } return false }   fn is_prime(n int) bool { match true { n < 2 { return false } n%2 == 0 { return n == 2 } n%3 == 0 { return n == 3 } else { mut d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } } }   fn main() { kinds := [" ", " odd ", " prime "] for kind in kinds { println("First 20${kind}Brazilian numbers:") mut c := 0 mut n := 7 for { if is_brazilian(n) { print("$n ") c++ if c == 20 { println("\n") break } } match kind { " " { n++ } " odd " { n += 2 } " prime "{ for { n += 2 if is_prime(n) { break } } } else{} } } }   mut n := 7 for c := 0; c < 100000; n++ { if is_brazilian(n) { c++ } } println("The 100,000th Brazilian number: ${n-1}") }
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 formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43. (Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.) Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar. This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983. THE REAL PROGRAMMER'S NATURAL HABITAT "Taped to the wall is a line-printer Snoopy calender for the year 1969." For further Kudos see task CALENDAR, where all code is to be in UPPERCASE. For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. Related task   Five weekends
#Phix
Phix
with javascript_semantics constant year = 1969 include builtins\timedate.e function centre(string s, integer width) integer gap = width-length(s), left = floor(gap/2), right = gap-left return repeat(' ',left) & s & repeat(' ',right) end function function one_month(integer year, integer month, bool sun_to_sat) string weekdays = iff(sun_to_sat?"Su Mo Tu We Th Fr Sa" :"Mo Tu We Th Fr Sa Su"), line = repeat(' ',20) sequence ldm = adjust_timedate(iff(month=12?{year+1,1,1,0,0,0,0,0} :{year,month+1,1,0,0,0,0,0}), timedelta(days:=-1)), res = {centre(format_timedate(ldm,"Mmmm"),20),weekdays} integer dow = day_of_week(year,month,1) if sun_to_sat then dow = remainder(dow,7)+1 end if integer lastday = ldm[DT_DAY], p = dow*3-2 for d=1 to lastday do line[p..p+1] = sprintf("%2d",d) p += 3 if dow=7 or d=lastday then res = append(res,line) line = repeat(' ',20) dow = 1 p = 1 else dow += 1 end if end for return res end function procedure print_calendar(integer year, width, bool sun_to_sat=false) sequence months = repeat(0,12) integer wide = floor((width+2)/22) printf(1,centre("[Spot Reserved For Snoopy]",width)&"\n") printf(1,centre(sprintf("%d",year),width)&"\n") for month=1 to 12 do months[month] = one_month(year,month,sun_to_sat) end for for month=1 to 12 by wide do for k=1 to 9 do -- (more than enough) integer any = 0 string line = "" for j=0 to wide-1 do if length(line) then line &= " " end if if k>length(months[month+j]) then line &= repeat(' ',20) else line &= months[month+j][k] any = 1 end if end for if any=0 then exit end if printf(1,centre(line,width)&"\n") end for end for end procedure print_calendar(year,80) printf(1,join(repeat("1234567890",8),"")&"\n") print_calendar(year,132,true) printf(1,join(repeat("1234567890",13),"")&"12\n")
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 within the field. Where is not particularly important; it could be randomized, or it could be a fixed point. Particles are injected into the field, and are individually given a (typically random) motion pattern. When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree. Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
#Rust
Rust
  extern crate image; extern crate rand;   use image::ColorType;   use std::cmp::{min, max}; use std::env; use std::path::Path; use std::process; use rand::Rng;   fn help() { println!("Usage: brownian_tree <output_path> <mote_count> <edge_length>"); }   fn main() { let args: Vec<String> = env::args().collect(); let mut output_path = Path::new("out.png"); let mut mote_count: u32 = 10000; let mut width: usize = 512; let mut height: usize = 512;   match args.len() { 1 => {} 4 => { output_path = Path::new(&args[1]); mote_count = args[2].parse::<u32>().unwrap(); width = args[3].parse::<usize>().unwrap(); height = width; } _ => { help(); process::exit(0); } }   assert!(width >= 2);   // Base 1d array let mut field_raw = vec![0u8; width * height]; populate_tree(&mut field_raw, width, height, mote_count);   // Balance image for 8-bit grayscale let our_max = field_raw.iter().fold(0u8, |champ, e| max(champ, *e)); let fudge = std::u8::MAX / our_max; let balanced: Vec<u8> = field_raw.iter().map(|e| e * fudge).collect();   match image::save_buffer(output_path, &balanced, width as u32, height as u32, ColorType::L8) { Err(e) => println!("Error writing output image:\n{}", e), Ok(_) => println!("Output written to:\n{}", output_path.to_str().unwrap()), } }     fn populate_tree(raw: &mut Vec<u8>, width: usize, height: usize, mc: u32) { // Vector of 'width' elements slices let mut field_base: Vec<_> = raw.as_mut_slice().chunks_mut(width).collect(); // Addressable 2d vector let field: &mut [&mut [u8]] = field_base.as_mut_slice();   // Seed mote field[width / 2][height / 2] = 1;   let mut rng = rand::thread_rng();   for i in 0..mc { if i % 100 == 0 { println!("{}", i) }   let mut x=rng.gen_range(1usize..width-1); let mut y=rng.gen_range(1usize..height-1);   // Increment field value when motes spawn on top of the structure if field[x][y] > 0 { field[x][y] = min(field[x][y] as u32 + 1, std::u8::MAX as u32) as u8; continue; }   loop { let contacts = field[x - 1][y - 1] + field[x][y - 1] + field[x + 1][y - 1] + field[x - 1][y] + field[x + 1][y] + field[x - 1][y + 1] + field[x][y + 1] + field[x + 1][y + 1];   if contacts > 0 { field[x][y] = 1; break; } else { let xw = rng.gen_range(-1..2) + x as i32; let yw = rng.gen_range(-1..2) + y as i32; if xw < 1 || xw >= (width as i32 - 1) || yw < 1 || yw >= (height as i32 - 1) { break; } x = xw as usize; y = yw as usize; } } } }
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 randomly chosen number, and the program ends. A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number. A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position. Related tasks   Bulls and cows/Player   Guess the number   Guess the number/With Feedback   Mastermind
#JavaScript
JavaScript
#!/usr/bin/env js   function main() { var len = 4; playBullsAndCows(len); }   function playBullsAndCows(len) { var num = pickNum(len); // print('The secret number is:\n ' + num.join('\n ')); showInstructions(len); var nGuesses = 0; while (true) { nGuesses++; var guess = getGuess(nGuesses, len); var census = countBovine(num, guess); showScore(census.bulls, census.cows); if (census.bulls == len) { showFinalResult(nGuesses); return; } } }   function showScore(nBulls, nCows) { print(' Bulls: ' + nBulls + ', cows: ' + nCows); }   function showFinalResult(guesses) { print('You win!!! Guesses needed: ' + guesses); }   function countBovine(num, guess) { var count = {bulls:0, cows:0}; var g = guess.join(''); for (var i = 0; i < num.length; i++) { var digPresent = g.search(num[i]) != -1; if (num[i] == guess[i]) count.bulls++; else if (digPresent) count.cows++; } return count; }   function getGuess(nGuesses, len) { while (true) { putstr('Your guess #' + nGuesses + ': '); var guess = readline(); guess = String(parseInt(guess)).split(''); if (guess.length != len) { print(' You must enter a ' + len + ' digit number.'); continue; } if (hasDups(guess)) { print(' No digits can be duplicated.'); continue; } return guess; } }   function hasDups(ary) { var t = ary.concat().sort(); for (var i = 1; i < t.length; i++) { if (t[i] == t[i-1]) return true; } return false; }   function showInstructions(len) { print(); print('Bulls and Cows Game'); print('-------------------'); print(' You must guess the ' + len + ' digit number I am thinking of.'); print(' The number is composed of the digits 1-9.'); print(' No digit appears more than once.'); print(' After each of your guesses, I will tell you:'); print(' The number of bulls (digits in right place)'); print(' The number of cows (correct digits, but in the wrong place)'); print(); }   function pickNum(len) { var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]; nums.sort(function(){return Math.random() - 0.5}); return nums.slice(0, len); }   main();  
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 "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Fortran
Fortran
program Caesar_Cipher implicit none   integer, parameter :: key = 3 character(43) :: message = "The five boxing wizards jump quickly"   write(*, "(2a)") "Original message = ", message call encrypt(message) write(*, "(2a)") "Encrypted message = ", message call decrypt(message) write(*, "(2a)") "Decrypted message = ", message   contains   subroutine encrypt(text) character(*), intent(inout) :: text integer :: i   do i = 1, len(text) select case(text(i:i)) case ('A':'Z') text(i:i) = achar(modulo(iachar(text(i:i)) - 65 + key, 26) + 65) case ('a':'z') text(i:i) = achar(modulo(iachar(text(i:i)) - 97 + key, 26) + 97) end select end do end subroutine   subroutine decrypt(text) character(*), intent(inout) :: text integer :: i   do i = 1, len(text) select case(text(i:i)) case ('A':'Z') text(i:i) = achar(modulo(iachar(text(i:i)) - 65 - key, 26) + 65) case ('a':'z') text(i:i) = achar(modulo(iachar(text(i:i)) - 97 - key, 26) + 97) end select end do end subroutine   end program Caesar_Cipher
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   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#Luck
Luck
/* Calling a function that requires no arguments */ f();;   /* Calling a function with a fixed number of arguments */ f(1,2);;   /* Calling a function with optional arguments Note: defining the function is cumbersome but will get easier in future versions. */ f(1,2,new {default with x=3, y=4});;   /* Calling a function with a variable number of arguments */ printf("%d %d %d %d":char*,2,3,4,5);;   /* Calling a function with named arguments Note: may get syntax sugar in future versions */ f(1,2,new {default with x=3, y=4});;   /* Using a function in statement context (what?) */ f();f();f();;   /* Using a function in first-class context within an expression */ [1,2,3].map(string);;   /* Obtaining the return value of a function */ let x:int = f();;   /* Distinguishing built-in functions and user-defined functions */ /* Builtin function i.e. custom calling convention: */ (@ binop "==" l r);; /* User defined function i.e. normal function */ f(l)(r);;   /* Distinguishing subroutines and functions: both are supported, but compiler is not aware of difference */ sub();; fun();;   /* Stating whether arguments are passed by value or by reference */ f(value);; /* by value */ f(&value);; /* by pointer reference */ f(ref(value));; /* by managed reference */   /* Is partial application possible and how */ tasty_curry(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)(q)(r)(s)(t)(u)(v)(w)(x)(y)(z);;
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_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#Prolog
Prolog
catalan(N) :- length(L1, N), L = [1 | L1], init(1,1,L1), numlist(0, N, NL), maplist(my_write, NL, L).     init(_, _, []).   init(V, N, [H | T]) :- N1 is N+1, H is 2 * (2 * N - 1) * V / N1, init(H, N1, T).   my_write(N, V) :- format('~w : ~w~n', [N, V]).
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 representation of N in base B has all equal digits. E.G. 1, 2 & 3 can not be Brazilian; there is no base B that satisfies the condition 1 < B < N-1. 4 is not Brazilian; 4 in base 2 is 100. The digits are not all the same. 5 is not Brazilian; 5 in base 2 is 101, in base 3 is 12. There is no representation where the digits are the same. 6 is not Brazilian; 6 in base 2 is 110, in base 3 is 20, in base 4 is 12. There is no representation where the digits are the same. 7 is Brazilian; 7 in base 2 is 111. There is at least one representation where the digits are all the same. 8 is Brazilian; 8 in base 3 is 22. There is at least one representation where the digits are all the same. and so on... All even integers 2P >= 8 are Brazilian because 2P = 2(P-1) + 2, which is 22 in base P-1 when P-1 > 2. That becomes true when P >= 4. More common: for all all integers R and S, where R > 1 and also S-1 > R, then R*S is Brazilian because R*S = R(S-1) + R, which is RR in base S-1 The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. All prime integers, that are brazilian, can only have the digit 1. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of 111 to base Integer(sqrt(prime number)). Must be an odd count of 1 to stay odd like primes > 2 Task Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page; the first 20 Brazilian numbers; the first 20 odd Brazilian numbers; the first 20 prime Brazilian numbers; See also OEIS:A125134 - Brazilian numbers OEIS:A257521 - Odd Brazilian numbers OEIS:A085104 - Prime Brazilian numbers
#Wren
Wren
import "/math" for Int   var sameDigits = Fn.new { |n, b| var f = n % b n = (n/b).floor while (n > 0) { if (n%b != f) return false n = (n/b).floor } return true }   var isBrazilian = Fn.new { |n| if (n < 7) return false if (n%2 == 0 && n >= 8) return true for (b in 2...n-1) { if (sameDigits.call(n, b)) return true } return false }   for (kind in [" ", " odd ", " prime "]) { System.print("First 20%(kind)Brazilian numbers:") var c = 0 var n = 7 while (true) { if (isBrazilian.call(n)) { System.write("%(n) ") c = c + 1 if (c == 20) { System.print("\n") break } } if (kind == " ") { n = n + 1 } else if (kind == " odd ") { n = n + 2 } else { while (true) { n = n + 2 if (Int.isPrime(n)) break } } } }   var c = 0 var n = 7 while (c < 1e5) { if (isBrazilian.call(n)) c = c + 1 n = n + 1 } System.print("The 100,000th Brazilian number: %(n-1)")
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 formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43. (Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.) Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar. This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983. THE REAL PROGRAMMER'S NATURAL HABITAT "Taped to the wall is a line-printer Snoopy calender for the year 1969." For further Kudos see task CALENDAR, where all code is to be in UPPERCASE. For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. Related task   Five weekends
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   32 var space   def bksp /# -- backspace #/ 8 tochar print enddef   def floor .5 + int enddef   def center tostr align enddef   def startday /# year -- day of the week of january 1 #/ 1 - >ps tps 365 * tps 4 / floor + tps 100 / floor - ps> 400 / floor + 7 mod enddef   def bisiesto? /# year -- true if leap #/ dup 4 mod not over 100 mod and swap 400 mod not or enddef   def snoopy 0 tcolor 15 bcolor "snoopy.txt" "r" fopen var f   true while f fgets dup -1 == if drop f fclose false else print true endif endwhile   15 tcolor 0 bcolor enddef   ( "JANUARY" "FEBRUARY" "MARCH" "APRIL" "MAY" "JUNE" "JULY" "AUGUST" "SEPTEMBER" "OCTOBER" "NOVEMBER" "DECEMBER" ) var months "MO TU WE TH FR SA SU" var daysTitle ( 31 28 31 30 31 30 31 31 30 31 30 31 ) var daysPerMonth daysTitle len nip var monthwidth   def makeMonth var days >ps monthwidth center daysTitle 2 tolist   1 ps> - 1 + >ps   true while ( ) 7 for drop tps 1 < tps days > or if " " else tps endif 2 align 0 put ps> 1 + >ps endfor 0 put len 8 < endwhile ps> drop enddef   def print_cal >ps tps bisiesto? if daysPerMonth 29 2 set var daysPerMonth endif 5 space over repeat var spaces   snoopy   3 monthwidth * swap 2 * + "--- " tps tostr " ---" chain chain swap center ? nl   ps> startday var inicio   ( )   12 for >ps months tps get nip inicio daysPerMonth ps> get nip >ps tps makeMonth 0 put inicio ps> + 7 mod var inicio endfor   ( 0 3 ) for var i 8 for var k 3 for var j i 3 * j + get k get list? if 10 tcolor len for get print " " print endfor drop bksp else 11 tcolor print endif drop spaces print endfor nl endfor nl endfor drop enddef   2020 print_cal
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 within the field. Where is not particularly important; it could be randomized, or it could be a fixed point. Particles are injected into the field, and are individually given a (typically random) motion pattern. When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree. Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
#Scala
Scala
import java.awt.Graphics import java.awt.image.BufferedImage   import javax.swing.JFrame   import scala.collection.mutable.ListBuffer   object BrownianTree extends App { val rand = scala.util.Random   class BrownianTree extends JFrame("Brownian Tree") with Runnable { setBounds(100, 100, 400, 300) val img = new BufferedImage(getWidth, getHeight, BufferedImage.TYPE_INT_RGB)   override def paint(g: Graphics): Unit = g.drawImage(img, 0, 0, this)   override def run(): Unit = { class Particle(var x: Int = rand.nextInt(img.getWidth), var y: Int = rand.nextInt(img.getHeight)) {   /* returns false if either out of bounds or collided with tree */ def move: Boolean = { val (dx, dy) = (rand.nextInt(3) - 1, rand.nextInt(3) - 1) if ((x + dx < 0) || (y + dy < 0) || (y + dy >= img.getHeight) || (x + dx >= img.getWidth)) false else { x += dx y += dy if ((img.getRGB(x, y) & 0xff00) == 0xff00) { img.setRGB(x - dx, y - dy, 0xff00) false } else true } } }   var particles = ListBuffer.fill(20000)(new Particle) while (particles.nonEmpty) { particles = particles.filter(_.move) repaint() } }   setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE) img.setRGB(img.getWidth / 2, img.getHeight / 2, 0xff00) setVisible(true) }   new Thread(new BrownianTree).start() }
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 randomly chosen number, and the program ends. A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number. A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position. Related tasks   Bulls and cows/Player   Guess the number   Guess the number/With Feedback   Mastermind
#Julia
Julia
function cowsbulls() print("Welcome to Cows & Bulls! I've picked a number with unique digits between 1 and 9, go ahead and type your guess.\n You get one bull for every right number in the right position.\n You get one cow for every right number, but in the wrong position.\n Enter 'n' to pick a new number and 'q' to quit.\n>") function new_number() s = [1:9] n = "" for i = 9:-1:6 n *= string(delete!(s,rand(1:i))) end return n end answer = new_number() while true input = chomp(readline(STDIN)) input == "q" && break if input == "n" answer = new_number() print("\nI've picked a new number, go ahead and guess\n>") continue end !ismatch(r"^[1-9]{4}$",input) && (print("Invalid guess: Please enter a 4-digit number\n>"); continue) if input == answer print("\nYou're right! Good guessing!\nEnter 'n' for a new number or 'q' to quit\n>") else bulls = sum(answer.data .== input.data) cows = sum([answer[x] != input[x] && contains(input.data,answer[x]) for x = 1:4]) print("\nNot quite! Your guess is worth:\n$bulls Bulls\n$cows Cows\nPlease guess again\n\n>") end end end
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 "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Sub Encrypt(s As String, key As Integer) Dim c As Integer For i As Integer = 0 To Len(s) Select Case As Const s[i] Case 65 To 90 c = s[i] + key If c > 90 Then c -= 26 s[i] = c Case 97 To 122 c = s[i] + key If c > 122 Then c -= 26 s[i] = c End Select Next End Sub   Sub Decrypt(s As String, key As Integer) Dim c As Integer For i As Integer = 0 To Len(s) Select Case As Const s[i] Case 65 To 90 c = s[i] - key If c < 65 Then c += 26 s[i] = c Case 97 To 122 c = s[i] - key If c < 97 Then c += 26 s[i] = c End Select Next End Sub   Dim As String s = "Bright vixens jump; dozy fowl quack." Print "Plain text : "; s Encrypt s, 8 Print "Encrypted  : "; s Decrypt s, 8 Print "Decrypted  : "; s Sleep
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   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#M2000_Interpreter
M2000 Interpreter
// Calling a function that requires no arguments ModuleA ' introduce a namespace can have modules/functions/subs, anything inside, and threads. Call FunctionA() ' introduce a namespace can have modules/functions/subs, anything inside. Call LambdaA() ' introduce a namespace can have modules/functions/subs, anything inside. SubAlfa() ' subroutine this has the same scope as the caller, we can use Local statement to shadow variables/arrays Print @Simple() ' simple function this has the same scope as the caller, we can use Local statement to shadow variables/arrays Gosub labelA ' Statement Return used to return from a gosub, no arguments and no local statement used, the code is like any other code in the module/function/lambda scope. No jump out of scope allowed. Gosub 10020 ' Statement Return used to return from a gosub,, no arguments and no local statement used, the code is like any other code in the module/function/lambda scope. No jump out of scope allowed. // Calling a function with a fixed number of arguments ModuleA 100 SubAlfa(100) ' subroutine Print @Simple(100) ' simple function Call FunctionA(100) Call LambdaA(100) // Calling a function with optional arguments ModuleA ?,4 SubAlfa(?) ' subroutine Print @Simple(?) ' simple function Call FunctionA(,4) Call LambdaA(,4) // Calling a function with a variable number of arguments Call FunctionA(1,2,3,4,5) Call LambdaA(1,2,3,4,5) // Calling a function with named arguments ModuleA %X=10, %Z=20 // Using a function in statement context Module A SubAlfa() Call Void FunctionA() Call Void LambdaA() // Using a function in first-class context within an expression Print (lambda (x,y)->{=x**y}(2,3))*8=64 // Obtaining the return value of a function A%=FunctionA%() ' integer part from any numeric type. Also A% if get decimals convert to integer using school rounding (0.5, so 3.5 is 4, 2.5 is 3) A=FunctionA() ' numeric or object A$=FunctionA$() ' string or object which return string A=LambdaA() A$=LambdaA$() A=@SimpleA() A$=@SimpleA$() // Distinguishing built-in functions and user-defined functions Def Cos(x)=100*X ' change the build in Print Cos(3), @Cos(3) ' @Cos() is the build in anyway ' we can't use simple function with same name as a bultin function. // Distinguishing subroutines and functions Name without parenthesis like a command or statement is a Module Name with parentesis without operator is a Sub Name with parenthesis in an expression is a function or array (array come first), using a(*10) we say that it is function even an array a() exist. Name with @ as first symbol and parenthesis like @alfa() is a simple function unless has a builtin name, so is that function. // Stating whether arguments are passed by value or by reference Default:By Value By Reference: Using & at both sides (caller and calee) Function Alfa(&x) { =X : X++ } Print Alfa(&counter) Subs and Simple Functions not need a by reference pass because they are in the same scope from the caller, so actuall we pass by value to be local to those entities. But we can use by reference, except for static variables, and array items. Those can only passed by reference on modules and nornal functions and lambdas (which are normal functions plus more). // Is partial application possible and how A=Lambda (X) -> { =Lambda X (Y) -> { =Y**X } } Cube=A(3) : Square=A(2) Print Cube(2)=8, Square(2)=4 OOP: Functions/Modules can be members of objects. Objects may have a name (they live until code get out of scope) Objects may don't have a name but one or more pointers, (they live until counting references are zero) ObjectA.moduleA is a call to an object method (a module) pointerA=>moduleA is a call to an object by a pointer An object may return values, and may accept parameters too. Also objects if they didn't return values other than a copy of them can be use operators defined as object functions. Objects may have events and fire them using Call Event "simpleevent", param1, param2... Functions and lambda (not simple functions), and object functions can be passed by reference as parameters.
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_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#PureBasic
PureBasic
; saving the division for last ensures we divide the largest ; numerator by the smallest denominator   Procedure.q CatalanNumber(n.q) If n<0:ProcedureReturn 0:EndIf If n=0:ProcedureReturn 1:EndIf ProcedureReturn (2*(2*n-1))*CatalanNumber(n-1)/(n+1) EndProcedure   ls=25 rs=12   a.s="" a.s+LSet(RSet("n",rs),ls)+"CatalanNumber(n)" ; cw(a.s) Debug a.s   For n=0 to 33 ;33 largest correct quad for n a.s="" a.s+LSet(RSet(Str(n),rs),ls)+Str(CatalanNumber(n)) ; cw(a.s) Debug a.s Next
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 representation of N in base B has all equal digits. E.G. 1, 2 & 3 can not be Brazilian; there is no base B that satisfies the condition 1 < B < N-1. 4 is not Brazilian; 4 in base 2 is 100. The digits are not all the same. 5 is not Brazilian; 5 in base 2 is 101, in base 3 is 12. There is no representation where the digits are the same. 6 is not Brazilian; 6 in base 2 is 110, in base 3 is 20, in base 4 is 12. There is no representation where the digits are the same. 7 is Brazilian; 7 in base 2 is 111. There is at least one representation where the digits are all the same. 8 is Brazilian; 8 in base 3 is 22. There is at least one representation where the digits are all the same. and so on... All even integers 2P >= 8 are Brazilian because 2P = 2(P-1) + 2, which is 22 in base P-1 when P-1 > 2. That becomes true when P >= 4. More common: for all all integers R and S, where R > 1 and also S-1 > R, then R*S is Brazilian because R*S = R(S-1) + R, which is RR in base S-1 The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. All prime integers, that are brazilian, can only have the digit 1. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of 111 to base Integer(sqrt(prime number)). Must be an odd count of 1 to stay odd like primes > 2 Task Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page; the first 20 Brazilian numbers; the first 20 odd Brazilian numbers; the first 20 prime Brazilian numbers; See also OEIS:A125134 - Brazilian numbers OEIS:A257521 - Odd Brazilian numbers OEIS:A085104 - Prime Brazilian numbers
#zkl
zkl
fcn isBrazilian(n){ foreach b in ([2..n-2]){ f,m := n%b, n/b; while(m){ if((m % b)!=f) continue(2); m/=b; } return(True); } False } fcn isBrazilianW(n){ isBrazilian(n) and n or Void.Skip }
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 formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43. (Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.) Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar. This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983. THE REAL PROGRAMMER'S NATURAL HABITAT "Taped to the wall is a line-printer Snoopy calender for the year 1969." For further Kudos see task CALENDAR, where all code is to be in UPPERCASE. For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. Related task   Five weekends
#PicoLisp
PicoLisp
(de cal (Year) (prinl "====== " Year " ======") (for Dat (range (date Year 1 1) (date Year 12 31)) (let D (date Dat) (tab (3 3 4 8) (when (= 1 (caddr D)) (get *Mon (cadr D)) ) (caddr D) (day Dat *Day) (when (=0 (% (inc Dat) 7)) (pack "Week " (week Dat)) ) ) ) ) )   (cal 1969)
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 within the field. Where is not particularly important; it could be randomized, or it could be a fixed point. Particles are injected into the field, and are individually given a (typically random) motion pattern. When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree. Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
#Scheme
Scheme
; Save bitmap to external file (define (save-pbm bitmap filename) (define f (open-output-file filename)) (simple-format f "P1\n~A ~A\n" (list-ref (array-dimensions bitmap) 0) (list-ref (array-dimensions bitmap) 1)) (do ((c 0 (+ c 1))) ((eqv? c (list-ref (array-dimensions bitmap) 1))) (do ((r 0 (+ r 1))) ((eqv? r (list-ref (array-dimensions bitmap) 0))) (display (array-ref bitmap r c) f)) (newline f)) (close-output-port f) )   ; Return a random coordinate in the bitmap that isn't filled yet along with a direction (define (new-particle bitmap) (define x (random (list-ref (array-dimensions bitmap) 0))) (define y (random (list-ref (array-dimensions bitmap) 1))) (define dx (- (random 3) 1)) (define dy (- (random 3) 1)) ;Repeat until we find an unused location (if (> (array-ref bitmap x y) 0) (new-particle bitmap) (list (list x y) (list dx dy))))   ; Check neighboring coordinates to see if a collision occured (define (collision-check bitmap p) (define c #f) (define oob #f) (define x (list-ref (car p) 0)) (define y (list-ref (car p) 1)) (define dx (list-ref (cadr p) 0)) (define dy (list-ref (cadr p) 1)) (define w (list-ref (array-dimensions bitmap) 0)) (define h (list-ref (array-dimensions bitmap) 1))   ; If the particle hasn't gone out of bounds keep checking for a collision (if (or (> 0 x) (> 0 y) (<= w x) (<= h y)) (set! oob #t) (do ((x (- (list-ref (car p) 0) 1) (+ x 1))) ((eqv? x (+ (list-ref (car p) 0) 2))) (do ((y (- (list-ref (car p) 1) 1) (+ y 1))) ((eqv? y (+ (list-ref (car p) 1) 2))) ; Check existing neighbors for collisions (if (and (<= 0 x) (<= 0 y) (> w x) (> h y)) (if (not (zero? (array-ref bitmap x y))) (set! c #t)))))) (if oob #f ; Return false if out of bounds (if c p ; Return the point of collision if a collision occured (if (and (zero? dx) (zero? dy)) #f ; Return false if particle is motionless with no collision (collision-check bitmap (particle-move p))))))   ; Plot a particle on the bitmap (define (particle-plot! bitmap p) (array-set! bitmap 1 (list-ref (car p) 0) (list-ref (car p) 1)))   ; Move a particle along its slope (define (particle-move p) (list (list (+ (list-ref (car p) 0) (list-ref (cadr p) 0)) (+ (list-ref (car p) 1) (list-ref (cadr p) 1))) (cadr p)))   ; Grow a brownian tree (define (grow-brownian-tree! bitmap collisions) (define w (list-ref (array-dimensions bitmap) 0)) (define h (list-ref (array-dimensions bitmap) 1))   ; Generate a new particle at a random location (define p (new-particle bitmap))   ; Find a collision or lack of one and plot it on the bitmap (set! p (collision-check bitmap p)) (if p (begin ; Display collision number and the place it happened (display collisions)(display ": ")(display (car p))(newline) (set! collisions (- collisions 1)) ; Plot the point (particle-plot! bitmap p)))   ; If we're done say so (if (zero? collisions) (display "Done\n"))   ; Keep going until we have enough collisions ; or have filled the bitmap (if (and (< 0 collisions) (memq 0 (array->list (array-contents bitmap)))) (grow-brownian-tree! bitmap collisions)))   ; Plot a random point to seed the brownian tree (define (seed-brownian-tree! bitmap) (define p (new-particle bitmap)) (particle-plot! bitmap p))   ;;; Example usage ;;; ; Seed the random number generator (let ((time (gettimeofday))) (set! *random-state* (seed->random-state (+ (car time) (cdr time)))))   ; Generate a tree with 320*240 collisions on a bitmap of the size 640x480 ; The bitmap is zeroed to start and written with a one where a collision occurs (define bitmap (make-array 0 640 480)) (seed-brownian-tree! bitmap) (grow-brownian-tree! bitmap (* 320 240))   ; Save to a portable bitmap file (save-pbm bitmap "brownian-tree.pbm")
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 randomly chosen number, and the program ends. A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number. A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position. Related tasks   Bulls and cows/Player   Guess the number   Guess the number/With Feedback   Mastermind
#Kotlin
Kotlin
// version 1.1.2   import java.util.Random   const val MAX_GUESSES = 20 // say   fun main(args: Array<String>) { val r = Random() var num: String // generate a 4 digit random number from 1234 to 9876 with no zeros or repeated digits do { num = (1234 + r.nextInt(8643)).toString() } while ('0' in num || num.toSet().size < 4)   println("All guesses should have exactly 4 distinct digits excluding zero.") println("Keep guessing until you guess the chosen number (maximum $MAX_GUESSES valid guesses).\n") var guesses = 0 while (true) { print("Enter your guess : ") val guess = readLine()!! if (guess == num) { println("You've won with ${++guesses} valid guesses!") return } val n = guess.toIntOrNull() if (n == null) println("Not a valid number") else if ('-' in guess || '+' in guess) println("Can't contain a sign") else if ('0' in guess) println("Can't contain zero") else if (guess.length != 4) println("Must have exactly 4 digits") else if (guess.toSet().size < 4) println("All digits must be distinct") else { var bulls = 0 var cows = 0 for ((i, c) in guess.withIndex()) { if (num[i] == c) bulls++ else if (c in num) cows++ } println("Your score for this guess: Bulls = $bulls Cows = $cows") guesses++ if (guesses == MAX_GUESSES) println("You've now had $guesses valid guesses, the maximum allowed") } } }
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 "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Gambas
Gambas
Public Sub Main() Dim byKey As Byte = 3 'The key (Enter 26 to get the same output as input) Dim byCount As Byte 'Counter Dim sCeasar As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" 'Used to calculate the cipher Dim sString As String = "The five boxing wizards jump quickly" 'Phrase to encrypt Dim sCoded, sTemp As String 'Various strings   For byCount = 1 To Len(sString) 'Count through each letter in the phrase If Mid(sString, byCount, 1) = " " Then 'If it's a space.. sCoded &= " " 'Keep it a space Continue 'Jump to the next iteration of the loop Endif sTemp = Mid(sCeasar, InStr(sCeasar, Mid(UCase(sString), byCount, 1)) + byKey, 1) 'Get the new 'coded' letter If Asc(Mid(sString, byCount, 1)) > 96 Then sTemp = Chr(Asc(sTemp) + 32) 'If the original was lower case then make the new 'coded' letter lower case sCoded &= sTemp 'Add the result to the code string Next   Print sString & gb.NewLine & sCoded 'Print the result   End
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   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#Maple
Maple
f()
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_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#Python
Python
from math import factorial import functools     def memoize(func): cache = {}   def memoized(key): # Returned, new, memoized version of decorated function if key not in cache: cache[key] = func(key) return cache[key] return functools.update_wrapper(memoized, func)     @memoize def fact(n): return factorial(n)     def cat_direct(n): return fact(2 * n) // fact(n + 1) // fact(n)     @memoize def catR1(n): return 1 if n == 0 else ( sum(catR1(i) * catR1(n - 1 - i) for i in range(n)) )     @memoize def catR2(n): return 1 if n == 0 else ( ((4 * n - 2) * catR2(n - 1)) // (n + 1) )     if __name__ == '__main__': def pr(results): fmt = '%-10s %-10s %-10s' print((fmt % tuple(c.__name__ for c in defs)).upper()) print(fmt % (('=' * 10,) * 3)) for r in zip(*results): print(fmt % r)   defs = (cat_direct, catR1, catR2) results = [tuple(c(i) for i in range(15)) for c in defs] pr(results)
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 formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43. (Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.) Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar. This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983. THE REAL PROGRAMMER'S NATURAL HABITAT "Taped to the wall is a line-printer Snoopy calender for the year 1969." For further Kudos see task CALENDAR, where all code is to be in UPPERCASE. For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. Related task   Five weekends
#Pike
Pike
#!/bin/env pike   int main(int argc, array(string) argv) { object cal = Calendar; object year; string region = "us";   array date = argv[1..]; if (sizeof(date) && objectp(Calendar[date[0]]) && Calendar[date[0]]->Day) { cal = Calendar[date[0]]; date = Array.shift(date)[1]; }   if (sizeof(date) && (int)date[0]) { year = cal.Year((int)date[0]); date = Array.shift(date)[1]; }   if (sizeof(date)) region = date[0];   if (!year) year = cal.Year();   print_year(year, region); }   array make_month(object month, int field_width, void|string region) { array out =({}); mapping holidays = ([]); object today = Calendar.Day();   if (region) holidays = Calendar.Events.find_region(region)->scan_events(month);   array weekday_names = sprintf("%*.*s", field_width, field_width, month->week()->days()->week_day_shortname()[*]);   out += ({ ({ month->month_name(), month->month_no(), month->year_name() }) }); out += ({ weekday_names }); out += showday(month->weeks()->days()[*][*], month, today, holidays, field_width);   out += ({ ({ " "*field_width })*sizeof(weekday_names) });   return out; }   string print_month(object _month, void|int field_width, void|string region) { if (!field_width) field_width = 2; array month = make_month(_month, field_width, region); string out = "";   out += sprintf("%|*s\n", (field_width+1)*sizeof(month[1])-1, sprintf("%s", month[0][0])); out += sprintf((month[1..][*]*" ")*"\n"); return out; }   string print_year(object year, void|string region) { array output = ({}); int day_width = 2; int columns = Stdio.stdout.tcgetattr()->columns; int month_width = sizeof(make_month(year->month(), day_width)[1]) * (day_width+1) - 1; if (columns < month_width) columns = month_width;   // try to find an optimal good looking solution to spread the months // across the terminal width // for the common calendar of 12 months this is easy but we need to // account for caledars that have more than 12 months float max_width = (float)((columns+2)/(month_width+2)); float max_height = ceil(year->number_of_months()/max_width); float w = max_width;   while(ceil(year->number_of_months()/(w-1)) == max_height) w--;   foreach(print_month(year->months()[*], day_width, region)/w;; array row) { array rows = row[*]/"\n"; int l = max(@sizeof(rows[*])); foreach(rows; int i;) { // the last line of each month is an empty line. // repeat the line as many times as needed to make the months equally long rows[i]+=({ rows[i][-1] })*(l-sizeof(rows[i])); } rows = Array.transpose(rows); output += rows[*]*" "; } write("%*|s\n", sizeof(output[1]), year->format_nice()); write(output * "\n"); write("\n"); }   string showday(object day, object month, object today, mapping holidays, int field_width) { string dayname; if (day->month() == month) { dayname = (string)day->month_day(); dayname = " "*(sizeof((string)month->number_of_days())-sizeof(dayname))+dayname; if (day == today) dayname = sprintf("%|*.*s", field_width, field_width, dayname); else dayname = sprintf("%|*.*s", field_width, field_width, dayname); if (holidays[day]) dayname = sprintf("%|s", dayname); } else dayname = " "*field_width; return dayname; }  
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 within the field. Where is not particularly important; it could be randomized, or it could be a fixed point. Particles are injected into the field, and are individually given a (typically random) motion pattern. When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree. Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "draw.s7i"; include "keybd.s7i";   const integer: SIZE is 300; const integer: SCALE is 1;   const proc: genBrownianTree (in integer: fieldSize, in integer: numParticles) is func local var array array integer: world is 0 times 0 times 0; var integer: px is 0; var integer: py is 0; var integer: dx is 0; var integer: dy is 0; var integer: i is 0; var boolean: bumped is FALSE; begin world := fieldSize times fieldSize times 0; world[rand(1, fieldSize)][rand(1, fieldSize)] := 1; # Set the seed for i range 1 to numParticles do # Set particle's initial position px := rand(1, fieldSize); py := rand(1, fieldSize); bumped := FALSE; repeat # Randomly choose a direction dx := rand(-1, 1); dy := rand(-1, 1); if dx + px < 1 or dx + px > fieldSize or dy + py < 1 or dy + py > fieldSize then # Plop the particle into some other random location px := rand(1, fieldSize); py := rand(1, fieldSize); elsif world[py + dy][px + dx] <> 0 then # Bumped into something world[py][px] := 1; rect(SCALE * pred(px), SCALE * pred(py), SCALE, SCALE, white); DRAW_FLUSH; bumped := TRUE; else py +:= dy; px +:= dx; end if; until bumped; end for; end func;   const proc: main is func begin screen(SIZE * SCALE, SIZE * SCALE); KEYBOARD := GRAPH_KEYBOARD; genBrownianTree(SIZE, 20000); readln(KEYBOARD); end func;
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 within the field. Where is not particularly important; it could be randomized, or it could be a fixed point. Particles are injected into the field, and are individually given a (typically random) motion pattern. When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree. Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
#SequenceL
SequenceL
import <Utilities/Random.sl>; import <Utilities/Sequence.sl>;   POINT ::= (X: int, Y: int); RET_VAL ::= (World: int(2), Rand: RandomGenerator<int, int>, Point: POINT);   randomWalk(x, y, world(2), rand) := let randX := getRandom(rand); randY := getRandom(randX.Generator); nextX := x + (randX.Value mod 3) - 1; nextY := y + (randY.Value mod 3) - 1; newStartX := (randX.Value mod (size(world) - 2)) + 2; newStartY := (randY.Value mod (size(world) - 2)) + 2;   numNeighbors := world[y-1,x-1] + world[y-1,x] + world[y-1,x+1] + world[y,x-1] + world[y,x+1] + world[y+1,x-1] + world[y+1,x] + world[y+1,x+1];   outOfBounds := nextX <= 1 or nextY <= 1 or nextX >= size(world) or nextY >= size(world); in randomWalk(newStartX, newStartY, world, randY.Generator) when world[y,x] = 1 or outOfBounds else (X: x, Y: y) when numNeighbors > 0 else randomWalk(nextX, nextY, world, randY.Generator);   step(rand, world(2)) := let walkSeed := getRandom(rand); newParticle := randomWalk(size(world)/2,size(world)/2, world, seedRandom(walkSeed.Value));   newWorld[j] := world[j] when j /= newParticle.Y else setElementAt(world[j], newParticle.X, 1); in (World: newWorld, Rand: walkSeed.Generator, Point: newParticle);     initialWorld(worldSize, seed) := let world[i,j] := 1 when i = worldSize / 2 and j = worldSize / 2 else 0 foreach i within 1 ... worldSize, j within 1 ... worldSize; in (World: world, Rand: seedRandom(seed), Point: (X: worldSize / 2, Y: worldSize / 2));
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 randomly chosen number, and the program ends. A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number. A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position. Related tasks   Bulls and cows/Player   Guess the number   Guess the number/With Feedback   Mastermind
#Lasso
Lasso
[ define randomizer() => { local(n = string) while(#n->size < 4) => { local(r = integer_random(1,9)->asString) #n !>> #r ? #n->append(#r) } return #n } define cowbullchecker(n::string,a::string) => { integer(#n) == integer(#a) ? return (:true,map('cows'=0,'bulls'=4,'choice'=#a)) local(cowbull = map('cows'=0,'bulls'=0,'choice'=#a),'checked' = array) loop(4) => { if(#checked !>> integer(#a->values->get(loop_count))) => { #checked->insert(integer(#a->values->get(loop_count))) if(integer(#n->values->get(loop_count)) == integer(#a->values->get(loop_count))) => { #cowbull->find('bulls') += 1 else(#n->values >> #a->values->get(loop_count)) #cowbull->find('cows') += 1 } } } #cowbull->find('bulls') == 4 ? return (:true,map('cows'=0,'bulls'=4,'choice'=#a)) return (:true,#cowbull) } session_start('user') session_addvar('user', 'num') session_addvar('user', 'historic_choices') // set up rand var(num)->isNotA(::string) ? var(num = randomizer) var(historic_choices)->isNotA(::array) ? var(historic_choices = array) local(success = false) // check answer if(web_request->param('a')->asString->size) => { local(success,result) = cowbullchecker($num,web_request->param('a')->asString) $historic_choices->insert(#result) } if(web_request->params->asStaticArray >> 'restart') => { $num = randomizer $historic_choices = array } ] <h1>Bulls and Cows</h1> <p>Guess the 4-digit number...</p> <p>Your win if the guess is the same as the randomly chosen number.<br> - A score of one bull is accumulated for each digit in your guess that equals the corresponding digit in the randomly chosen initial number.<br> - A score of one cow is accumulated for each digit in your guess that also appears in the randomly chosen number, but in the wrong position. </p> [ local(win = false) if($historic_choices->size) => { with c in $historic_choices do => {^ '<p>'+#c->find('choice')+': Bulls: '+#c->find('bulls')+', Cows: '+#c->find('cows') if(#c->find('bulls') == 4) => {^ ' - YOU WIN!' #win = true ^} '</p>' ^} } if(not #win) => {^ ] <form action="?" method="post"> <input name="a" value="[web_request->param('a')->asString]" size="5"> <input type="submit" name="guess"> <a href="?restart">Restart</a> </form> [else '<a href="?restart">Restart</a>' ^}]  
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 "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#GAP
GAP
CaesarCipher := function(s, n) local r, c, i, lower, upper; lower := "abcdefghijklmnopqrstuvwxyz"; upper := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; r := ""; for c in s do i := Position(lower, c); if i <> fail then Add(r, lower[RemInt(i + n - 1, 26) + 1]); else i := Position(upper, c); if i <> fail then Add(r, upper[RemInt(i + n - 1, 26) + 1]); else Add(r, c); fi; fi; od; return r; end;   CaesarCipher("IBM", 25); # "HAL"   CaesarCipher("Vgg cphvi wzdibn vmz wjmi amzz viy zlpvg di ydbidot viy mdbcon.", 5); # "All human beings are born free and equal in dignity and rights."
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   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
f[]
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   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#MATLAB_.2F_Octave
MATLAB / Octave
  % Calling a function that requires no arguments function a=foo(); a=4; end; x = foo(); % Calling a function with a fixed number of arguments function foo(a,b,c); %% function definition; end; foo(x,y,z); % Calling a function with optional arguments function foo(a,b,c); if nargin<2, b=0; end; if nargin<3, c=0; end; %% function definition; end; foo(x,y); % Calling a function with a variable number of arguments function foo(varargin); for k=1:length(varargin) arg{k} = varargin{k}; end; foo(x,y); % Calling a function with named arguments %% does not apply % Using a function in statement context %% does not apply % Using a function in first-class context within an expression % Obtaining the return value of a function function [a,b]=foo(); a=4; b='result string'; end; [x,y] = foo(); % Distinguishing built-in functions and user-defined functions fun = 'foo'; if (exist(fun,'builtin')) printf('function %s is a builtin\n'); elseif (exist(fun,'file')) printf('function %s is user-defined\n'); elseif (exist(fun,'var')) printf('function %s is a variable\n'); else printf('%s is not a function or variable.\n'); end % Distinguishing subroutines and functions % there are only scripts and functions, any function declaration starts with the keyword function, otherwise it is a script that runs in the workspace % Stating whether arguments are passed by value or by reference % arguments are passed by value, however Matlab has delayed evaluation, such that a copy of large data structures are done only when an element is written to.  
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_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#Quackery
Quackery
[ 1 over times [ over i 1+ + * ] nip ] is 2n!/n! ( n --> n )   [ times [ i 1+ / ] ] is /n! ( n --> n )   [ dup 2n!/n! swap 1+ /n! ] is catalan ( n --> n )   15 times [ i^ dup echo say " : " catalan echo cr ]
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 formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43. (Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.) Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar. This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983. THE REAL PROGRAMMER'S NATURAL HABITAT "Taped to the wall is a line-printer Snoopy calender for the year 1969." For further Kudos see task CALENDAR, where all code is to be in UPPERCASE. For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. Related task   Five weekends
#PL.2FI
PL/I
  calendar: procedure (year) options (main); declare year character (4) varying; declare (a, b, c) (0:5,0:6) character (3); declare name_month(12) static character (9) varying initial ( 'JANUARY', 'FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE', 'JULY', 'AUGUST', 'SEPTEMBER', 'OCTOBER', 'NOVEMBER', 'DECEMBER'); declare i fixed; declare (mm, mmp1, mmp2) pic '99';   put edit (center('CALENDAR FOR ' || YEAR, 67)) (a); put skip (2);   do mm = 1 to 12 by 3; mmp1 = mm + 1; mmp2 = mm + 2; call prepare_month('01' || mm || YEAR, a); call prepare_month('01' || mmp1 || YEAR, b); call prepare_month('01' || mmp2 || YEAR, c);   put skip edit (center(name_month(mm), 23), center(name_month(mmp1), 23), center(name_month(mmp2), 23) ) (a); put skip edit ((3)' M T W T F S S ') (a); do i = 0 to 5; put skip edit (a(i,*), b(i,*), c(i,*)) (7 a, x(2)); end; end;   prepare_month: procedure (start, month); declare month(0:5,0:6) character (3); declare start character (8); declare i pic 'ZZ9'; declare offset fixed; declare (j, day) fixed binary (31); declare (this_month, next_month, k) fixed binary;   day = days(start, 'DDMMYYYY'); offset = weekday(day) - 1; if offset = 0 then offset = 7; month = ''; do j = day by 1; this_month = substr(daystodate(j, 'DDMMYYYY'), 3, 2); next_month = substr(daystodate(j+1, 'DDMMYYYY'), 3, 2); if this_month^= next_month then leave; end; i = 1; do k = offset-1 to offset+j-day-1; month(k/7, mod(k,7)) = i; i = i + 1; end; end prepare_month;   end calendar;  
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 within the field. Where is not particularly important; it could be randomized, or it could be a fixed point. Particles are injected into the field, and are individually given a (typically random) motion pattern. When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree. Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
#Sidef
Sidef
const size = 100 const mid = size>>1 const particlenum = 1000   var map = [] var spawnradius = 5   func set(x, y) { map[x][y] = 1 }   func get(x, y) { map[x][y] \\ 0 }   set(mid, mid)   var blocks = [ " ", "\N{UPPER HALF BLOCK}", "\N{LOWER HALF BLOCK}", "\N{FULL BLOCK}" ]   func block(a, b) { blocks[2*b + a] }   func display { 0..size `by` 2 -> map {|y| 0..size -> map {|x| if ([x, y].all { .-mid < spawnradius }) { block(get(x, y), get(x, y+1)) } else { " " } }.join }.join("\n").say }   for progress in (^particlenum) { var (x=0, y=0)   var reset = { do { (x, y) = ( (mid-spawnradius .. mid+spawnradius -> pick), [mid-spawnradius, mid+spawnradius] -> pick ) (x, y) = (y, x) if (1.rand < 0.5) } while(get(x, y)) }   reset.run   while ([[-1, 0, 1]]*2 -> cartesian.any {|pair| get(x+pair[0], y+pair[1]) } -> not) { x = [x-1, x, x+1].pick y = [y-1, y, y+1].pick   if (1.rand < 0.25) { x = (x >= mid ? (x-1) : (x+1)) y = (y >= mid ? (y-1) : (y+1)) }   if ([x,y].any { .-mid > spawnradius }) { reset.run } }   set(x, y) display() if (progress %% 50)   if ((spawnradius < mid) && [x,y].any { .-mid > spawnradius-5 }) { ++spawnradius } }   display()
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 randomly chosen number, and the program ends. A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number. A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position. Related tasks   Bulls and cows/Player   Guess the number   Guess the number/With Feedback   Mastermind
#Liberty_BASIC
Liberty BASIC
    do while len( secret$) <4 c$ =chr$( int( rnd( 1) *9) +49) if not( instr( secret$, c$)) then secret$ =secret$ +c$ loop   print " Secret number has been guessed.... "; secret$   guesses = 0   [loop] print " Your guess "; input " "; guess$   guesses = guesses +1   r$ =score$( guess$, secret$)   bulls =val( word$( r$, 1, ",")) cows =val( word$( r$, 2, ","))   print " Result: "; bulls; " bulls, and "; cows; " cows" print   if guess$ =secret$ then print " You won after "; guesses; " guesses!" print " You guessed it in "; guesses print " Thanks for playing!" wait end if   goto [loop]   end ' _____________________________________________________________   function check( i$) ' check =0 if no digit repeats, else =1 check =0 for i =1 to 3 for j =i +1 to 4 if mid$( i$, i, 1) =mid$( i$, j, 1) then check =1 next j next i end function   function score$( a$, b$) ' return as a csv string the number of bulls & cows. bulls = 0: cows = 0 for i = 1 to 4 c$ = mid$( a$, i, 1) if mid$( b$, i, 1) = c$ then bulls = bulls + 1 else if instr( b$, c$) <>0 and instr( b$, c$) <>i then cows = cows + 1 end if end if next i score$ =str$( bulls); ","; str$( cows) end function   [quit] close #w end  
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 "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#GFA_Basic
GFA Basic
  ' ' Caesar cypher ' OPENW 1 ! Creates a window for handling input/output CLEARW 1 INPUT "string to encrypt ";text$ INPUT "encryption key ";key% encrypted$=@encrypt$(UPPER$(text$),key%) PRINT "Encrypted: ";encrypted$ PRINT "Decrypted: ";@decrypt$(encrypted$,key%) ' PRINT "(Press any key to end program.)" ~INP(2) CLOSEW 1 ' FUNCTION encrypt$(text$,key%) LOCAL result$,i%,c% result$="" FOR i%=1 TO LEN(text$) c%=ASC(MID$(text$,i%)) IF c%<ASC("A") OR c%>ASC("Z") ! don't encrypt non A-Z result$=result$+CHR$(c%) ELSE c%=c%+key% IF c%>ASC("Z") c%=c%-26 ENDIF result$=result$+CHR$(c%) ENDIF NEXT i% RETURN result$ ENDFUNC ' FUNCTION decrypt$(text$,key%) RETURN @encrypt$(text$,26-key%) ENDFUNC  
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   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#Nanoquery
Nanoquery
// function with no arguments no_args()   // function with fixed amount of arguments three_args(a, b, c)   // nanoquery does not support optional, variable, or named arguments   // obtaining a return value value = returns_value()   // checking if a function called "func" is user-defined try type(func) println "func is user-defined" catch println "func is a built-in or doesn't exist" end
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   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#Nemerle
Nemerle
// no arguments f()   // fixed arguments def f(a, b) { ... } // as an aside, functions defined with 'def' use type inference for parameters and return types f(1, 'a')   // optional arguments def f(a, b = 0) { ... } f("hello") f("goodbye", 2) f("hey", b = 2) // using the name makes more sense if there's more than one optional argument, obviously   // variable number of arguments def f(params args) { ... } def g(a, b, params rest) { ... } f(1, 2, 3) // arguments should all have the same type or may be coerced to a supertype g(1.0, 2, "a", "hello")   // named arguments f(a = 'a', b = 0) f(b = 0, a = 'a') f('a', b = 0) // if mixing named and unnamed args, unnamed must be first and in correct order   // statement context if (f(foo) == 42) WriteLine($"$foo is the meaning to life, the universe and everything.") else WriteLine($"$foo is meaningless.")   // first class function in an expression def a = numList.FoldLeft(f)   // obtaining return value def a = f(3)   // distinguishing built-in from user functions // N/A?   // distinguishing subroutines from functions // N/A   // stating whether passed by value or by reference // .NET distinguishes between value types and reference types; if a reference type is passed by reference (using ref or out), // the reference is passed by reference, which would allow a method to modify the object to which the reference refers def f(a, ref b) { ... } mutable someVar = "hey there" // doesn't make sense to pass immutable value by ref f(2, ref someVar) def g(a, out b) { ... } mutable someOtherVar // if passed by ref using 'out', the variable needn't be initialized g(2, out someOtherVar)   // partial application def f(a, b) { ... } def g = f(2, _) def h = f(_, 2) def a = g(3) // equivalent to: def a = f(2, 3) def b = h(3) // equivalent to: def b = f(3, 2)
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_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#R
R
catalan <- function(n) choose(2*n, n)/(n + 1) catalan(0:15) [1] 1 1 2 5 14 42 132 429 1430 [10] 4862 16796 58786 208012 742900 2674440 9694845
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 formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43. (Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.) Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar. This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983. THE REAL PROGRAMMER'S NATURAL HABITAT "Taped to the wall is a line-printer Snoopy calender for the year 1969." For further Kudos see task CALENDAR, where all code is to be in UPPERCASE. For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. Related task   Five weekends
#PowerShell
PowerShell
  Param([int]$Year = 1969) Begin { $COL_WIDTH = 21 $COLS = 3 $MONTH_COUNT = 12 $MONTH_LINES = 9   Function CenterStr([string]$s, [int]$lineSize) { $padSize = [int](($lineSize - $s.Length) / 2) ($(if ($padSize -gt 0) { ' ' * $padSize } else { '' }) + $s).PadRight($lineSize,' ') }   Function MonthLines([int]$month) { $dt = [System.DateTime]::new($Year, $month, 1) $line = CenterStr $dt.ToString("MMMM") $COL_WIDTH $line += 'Su Mo Tu We Th Fr Sa' $line += $(' ' * $dt.DayOfWeek.value__) $line += (-join ($(1..$($dt.AddMonths(1).AddDays(-1).Day)) | %{ $("" + $_).PadLeft(3) })) $line = $line.PadRight($MONTH_LINES * $COL_WIDTH) New-Object –TypeName PSObject –Prop(@{ 'Lines'=(0..($MONTH_LINES - 1)) | %{ $_ * $COL_WIDTH } | %{ -join $line[$_..($_ + $COL_WIDTH - 1)] } 'Dt'=$dt}) } } Process { Write-Output (CenterStr $Year ($COL_WIDTH * $COLS + 4)) $(0..($MONTH_COUNT / $COLS - 1)) | %{ $fm = $_ * $COLS $monthNums = $fm..($fm + $COLS - 1) | %{ $_ + 1 } $months = $monthNums | %{ MonthLines $_ } $(0..($MONTH_LINES - 1)) | %{ $ml = $_ Write-Output $(-join ($(0..($COLS - 1)) | %{ $(if ($_ -eq 0) { '' } else {' '}) + $months[$_].Lines[$ml] })) } } }  
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 within the field. Where is not particularly important; it could be randomized, or it could be a fixed point. Particles are injected into the field, and are individually given a (typically random) motion pattern. When a particle collides with the seed or tree, its position is fixed, and it's considered to be part of the tree. Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.
#Simula
Simula
BEGIN INTEGER NUM_PARTICLES; INTEGER LINES, COLUMNS; INTEGER SEED;   NUM_PARTICLES := 1000; LINES := 46; COLUMNS := 80; SEED := ININT; BEGIN   PROCEDURE DRAW_BROWNIAN_TREE(WORLD); INTEGER ARRAY WORLD; BEGIN INTEGER PX, PY; COMMENT PARTICLE VALUES ; INTEGER DX, DY; COMMENT OFFSETS ; INTEGER I;   COMMENT SET THE SEED ; PX := RANDINT(0,LINES-1,SEED); PY := RANDINT(0,COLUMNS-1,SEED); WORLD(PX,PY) := 1;   FOR I := 0 STEP 1 UNTIL NUM_PARTICLES - 1 DO BEGIN COMMENT SET PARTICLE'S INITIAL POSITION ; PX := RANDINT(0,LINES-1,SEED); PY := RANDINT(0,COLUMNS-1,SEED);   WHILE TRUE DO BEGIN COMMENT RANDOMLY CHOOSE A DIRECTION ; DX := RANDINT(-1,1,SEED); DY := RANDINT(-1,1,SEED);   IF DX + PX < 0 OR DX + PX >= LINES OR DY + PY < 0 OR DY + PY >= COLUMNS THEN BEGIN COMMENT PLOP THE PARTICLE INTO SOME OTHER RANDOM LOCATION ; PX := RANDINT(0,LINES-1,SEED); PY := RANDINT(0,COLUMNS-1,SEED); END ELSE IF WORLD(PX + DX, PY + DY) <> 0 THEN BEGIN COMMENT BUMPED INTO SOMETHING ; WORLD(PX, PY) := 1; GO TO BREAK; END ELSE BEGIN PY := PY + DY; PX := PX + DX; END IF; END WHILE; BREAK: END FOR; END DRAW_BROWNIAN_TREE;   INTEGER ARRAY WORLD(0:LINES-1,0:COLUMNS-1); INTEGER I,J;   DRAW_BROWNIAN_TREE(WORLD);   FOR I := 0 STEP 1 UNTIL LINES-1 DO BEGIN FOR J := 0 STEP 1 UNTIL COLUMNS-1 DO BEGIN OUTCHAR(IF WORLD(I,J)=0 THEN '.' ELSE '*'); END; OUTIMAGE; END;   END; END.
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 randomly chosen number, and the program ends. A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number. A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position. Related tasks   Bulls and cows/Player   Guess the number   Guess the number/With Feedback   Mastermind
#Logo
Logo
to ok? :n output (and [number? :n] [4 = count :n] [4 = count remdup :n] [not member? 0 :n]) end   to init do.until [make "hidden random 10000] [ok? :hidden] end   to guess :n if not ok? :n [print [Bad guess! (4 unique digits, 1-9)] stop] localmake "bulls 0 localmake "cows 0 foreach :n [cond [ [[? = item # :hidden] make "bulls 1 + :bulls] [[member?  ? :hidden] make "cows 1 + :cows ] ]] (print :bulls "bulls, :cows "cows) if :bulls = 4 [print [You guessed it!]] end
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 "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#Go
Go
package main   import ( "fmt" "strings" )   type ckey struct { enc, dec func(rune) rune }   func newCaesar(k int) (*ckey, bool) { if k < 1 || k > 25 { return nil, false } rk := rune(k) return &ckey{ enc: func(c rune) rune { if c >= 'a' && c <= 'z'-rk || c >= 'A' && c <= 'Z'-rk { return c + rk } else if c > 'z'-rk && c <= 'z' || c > 'Z'-rk && c <= 'Z' { return c + rk - 26 } return c }, dec: func(c rune) rune { if c >= 'a'+rk && c <= 'z' || c >= 'A'+rk && c <= 'Z' { return c - rk } else if c >= 'a' && c < 'a'+rk || c >= 'A' && c < 'A'+rk { return c - rk + 26 } return c }, }, true }   func (ck ckey) encipher(pt string) string { return strings.Map(ck.enc, pt) }   func (ck ckey) decipher(ct string) string { return strings.Map(ck.dec, ct) }   func main() { pt := "The five boxing wizards jump quickly" fmt.Println("Plaintext:", pt) for _, key := range []int{0, 1, 7, 25, 26} { ck, ok := newCaesar(key) if !ok { fmt.Println("Key", key, "invalid") continue } ct := ck.encipher(pt) fmt.Println("Key", key) fmt.Println(" Enciphered:", ct) fmt.Println(" Deciphered:", ck.decipher(ct)) } }
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   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#Nim
Nim
proc no_args() = discard # call no_args()   proc fixed_args(x, y) = echo x echo y # calls fixed_args(1, 2) # x=1, y=2 fixed_args 1, 2 # same call 1.fixed_args(2) # same call     proc opt_args(x=1.0) = echo x # calls opt_args() # 1 opt_args(3.141) # 3.141   proc var_args(v: varargs[string, `$`]) = for x in v: echo x # calls var_args(1, 2, 3) # (1, 2, 3) var_args(1, (2,3)) # (1, (2, 3)) var_args() # ()   ## Named arguments fixed_args(y=2, x=1) # x=1, y=2   ## As a statement if true: no_args()   proc return_something(x): int = x + 1   var a = return_something(2)   ## First-class within an expression let x = return_something(19) + 10 let y = 19.return_something() + 10 let z = 19.return_something + 10
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   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#OCaml
OCaml
f ()
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_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#Racket
Racket
#lang racket (require planet2) ; (install "this-and-that")  ; uncomment to install (require memoize/memo)   (define/memo* (catalan m) (if (= m 0) 1 (for/sum ([i m]) (* (catalan i) (catalan (- m i 1))))))   (map catalan (range 1 15))
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 formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43. (Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.) Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar. This task is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983. THE REAL PROGRAMMER'S NATURAL HABITAT "Taped to the wall is a line-printer Snoopy calender for the year 1969." For further Kudos see task CALENDAR, where all code is to be in UPPERCASE. For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. Related task   Five weekends
#Prolog
Prolog
% Write out the calender, because format can actually span multiple lines, it is easier % to write out the static parts in place and insert the generated parts into that format. write_calendar(Year) :- month_x3_format(Year, 1, 2, 3, F1_3), month_x3_format(Year, 4, 5, 6, F4_6), month_x3_format(Year, 7, 8, 9, F7_9), month_x3_format(Year, 10, 11, 12, F10_12),   format('   ~w   January February March Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa ~w   April May June Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa ~w   July August September Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa ~w   October November December Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa ~w ', [Year, F1_3, F4_6, F7_9, F10_12]), !.   % Generate the data for a row of months and then create an atom one row at a time % for all of the months. month_x3_format(Year, M1, M2, M3, F) :- calc_month_rows(Year, M1, M1r), calc_month_rows(Year, M2, M2r), calc_month_rows(Year, M3, M3r), month_x3_format(M1r, M2r, M3r, F).   month_x3_format(M1, M2, M3, '') :- maplist(=(' '), M1), maplist(=(' '), M2), maplist(=(' '), M3). month_x3_format(M1, M2, M3, F) :- month_format(' ', M1, M1r, F1), month_format(F1, M2, M2r, F2), month_format(F2, M3, M3r, F3), atom_concat(F3, '\n', F4), month_x3_format(M1r, M2r, M3r, Fr), atom_concat(F4, Fr, F).   month_format(Orig, [Su,Mo,Tu,We,Th,Fr,Sa|R], R, F) :- maplist(day_format, [Su,Mo,Tu,We,Th,Fr,Sa], Formatted), format(atom(F2), '~w~w~w~w~w~w~w ', Formatted), atom_concat(Orig, F2, F).   day_format(' ', ' ') :- !. day_format(D, F) :- D < 10, format(atom(F), '~w ', D). day_format(D, F) :- D >= 10, format(atom(F), '~w ', D).   % Calculate the days of a month, this is done by getting the first day of the month, % then offsetting that with spaces from the start and then adding 1-NumDaysinMonth and % finally spaces until the end. The maximum possible size is used and then truncated later. calc_month_rows(Year, Month, Result) :- length(Result, 42), % max 6 rows of 7 days month_days(Month, Year, DaysInMonth), day_of_the_week(date(Year, Month, 1), FirstWeekDay), day_offset(FirstWeekDay, Offset), day_print_map(DaysInMonth, Offset, Result).   day_print_map(DaysInMonth, 0, [1|R]) :- day_print_map2(DaysInMonth, 2, R). day_print_map(DaysInMonth, Offset, [' '|R]) :- dif(Offset, 0), succ(NewOffset, Offset), day_print_map(DaysInMonth, NewOffset, R).   day_print_map2(D, D, [D|R]) :- day_print_map(R). day_print_map2(D, N, [N|R]) :- dif(D,N), succ(N, N1), day_print_map2(D, N1, R).   day_print_map([]). day_print_map([' '|R]) :- day_print_map(R).   % Figure out the number of days in a month based on whether it is a leap year or not. month_days(2, Year, Days) :- is_leap_year(Year) -> Days = 29 ; Days = 28. month_days(Month, _, Days) :- dif(Month, 2), nth1(Month, [31, _, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], Days).   % Figure out the space offset based on the day the month starts on. day_offset(D, D) :- dif(D, 7). day_offset(7, 0).   % Test for leap years is_leap_year(Year) :- 0 is Year mod 100 -> 0 is Year mod 400 ; 0 is Year mod 4.