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/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Fortran
Fortran
program main implicit none integer :: a integer :: f, g logical :: lresult interface integer function h(a,b,c) integer :: a, b integer, optional :: c end function end interface write(*,*) 'no arguments: ', f() write(*,*) '-----------------' write(*,*) 'fixed arguments: ', g(5,8,lresult) write(*,*) '--------...
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#VBA
VBA
Public Sub reduce() s = [{1,2,3,4,5}] Debug.Print WorksheetFunction.Sum(s) Debug.Print WorksheetFunction.Product(s) End Sub
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#Vlang
Vlang
vfn main() { n := [1, 2, 3, 4, 5]   println(reduce(add, n)) println(reduce(sub, n)) println(reduce(mul, n)) }   fn add(a int, b int) int { return a + b } fn sub(a int, b int) int { return a - b } fn mul(a int, b int) int { return a * b }   fn reduce(rf fn(int, int) int, m []int) int { mut r := m[0] for v in m[1....
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists
Cartesian product of two or more lists
Task Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language. Demonstrate that your function/method correctly returns: {1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)} and, in contrast: {3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)} Also demonstrate, using y...
#zkl
zkl
zkl: Walker.cproduct(List(1,2),List(3,4)).walk().println(); L(L(1,3),L(1,4),L(2,3),L(2,4)) zkl: foreach a,b in (List(1,2),List(3,4)){ print("(%d,%d) ".fmt(a,b)) } (1,3) (1,4) (2,3) (2,4)   zkl: Walker.cproduct(List(3,4),List(1,2)).walk().println(); L(L(3,1),L(3,2),L(4,1),L(4,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...
#langur
langur
val .factorial = f if(.x < 2: 1; .x x self(.x - 1)) val .catalan = f(.n) .factorial(2 x .n) / .factorial(.n+1) / .factorial(.n)   for .i in 0..15 { writeln $"\.i:2;: \(.catalan(.i):10)" }   writeln "10000: ", .catalan(10000)
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#PHP
PHP
function getitem($s,$depth=0) { $out = ['']; while ($s) { $c = $s[0]; if ($depth && ($c == ',' || $c == '}')) { return [$out, $s]; } if ($c == '{') { $x = getgroup(substr($s, 1), $depth + 1); if($x) { $tmp = []; ...
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Haskell
Haskell
import Data.Numbers.Primes (primes)   isBrazil :: Int -> Bool isBrazil n = 7 <= n && (even n || any (monoDigit n) [2 .. n - 2])   monoDigit :: Int -> Int -> Bool monoDigit n b = let (q, d) = quotRem n b in d == snd (until (uncurry (flip ((||) . (d /=)) . (0 ==))) ((`quotRem` b) . fst...
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#FutureBasic
FutureBasic
window 1, @"Calendar", (0, 0, 520, 520 )   Str255 a   open "UNIX", 1,"cal 1969" do line input #1, a print a until eof(1) close 1   HandleEvents
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#JavaScript
JavaScript
function brownian(canvasId, messageId) { var canvas = document.getElementById(canvasId); var ctx = canvas.getContext("2d");   // Options var drawPos = true; var seedResolution = 50; var clearShade = 0; // 0..255   // Static state var width = canvas.width; var height = canvas.height; var cx = width/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 random...
#E
E
def Digit := 1..9 def Number := Tuple[Digit,Digit,Digit,Digit]   /** Choose a random number to be guessed. */ def pick4(entropy) { def digits := [1,2,3,4,5,6,7,8,9].diverge()   # Partial Fisher-Yates shuffle for i in 0..!4 { def other := entropy.nextInt(digits.size() - i) + i def t := 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...
#COBOL
COBOL
  identification division. program-id. caesar. data division. 1 msg pic x(50) value "The quick brown fox jumped over the lazy dog.". 1 offset binary pic 9(4) value 7. 1 from-chars pic x(52). 1 to-chars pic x(52). 1 tabl. 2 pic x(26) value "abcde...
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
#Myrddin
Myrddin
use std   const main = { var f: uint64 = 1 var e: flt64 = 2.0 var e0: flt64 = 0.0 var n = 2   while e > e0 e0 = e f *= n e += 1.0 / (f : flt64) n++  ;; std.put("e: {}\n", 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
#Nanoquery
Nanoquery
e0 = 0 e = 2 n = 0 fact = 1 while (e - e0) > 10^-15 e0 = e n += 1 fact *= 2*n*((2*n)+1) e += ((2.0*n)+2)/fact end   println "Computed e = " + e println "Number of iterations = " + n
http://rosettacode.org/wiki/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#Raku
Raku
# we use the [] reduction meta operator along with the Cartesian Product # operator X to create the Cartesian Product of four times [1..9] and then get # all the elements where the number of unique digits is four. my @candidates = ([X] [1..9] xx 4).grep: *.unique == 4;   repeat { my $guess = @candidates.pick; my ($bu...
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to al...
#Sidef
Sidef
-> DT { ('DATE'.("\LWC") + 'TIME'.("\LWC")).("\LREQUIRE") }   -> MONTHS_PER_COL { 6 } -> WEEK_DAY_NAMES { <MO TU WE TH FR SA SU> } -> MONTH_NAMES { <JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC> }   -> FMT_MONTH (YEAR, MONTH, STR="", WEEK_DAY=0) { STR = "%11\LS\E%9\LS\E\12".("\LSPRINTF")(MONTH_NAMES()[MONTH-...
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the...
#X86-64_Assembly
X86-64 Assembly
  option casemap:none   strdup proto :qword printf proto :qword, :vararg exit proto :dword   .data bstr db "String 1",0   .data? buff dq ?   .code main proc invoke printf, CSTR("Copying %s to buff with strdup using invoke....",10), addr bstr invoke strdup, addr bstr mov buff, rax invoke printf, CSTR(...
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the...
#Zig
Zig
const std = @import("std"); const c = @cImport({ @cInclude("stdlib.h"); // `free` @cInclude("string.h"); // `strdup` });   pub fn main() !void { const string = "Hello World!"; var copy = c.strdup(string);   try std.io.getStdOut().writer().print("{s}\n", .{copy}); c.free(copy); }
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Fortress
Fortress
  component call_a_function export Executable (* Declaring test functions that allow the various ways to call functions in Fortress to be demonstrated. *) addition(i:ZZ32, j:ZZ32): ZZ32 = i+j addition(i:ZZ32): ZZ32 = i+1   (* Strings are concatenated by using a space as an infix operator. *) addition(i:Stri...
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#WDTE
WDTE
let a => import 'arrays'; let s => import 'stream'; let str => import 'strings';   # Sum of [1, 10]: let nums => [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]; a.stream nums -> s.reduce 0 + -- io.writeln io.stdout;   # As an alternative to an array, a range stream can be used. Here's the product of [1, 11): s.range 1 11 -> s.reduce ...
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#Wortel
Wortel
!/ ^+ [1 2 3] ; returns 6
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...
#Liberty_BASIC
Liberty BASIC
print "non-recursive version" print catNonRec(5) for i = 0 to 15 print i;" = "; catNonRec(i) next print   print "recursive version" print catRec(5) for i = 0 to 15 print i;" = "; catRec(i) next print   print "recursive with memoisation" redim cats(20) 'clear the array print catRecMemo(5) for i = 0 to 1...
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#PicoLisp
PicoLisp
(de braceExpand (Str) (let Lst (make (for (Lst (chop Str) Lst) (case (pop 'Lst) ("\\" (link (pop 'Lst))) ("{" (recur () (let L (make (while ...
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Isabelle
Isabelle
theory Brazilian imports Main begin   function (sequential) base :: "nat ⇒ nat ⇒ nat list" where "base n 0 = undefined" | "base n (Suc 0) = replicate n 1" | "base n b = (if n < b then [n] else (base (n div b) b) @ [n mod b] )" by pat_completeness auto termination base apply(relation "...
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#Gambas
Gambas
Public Sub Main()   Shell "cal 1969"   End
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#Julia
Julia
using Images, FileIO   function main(h::Integer, w::Integer, side::Bool=false) W0 = w >> 1 H0 = h >> 1 @inline function motecolor(x::Integer, y::Integer) h = clamp(180 * (atan2(y - H0, x - W0) / π + 1.0), 0.0, 360.0) return HSV(h, 0.5, 0.5) end   img = zeros(RGB{N0f8}, h, w) img[...
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#EasyLang
EasyLang
dig[] = [ 1 2 3 4 5 6 7 8 9 ] for i range 4 h = i + random (9 - i) swap dig[i] dig[h] . # print dig[] len g[] 4 attempts = 0 repeat repeat ok = 0 s$[] = strchars input if len s$[] = 4 ok = 1 for i range 4 g[i] = number s$[i] if g[i] = 0 ok = 0 . . ...
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#CoffeeScript
CoffeeScript
cipher = (msg, rot) -> msg.replace /([a-z|A-Z])/g, ($1) -> c = $1.charCodeAt(0) String.fromCharCode \ if c >= 97 then (c + rot + 26 - 97) % 26 + 97 else (c + rot + 26 - 65) % 26 + 65   console.log cipher "Hello World", 2 console.log cipher "azAz %^&*()", 3
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
#Nim
Nim
const epsilon : float64 = 1.0e-15 var fact : int64 = 1 var e : float64 = 2.0 var e0 : float64 = 0.0 var n : int64 = 2   while abs(e - e0) >= epsilon: e0 = e fact = fact * n inc(n) e = e + 1.0 / fact.float64   echo 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
#Pascal
Pascal
program Calculating_the_value_of_e; {$IFDEF FPC} {$MODE DELPHI} {$ENDIF}   {$IFDEF WINDOWS} {$APPTYPE CONSOLE} {$ENDIF} uses SysUtils;   const EPSILON = 1.0e-14;   function Get_E: Extended; var recfact: Extended; n: Integer; begin recfact := 1.0; Result := 2.0; n := 2; repeat recfact /= n; i...
http://rosettacode.org/wiki/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#Red
Red
Red []   digits: charset [#"1" - #"9"]  ;; bitset for parse rule in valid function   check: function [s i ][  ;; returns string with bulls -B and cows - C found return sort append copy "" collect [ repeat pos 4 [ either ( v: pick i pos ) = pick s pos [ keep "B"][ if find s v [keep "C"] ] ] ...
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to al...
#Tcl
Tcl
  \146\157\162\145\141\143\150 42 [\151\156\146\157 \143\157\155\155\141\156\144\163] { \145\166\141\154 " \160\162\157\143 [\163\164\162\151\156\147 \164\157\165\160\160\145\162 $42] {\141\162\147\163} \{ \163\145\164 \151 1 \146\157\162\145\141\143\150 \141 \$\141\162\147\163 \{ \151\146 \[\163\164\162\1...
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the...
#zkl
zkl
//-*-c-*- // flf.c, Call a foreign-language function   // export zklRoot=/home/ZKL // clang -O -fPIC -I $zklRoot/VM -c -o flf.o flf.c // clang flf.o -L$zklRoot/Lib -lzkl -shared -Wl,-soname,flf.so -o flf.so   #include <string.h>   #include "zklObject.h" #include "zklMethod.h" #include "zklString.h" #include "zklImport...
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#FreeBASIC
FreeBASIC
  Sub Saludo() Print "Hola mundo!" End Sub   Function Copialo(txt As String, siNo As Short, final As String = "") As String Dim nuevaCadena As String   For cont As Short = 1 To siNo nuevaCadena &= txt Next   Return Trim(nuevaCadena) & final End Function   Sub testNumeros(a As Integer, b ...
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#Wren
Wren
var a = [1, 2, 3, 4, 5] var sum = a.reduce { |acc, i| acc + i } var prod = a.reduce { |acc, i| acc * i } var sumSq = a.reduce { |acc, i| acc + i*i } System.print(a) System.print("Sum is %(sum)") System.print("Product is %(prod)") System.print("Sum of squares is %(sumSq)")
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...
#Logo
Logo
to factorial :n output ifelse [less? :n 1] 1 [product :n factorial difference :n 1] end to choose :n :r output quotient factorial :n product factorial :r factorial difference :n :r end to catalan :n output product (quotient sum :n 1) choose product 2 :n :n end   repeat 15 [print catalan repcount]
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#PowerShell
PowerShell
  function Expand-Braces ( [string]$String ) { $Escaped = $False $Stack = New-Object System.Collections.Stack $ClosedBraces = $BracesToParse = $Null   ForEach ( $i in 0..($String.Length-1) ) { Switch ( $String[$i] ) { '\' { $Escaped = -not $Esc...
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#J
J
  Doc=: conjunction def 'u :: (n"_)'   brazilian=: (1 e. (#@~.@(#.^:_1&>)~ (2 + [: (i.) _3&+)))&> Doc 'brazilian y NB. is 1 if y is brazilian, else 0'   Filter=: (#~`)(`:6)     B=: brazilian Filter 4 + i. 300 NB. gather Brazilion numbers less than 304   20 {. B NB. first 20 Brazilion numbers 7 8 10 ...
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#Go
Go
package main   import ( "fmt" "time" )   const pageWidth = 80   func main() { printCal(1969) }   func printCal(year int) { thisDate := time.Date(year, 1, 1, 1, 1, 1, 1, time.UTC) var ( dayArr [12][7][6]int // month, weekday, week month, lastMonth time.Month weekInMonth, dayInMonth int...
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#Kotlin
Kotlin
// version 1.1.2   import java.awt.Graphics import java.awt.image.BufferedImage import java.util.* import javax.swing.JFrame   class BrownianTree : JFrame("Brownian Tree"), Runnable { private val img: BufferedImage private val particles = LinkedList<Particle>()   private companion object { val ran...
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Eiffel
Eiffel
  class BULLS_AND_COWS   create execute   feature   execute -- Initiate game. do io.put_string ("Let's play bulls and cows.%N") create answer.make_empty play end   feature {NONE}   play -- Plays bulls ans cows. local count, seed: INTEGER guess: STRING do from until seed > 0 ...
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#Commodore_BASIC
Commodore BASIC
1 rem caesar cipher 2 rem rosetta code 10 print chr$(147);chr$(14); 15 input "Enter a key value from 1 to 25";kv 20 if kv<1 or kv>25 then print "Out of range.":goto 15 25 gosub 1000 30 print chr$(147);"Enter a message to translate." 35 print:print "Press CTRL-Z when finished.":print 40 mg$="":gosub 2000 45 print chr$(1...
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
#Perl
Perl
use bignum qw(e);   $e = 2; $f = 1; do { $e0 = $e; $n++; $f *= 2*$n * (1 + 2*$n); $e += (2*$n + 2) / $f; } until ($e-$e0) < 1.0e-39;   print "Computed " . substr($e, 0, 41), "\n"; print "Built-in " . e, "\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
#Phix
Phix
with javascript_semantics atom e0 = 0, e = 2, n = 0, fact = 1 while abs(e-e0)>=1e-15 do e0 = e n += 1 fact *= 2*n*(2*n+1) e += (2*n+2)/fact end while printf(1,"Computed e = %.15f\n",e) printf(1," Real e = %.15f\n",E) printf(1," Error = %g\n",E-e) printf(1,"Number of iterations = %d\n",n)
http://rosettacode.org/wiki/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#REXX
REXX
/*REXX program plays the Bulls & Cows game with CBLFs (Carbon Based Life Forms). */ parse arg ? .; if datatype(?,'W') then call random ,,? /*Random seed? Make repeatable*/ L=1234; H=9876; call gen@ /*generate all possibilities. */ do forever; g=random(L,H); if @.g\==. ...
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to al...
#UNIX_Shell
UNIX Shell
CAL=CAL TR=TR A=A Z=Z LANG=C ${CAL,,} 1969 | ${TR,,} ${A,}-${Z,} A-Z
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Free_Pascal
Free Pascal
Public Sub Main()   Hello Print CopyIt("Hello ", 6) Print CopyIt("Hello ", 3, "!!")   End '_____________________________________________________________________________________ Public Sub CopyIt(sString As String, siNo As Short, Optional sEnd As String) As String Dim siCount As Short Dim sNewString As String   For siCo...
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#zkl
zkl
T("foo","bar").reduce(fcn(p,n){p+n}) //--> "foobar" "123four5".reduce(fcn(p,c){p+(c.matches("[0-9]") and c or 0)}, 0) //-->11 File("foo.zkl").reduce('+(1).fpM("0-"),0) //->5 (lines in file)
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 DIM a(5) 20 FOR i=1 TO 5 30 READ a(i) 40 NEXT i 50 DATA 1,2,3,4,5 60 LET o$="+": GO SUB 1000: PRINT tmp 70 LET o$="-": GO SUB 1000: PRINT tmp 80 LET o$="*": GO SUB 1000: PRINT tmp 90 STOP 1000 REM Reduce 1010 LET tmp=a(1) 1020 FOR i=2 TO 5 1030 LET tmp=VAL ("tmp"+o$+"a(i)") 1040 NEXT i 1050 RETURN
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...
#Lua
Lua
-- recursive with memoization catalan = {[0] = 1} setmetatable(catalan, { __index = function(c, n) c[n] = c[n-1]*2*(2*n-1)/(n+1) return c[n] end } )   for i=0,14 do print(catalan[i]) end
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#Prolog
Prolog
  sym(',', commalist) --> ['\\',','], !. sym(H, Context) --> [H], { not(H = '{'; H = '}'), (Context = commalist -> not(H = ','); true) }. syms([H|T], Context) --> sym(H, Context), !, syms(T, Context). syms([], _) --> []. symbol(Symbol, Context) --> syms(Syms,Context), {atom_chars(Symbol, Syms)}. ...
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Java
Java
import java.math.BigInteger; import java.util.List;   public class Brazilian { private static final List<Integer> primeList = List.of( 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, 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 fo...
#Haskell
Haskell
import qualified Data.Text as T import Data.Time import Data.Time.Calendar import Data.Time.Calendar.WeekDate import Data.List.Split (chunksOf) import Data.List   data Day = Su | Mo | Tu | We | Th | Fr | Sa deriving (Show, Eq, Ord, Enum)   data Month = January | February | March | April | May ...
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#Liberty_BASIC
Liberty BASIC
'[RC]Brownian motion tree nomainwin dim screen(600,600) WindowWidth = 600 WindowHeight = 600 open "Brownian" for graphics_nsb_nf as #1 #1 "trapclose [quit]" #1 "down ; fill blue" rad=57.29577951 particles=500   'draw starting circle and mid point for n= 1 to 360 x...
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Elena
Elena
import system'routines; import extensions;   class GameMaster { object theNumbers; object theAttempt;   constructor() { // generate secret number var randomNumbers := new int[]{1,2,3,4,5,6,7,8,9}.randomize(9);   theNumbers := randomNumbers.Subarray(0, 4); theAttempt := ne...
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...
#Common_Lisp
Common Lisp
(defun encipher-char (ch key) (let* ((c (char-code ch)) (la (char-code #\a)) (ua (char-code #\A)) (base (cond ((<= la c (char-code #\z)) la) ((<= ua c (char-code #\Z)) ua) (nil)))) (if base (code-char (+ (mod (+ (- c base) key) 26) base)) ch)))   (defun caes...
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
#Phixmonti
Phixmonti
0 var e0 2 var e 0 var n 1 var fact 1e-15 var v   def printOp swap print print nl enddef   def test e e0 - abs v >= enddef   test while e var e0 n 1 + var n 2 n * 2 n * 1 + * fact * var fact 2 n * 2 + fact / e + var e test endwhile   2.718281828459045 var rE   "Computed e = " e tostr printOp "Re...
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
#PicoLisp
PicoLisp
(scl 15) (let (F 1 E 2.0 E0 0 N 2) (while (> E E0) (setq E0 E F (* F N)) (inc 'E (*/ 1.0 F)) (inc 'N) ) (prinl "e = " (format E *Scl)) )
http://rosettacode.org/wiki/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#Ring
Ring
  # Project : Bulls and cows/Player   secret = "" while len(secret) != 4 c = char(48 + random(9)) if substr(secret, c) = 0 secret = secret + c ok end see "secret = " + secret + nl   possible = "" for i = 1234 to 9876 possible = possible + string(i) next   see "guess a four-digi...
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to al...
#Vedit_macro_language
Vedit macro language
BS(BF) CFT(22) #3 = 6 // NUMBER OF MONTHS PER LINE #2 = 1969 // YEAR #1 = 1 // STARTING MONTH IC(' ', COUNT, #3*9) IT("[SNOOPY]") IN(2) IC(' ', COUNT, #3*9+1) NI(#2) IN REPEAT(12/#3) { REPEAT (#3) { BS(BF) CALL("DRAW_CALENDAR") RCB(10, 1, EOB_POS, COLSET, 1,...
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Gambas
Gambas
Public Sub Main()   Hello Print CopyIt("Hello ", 6) Print CopyIt("Hello ", 3, "!!")   End '_____________________________________________________________________________________ Public Sub CopyIt(sString As String, siNo As Short, Optional sEnd As String) As String Dim siCount As Short Dim sNewString As String   For siCo...
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...
#MAD
MAD
NORMAL MODE IS INTEGER DIMENSION C(15)   C(0) = 1 THROUGH CALC, FOR N=1, 1, N.GE.15 CALC C(N) = ((4*N-2)*C(N-1))/(N+1)   THROUGH SHOW, FOR N=0, 1, N.GE.15 SHOW PRINT FORMAT CFMT,N,C(N)   VECTOR VALUES CFMT=$2HC(,I2,4H) = ,I7*$ ...
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#Python
Python
def getitem(s, depth=0): out = [""] while s: c = s[0] if depth and (c == ',' or c == '}'): return out,s if c == '{': x = getgroup(s[1:], depth+1) if x: out,s = [a+b for a in out for b in x[0]], x[1] continue if c...
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#jq
jq
# Output: a stream of digits, least significant digit first def to_base($base): def butlast(s): label $out | foreach (s,null) as $x ({}; if $x == null then break $out else .emit = .prev | .prev = $x end; select(.emit).emit);   if . == 0 then 0 else butlast(recurse( if . == 0 then empty els...
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#Huginn
Huginn
import DateTime as dt; import Algorithms as algo; import Text as text;   class Calendar { _monthNames_ = none; _dayNames_ = none; constructor() { t = dt.now(); _monthNames_ = algo.materialize( algo.map( algo.range( 1, 13 ), @[t]( m ) { dt.format( "%B", t.set_date( 1, m, 1 ) ); } ), tuple ); _dayNames_...
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#Locomotive_Basic
Locomotive Basic
10 MODE 1:DEFINT a-z:RANDOMIZE TIME:np=10000 20 INK 0,0:INK 1,26:BORDER 0 30 PLOT 320,200 40 FOR i=1 TO np 50 GOSUB 1000 60 IF TEST(x+1,y+1)+TEST(x,y+1)+TEST(x+1,y)+TEST(x-1,y-1)+TEST(x-1,y)+TEST(x,y-1)<>0 THEN 100 70 x=x+RND*2-1: y=y+RND*2-1 80 IF x<1 OR x>640 OR y<1 OR y>400 THEN GOSUB 1000 90 GOTO 60 100 PLOT x,y 11...
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Elixir
Elixir
defmodule Bulls_and_cows do def play(size \\ 4) do secret = Enum.take_random(1..9, size) |> Enum.map(&to_string/1) play(size, secret) end   defp play(size, secret) do guess = input(size) if guess == secret do IO.puts "You win!" else {bulls, cows} = count(guess, secret) IO.put...
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...
#Crystal
Crystal
class String ALPHABET = ("A".."Z").to_a   def caesar_cipher(num) self.tr(ALPHABET.join, ALPHABET.rotate(num).join) end end   # demo encrypted = "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG".caesar_cipher(5) decrypted = encrypted.caesar_cipher(-5)  
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
#PowerShell
PowerShell
$e0 = 0 $e = 2 $n = 0 $fact = 1 while([Math]::abs($e-$e0) -gt 1E-15){ $e0 = $e $n += 1 $fact *= 2*$n*(2*$n+1) $e += (2*$n+2)/$fact }   Write-Host "Computed e = $e" Write-Host " Real e = $([Math]::Exp(1))" Write-Host " Error = $([Math]::Exp(1) - $e)" Write-Host "Number of iterations = $n"
http://rosettacode.org/wiki/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#Ruby
Ruby
size = 4 scores = [] guesses = [] puts "Playing Bulls & Cows with #{size} unique digits." possible_guesses = [*'1'..'9'].permutation(size).to_a.shuffle   loop do guesses << current_guess = possible_guesses.pop print "Guess #{guesses.size} is #{current_guess.join}. Answer (bulls,cows)? " scores << score = gets.spl...
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to al...
#Visual_Basic_.NET
Visual Basic .NET
OPTION COMPARE BINARY OPTION EXPLICIT ON OPTION INFER ON OPTION STRICT ON   IMPORTS SYSTEM.GLOBALIZATION IMPORTS SYSTEM.TEXT IMPORTS SYSTEM.RUNTIME.INTEROPSERVICES IMPORTS SYSTEM.RUNTIME.COMPILERSERVICES   MODULE ARGHELPER READONLY _ARGDICT AS NEW DICTIONARY(OF STRING, STRING)()   DELEGATE FUNCTION TRYPARSE(OF ...
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Go
Go
noArgs()
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...
#Maple
Maple
CatalanNumbers := proc( n::posint ) return seq( (2*i)!/((i + 1)!*i!), i = 0 .. n - 1 ); end proc: CatalanNumbers(15);  
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#Racket
Racket
#lang racket/base (require racket/match) (define (merge-lists as . bss) (match bss ['() as] [(cons b bt) (apply merge-lists (for*/list ((a (in-list as)) (b (in-list b))) (append a b)) bt)]))   (define (get-item cs depth) (let loop ((out '(())) (cs cs)) (match cs ['() (...
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#Raku
Raku
grammar BraceExpansion { token TOP { ( <meta> | . )* } token meta { '{' <alts> '}' | \\ . } token alts { <alt>+ % ',' } token alt { ( <meta> | <-[ , } ]> )* } }   sub crosswalk($/) { |[X~] flat '', $0.map: -> $/ { $<meta><alts><alt>.&alternatives or ~$/ } }   sub alternatives($_) { when :not ...
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Julia
Julia
using Primes, Lazy   function samedigits(n, b) n, f = divrem(n, b) while n > 0 n, f2 = divrem(n, b) if f2 != f return false end end true end   isbrazilian(n) = n >= 7 && (iseven(n) || any(b -> samedigits(n, b), 2:n-2)) brazilians = filter(isbrazilian, Lazy.range()) od...
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) printCalendar(\A[1]|1969) end   procedure printCalendar(year) #: Print a 3 column x 80 char calendar cols := 3 # fixed width mons := [] # table of months "January February March April May June " || ...
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#Lua
Lua
function SetSeed( f ) for i = 1, #f[1] do -- the whole boundary of the scene is used as the seed f[1][i] = 1 f[#f][i] = 1 end for i = 1, #f do f[i][1] = 1 f[i][#f[1]] = 1 end end   function SetParticle( f ) local pos_x, pos_y repeat pos_x = ma...
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Erlang
Erlang
-module(bulls_and_cows). -export([generate_secret/0, score_guess/2, play/0]).   % generate the secret code generate_secret() -> generate_secret([], 4, lists:seq(1,9)). generate_secret(Secret, 0, _) -> Secret; generate_secret(Secret, N, Digits) -> Next = lists:nth(random:uniform(length(Digits)), Digits), generate_se...
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...
#Cubescript
Cubescript
alias modn [ mod (+ (mod $arg1 $arg2) $arg2) $arg2 ] //Cubescript's built-in mod will fail on negative numbers   alias cipher [ push alpha [ "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" "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" ] [ push chars [] [ loop i (strlen $arg1) [ looplist n $alph...
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
#Processing
Processing
void setup() { double e = 0; long factorial = 1; for (int i = 0; i < 11; i++) { e += (double) (2 * i + 1) / factorial; factorial *= (2 * i + 1) * (2 * i + 2); } println("After 11 iterations"); println("Computed value: " + e); println("Real value: " + Math.E); println("Error: " + (e - Math.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
#Prolog
Prolog
  % Calculate the value e = exp 1 % Use Newton's method: x0 = 2; y = x(2 - ln x)   tolerance(1e-15).   exp1_iter(L) :- lazy_list(newton, 2, L).   newton(X0, X1, X1) :- X1 is X0*(2 - log(X0)).   e([X1, X2|_], X1) :- tolerance(Eps), abs(X2 - X1) < Eps. e([_|Xs], E) :- e(Xs, E).   main :- exp1_iter(Iter), ...
http://rosettacode.org/wiki/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#Scala
Scala
  def allCombinations: Seq[List[Byte]] = { (0 to 9).map(_.byteValue).toList.combinations(4).toList.flatMap(_.permutations) }   def nextGuess(possible: Seq[List[Byte]]): List[Byte] = possible match { case Nil => throw new IllegalStateException case List(only) => only case _ => possib...
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to al...
#Wren
Wren
IMPORT "/DATE" FOR DATE IMPORT "/FMT" FOR FMT IMPORT "/SEQ" FOR LST   VAR CALENDAR = FN.NEW { |YEAR| VAR SNOOPY = "🐶" VAR DAYS = "SU MO TU WE TH FR SA" VAR MONTHS = [ "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" ...
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Groovy
Groovy
noArgs()
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
CatalanN[n_Integer /; n >= 0] := (2 n)!/((n + 1)! n!)
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#REXX
REXX
/*- REXX -------------------------------------------------------------- * Brace expansion * 26.07.2016 * s.* holds the set of strings *--------------------------------------------------------------------*/ text.1='{,{,gotta have{ ,\, again\, }}more }cowbell!' text.2='~/{Downloads,Pictures}/*.{jpg,gif,png}' text.3='It{{...
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Kotlin
Kotlin
fun sameDigits(n: Int, b: Int): Boolean { var n2 = n val f = n % b while (true) { n2 /= b if (n2 > 0) { if (n2 % b != f) { return false } } else { break } } return true }   fun isBrazilian(n: Int): Boolean { if (...
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#J
J
require 'dates format' NB. J6.x require 'dates general/misc/format' NB. J7.x calBody=: (1 1 }. _1 _1 }. ":)@(-@(<.@%&22)@[ ]\ calendar@]) calTitle=: (<: - 22&|)@[ center '[Insert Snoopy here]' , '' ,:~ ":@] formatCalendar=: calTitle , calBody
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
canvasdim = 1000; n = 0.35*canvasdim^2; canvas = ConstantArray[0, {canvasdim, canvasdim}]; init = Floor@(0.5*{canvasdim, canvasdim}); (*RandomInteger[canvasdim,2]*) canvas[[init[[1]], init[[2]]]] = 1; (*1st particle initialized to midpoint*)   Monitor[ (*Provides real-time in...
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#Euphoria
Euphoria
include std\text.e include std\os.e include std\sequence.e include std\console.e   sequence bcData = {0,0} --bull,cow score for the player sequence goalNum = { {0,0,0,0}, {0,0,0,0}, 0} --computer's secret number digits (element 1), marked as bull/cow --indexes in element 2, integer value of it in element 3 sequence cur...
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...
#D
D
import std.stdio, std.traits;   S rot(S)(in S s, in int key) pure nothrow @safe if (isSomeString!S) { auto res = s.dup;   foreach (immutable i, ref c; res) { if ('a' <= c && c <= 'z') c = ((c - 'a' + key) % 26 + 'a'); else if ('A' <= c && c <= 'Z') c = ((c - 'A' + 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
#PureBasic
PureBasic
Define f.d=1.0, e.d=1.0, e0.d=e, n.i=1 LOOP: f*n : e+1.0/f If e-e0>=1.0e-15 : e0=e : n+1 : Goto LOOP : EndIf Debug "e="+StrD(e,15)
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
#Python
Python
import math #Implementation of Brother's formula e0 = 0 e = 2 n = 0 fact = 1 while(e-e0 > 1e-15): e0 = e n += 1 fact *= 2*n*(2*n+1) e += (2.*n+2)/fact   print "Computed e = "+str(e) print "Real e = "+str(math.e) print "Error = "+str(math.e-e) print "Number of iterations = "+str(n)
http://rosettacode.org/wiki/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#SenseTalk
SenseTalk
set the remoteWorkInterval to .001 -- optional repeat forever repeat forever set description to "Enter a 4 digit number" & newline & "- zero's excluded" & newline & "- each digit should be unique" & newline Ask "Enter a Number" title "Bulls & Cows (Player)" message description put it into num if num is "" A...
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to al...
#X86_Assembly
X86 Assembly
.MODEL TINY .CODE .486 ORG 100H ;.COM FILES START HERE YEAR EQU 1969 ;DISPLAY CALENDAR FOR SPECIFIED YEAR START: MOV CX, 61 ;SPACE(61); TEXT(0, "[SNOOPY]"); CRLF(0) CALL SPACE MOV DX, OFFSET SNOOPY CALL T...
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Haskell
Haskell
  -- Calling a function with a fixed number of arguments multiply x y = x * y multiply 10 20 -- returns 200   -- Calling a function that requires no arguments -- Normally, you use constant instead of function without arguments: twopi = 6.28 -- But you can also pass special value as the first argument indicating functio...
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...
#MATLAB_.2F_Octave
MATLAB / Octave
function n = catalanNumber(n) for i = (1:length(n)) n(i) = (1/(n(i)+1))*nchoosek(2*n(i),n(i)); end end
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#Ruby
Ruby
def getitem(s, depth=0) out = [""] until s.empty? c = s[0] break if depth>0 and (c == ',' or c == '}') if c == '{' and x = getgroup(s[1..-1], depth+1) out = out.product(x[0]).map{|a,b| a+b} s = x[1] else s, c = s[1..-1], c + s[1] if c == '\\' and s.size > 1 out, s = out.map...
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Lua
Lua
function sameDigits(n,b) local f = n % b n = math.floor(n / b) while n > 0 do if n % b ~= f then return false end n = math.floor(n / b) end return true end   function isBrazilian(n) if n < 7 then return false end if (n % 2 == 0) and (n >= 8) th...
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#Java
Java
import java.text.*; import java.util.*;   public class CalendarTask {   public static void main(String[] args) { printCalendar(1969, 3); }   static void printCalendar(int year, int nCols) { if (nCols < 1 || nCols > 12) throw new IllegalArgumentException("Illegal column width."); ...