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...
#Elena
Elena
  var c0 := { console.writeLine("No argument provided") }; var c2 := (int a, int b){ console.printLine("Arguments ",a," and ",b," provided") };  
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: ...
#Scala
Scala
object Main extends App { val a = Seq(1, 2, 3, 4, 5) println(s"Array  : ${a.mkString(", ")}") println(s"Sum  : ${a.sum}") println(s"Difference  : ${a.reduce { (x, y) => x - y }}") println(s"Product  : ${a.product}") println(s"Minimum  : ${a.min}") println(s"Maximum  : ${a.max}") }
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...
#Swift
Swift
func + <T>(el: T, arr: [T]) -> [T] { var ret = arr   ret.insert(el, at: 0)   return ret }   func cartesianProduct<T>(_ arrays: [T]...) -> [[T]] { guard let head = arrays.first else { return [] }   let first = Array(head)   func pel( _ el: T, _ ll: [[T]], _ a: [[T]] = [] ) -> [[T]] { ...
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...
#Java
Java
  import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;   public class CatlanNumbers {   public static void main(String[] args) { Catlan f1 = new Catlan1(); Catlan f2 = new Catlan2(); Catlan f3 = new Catlan3(); ...
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...
#Julia
Julia
function getitem(s, depth=0) out = [""] while s != "" c = s[1] if depth > 0 && (c == ',' || c == '}') return out, s elseif c == '{' x = getgroup(s[2:end], depth+1) if x != "" out, s = [a * b for a in out, b in x[1]], x[2] ...
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...
#Kotlin
Kotlin
// version 1.1.2   object BraceExpansion { fun expand(s: String) = expandR("", s, "")   private val r = Regex("""([\\]{2}|[\\][,}{])""")   private fun expandR(pre: String, s: String, suf: String) { val noEscape = s.replace(r, " ") var sb = StringBuilder("") var i1 = noEscape.indexOf...
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...
#F.C5.8Drmul.C3.A6
Fōrmulæ
: prime? ( n -- flag ) dup 2 < if drop false exit then dup 2 mod 0= if 2 = exit then dup 3 mod 0= if 3 = exit then 5 begin 2dup dup * >= while 2dup mod 0= if 2drop false exit then 2 + 2dup mod 0= if 2drop false exit then 4 + repeat 2drop true ;   : same_digits? ( n b -- ? ) 2dup mo...
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...
#D
D
import std.stdio, std.datetime, std.string, std.conv;   void printCalendar(in uint year, in uint nCols) in { assert(nCols > 0 && nCols <= 12); } body { immutable rows = 12 / nCols + (12 % nCols != 0); auto date = Date(year, 1, 1); int offs = date.dayOfWeek; const months = "January February March Apr...
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...
#Gnuplot
Gnuplot
  ## plotff.gp 11/27/16 aev ## Plotting from any data-file with 2 columns (space delimited), and writing to png-file. ## Especially useful to plot colored fractals using points. ## Note: assign variables: clr, filename and ttl (before using load command). reset set terminal png font arial 12 size 640,640 ofn=filename....
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...
#CLU
CLU
% This program needs to be merged with PCLU's "misc" library % to use the random number generator. % % pclu -merge $CLUHOME/lib/misc.lib -compile bulls_cows.clu   % Seed the random number generator with the current time init_rng = proc () d: date := now() seed: int := ((d.hour*60) + d.minute)*60 + d.second ...
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform
Burrows–Wheeler transform
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Burrows–Wheeler transform (BWT, also called block-s...
#zkl
zkl
class BurrowsWheelerTransform{ fcn init(chr="$"){ var special=chr; } fcn encode(str){ _assert_(not str.holds(special), "String cannot contain char \"%s\"".fmt(special) ); str=str.append(special); str.len().pump(List().merge,'wrap(n){ String(str[n,*],str[0,n]) }) .pump(String,T("get",-1)); ...
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#BQN
BQN
o ← @‿'A'‿@‿'a'‿@ ⋄ m ← 5⥊↕2 ⋄ p ← m⊏∞‿26 Rot ← {i←⊑"A[a{"⍋𝕩 ⋄ i⊑o+p|(𝕨×m)+𝕩-o}⎉0
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#K
K
  / Computing value of e / ecomp.k \p 17 fact: {*/1+!:x} evalue:{1 +/(1.0%)'fact' 1+!20} evalue[]  
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
#Klingphix
Klingphix
%e0 %e %n %fact %v   0 !e0 2 !e 0 !n 1 !fact 1e-15 !v   :printOp swap print print nl ; :test $e $e0 - abs $v >= ;   [$e !e0 $n 1 + !n 2 $n * 2 $n * 1 + * $fact * !fact 2 $n * 2 + $fact / $e + !e] [test] while   %rE 2.718281828459045 !rE   "Computed e = " $e tostr printOp "Real e = " $rE tostr printOp "Error = " $r...
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...
#PicoLisp
PicoLisp
(load "@lib/simul.l")   (de bullsAndCows () (let Choices (shuffle (mapcan permute (subsets 4 (range 1 9)))) (use (Guess Bulls Cows) (loop (prinl "Guessing " (setq Guess (pop 'Choices))) (prin "How many bulls and cows? ") (setq Bulls (read) Cows (read)) ...
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...
#Racket
Racket
  #CI(MODULE NAME-OF-THIS-FILE RACKET (REQUIRE RACKET/DATE) (DEFINE (CALENDAR YR) (DEFINE (NSPLIT N L) (IF (NULL? L) L (CONS (TAKE L N) (NSPLIT N (DROP L N))))) (DEFINE MONTHS (FOR/LIST ([MN (IN-NATURALS 1)] [MNAME '(JANUARY FEBRUARY MARCH APRIL MAY JUNE JULY AUGUST SEPTEM...
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...
#Raku
Raku
use NativeCall;   sub strdup(Str $s --> Pointer) is native {*} sub puts(Pointer $p --> int32) is native {*} sub free(Pointer $p --> int32) is native {*}   my $p = strdup("Success!"); say 'puts returns ', puts($p); say 'free returns ', free($p);
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...
#REALbasic
REALbasic
  Declare Function CreateFileW Lib "Kernel32" (FileName As WString, DesiredAccess As Integer, ShareMode As Integer, SecurityAttributes As Integer, _ CreateDisposition As Integer, Flags As Integer, Template As Integer) As Integer Declare Function WriteFile Lib "Kernel32" (fHandle As Integer, writeData As Ptr...
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...
#Elixir
Elixir
  # Anonymous function   foo = fn() -> IO.puts("foo") end   foo() #=> undefined function foo/0 foo.() #=> "foo"   # Using `def`   defmodule Foo do def foo do IO.puts("foo") end end   Foo.foo #=> "foo" Foo.foo() #=> "foo"     # Calling a function with a fixed number of arguments   defmodule Foo do def f...
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: ...
#Scheme
Scheme
(define (reduce fn init lst) (do ((val init (fn (car rem) val)) ; accumulated value passed as second argument (rem lst (cdr rem))) ((null? rem) val)))   (display (reduce + 0 '(1 2 3 4 5))) (newline) ; => 15 (display (reduce expt 2 '(3 4))) (newline) ; => 262144
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...
#Tailspin
Tailspin
  '{1,2}x{3,4} = $:[by [1,2]..., by [3,4]...]; ' -> !OUT::write   '{3,4}x{1,2} = $:[by [3,4]..., by [1,2]...]; ' -> !OUT::write   '{1,2}x{} = $:[by [1,2]..., by []...]; ' -> !OUT::write   '{}x{1,2} = $:[by []..., by [1,2]...]; ' -> !OUT::write   '{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1} = $:[by [1776, 1789]..., by...
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...
#JavaScript
JavaScript
<html><head><title>Catalan</title></head> <body><pre id='x'></pre><script type="application/javascript"> function disp(x) { var e = document.createTextNode(x + '\n'); document.getElementById('x').appendChild(e); }   var fc = [], c2 = [], c3 = []; function fact(n) { return fc[n] ? fc[n] : fc[n] = (n ? n * fact(n - 1) ...
http://rosettacode.org/wiki/Brace_expansion
Brace expansion
Brace expansion is a type of parameter expansion made popular by Unix shells, where it allows users to specify multiple similar string parameters without having to type them all out. E.g. the parameter enable_{audio,video} would be interpreted as if both enable_audio and enable_video had been specified. Task[edit] W...
#Lua
Lua
local function wrapEachItem(items, prefix, suffix) local itemsWrapped = {}   for i, item in ipairs(items) do itemsWrapped[i] = prefix .. item .. suffix end   return itemsWrapped end   local function getAllItemCombinationsConcatenated(aItems, bItems) local combinations = {}   for _, a in ipairs(aItems) do for ...
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...
#Forth
Forth
: prime? ( n -- flag ) dup 2 < if drop false exit then dup 2 mod 0= if 2 = exit then dup 3 mod 0= if 3 = exit then 5 begin 2dup dup * >= while 2dup mod 0= if 2drop false exit then 2 + 2dup mod 0= if 2drop false exit then 4 + repeat 2drop true ;   : same_digits? ( n b -- ? ) 2dup mo...
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...
#Delphi
Delphi
  program Calendar;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.DateUtils;   function Center(s: string; width: Integer): string; var side: Integer; begin if s.Length >= width then exit(s); side := (width - s.Length) div 2; Result := s + string.Create(' ', side); Result := string.Create(' ', wi...
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...
#Go
Go
package main   import ( "fmt" "image" "image/color" "image/png" "math/rand" "os" )   const w = 400 // image width const h = 300 // image height const n = 15000 // number of particles to add const frost = 255 // white   var g *image.Gray   func main() { g = image.NewGray(image.Recta...
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...
#Coco
Coco
say = print prompt = (str) -> putstr str readline! ? quit!
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...
#Brainf.2A.2A.2A
Brainf***
Author: Ettore Forigo | Hexwell   + start the key input loop [ memory: | c | 0 | cc | key | ^   , take one character of the 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
#Kotlin
Kotlin
// Version 1.2.40   import kotlin.math.abs   const val EPSILON = 1.0e-15   fun main(args: Array<String>) { var fact = 1L var e = 2.0 var n = 2 do { val e0 = e fact *= n++ e += 1.0 / fact } while (abs(e - e0) >= EPSILON) println("e = %.15f".format(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
#Lambdatalk
Lambdatalk
  1) straightforward   {+ 1 {S.map {lambda {:n} {/ 1 {* {S.serie 1 :n}}}} {S.serie 1 17}}} -> 2.7182818284590455   which is the value given by javascript : 2.718281828459045.   2) using recursion   {def fac {lambda {:a :b} {if {< :b 1} then :a else {fac {* :a :b} {- :b 1}}}}} -> fac   {def euler {lambda {:a :...
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...
#Prolog
Prolog
:- module('ia.pl', [tirage/1]). :- use_module(library(clpfd)).   % to store the previous guesses and the answers :- dynamic guess/2.   % parameters of the engine   % length of the guess proposition(4).   % Numbers of digits % 0 -> 8 digits(8).     % tirage(-) tirage(Ms) :- % are there previous guesses ? ( bagof([P, ...
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...
#Raku
Raku
$_="\0".."~";< 115 97 121 32 34 91 73 78 83 69 82 84 32 83 78 79 79 80 89 32 72 69 82 69 93 34 59 114 117 110 32 60 99 97 108 62 44 64 42 65 82 71 83 91 48 93 47 47 49 57 54 57 >."$_[99]$_[104]$_[114]$_[115]"()."$_[69]$_[86]$_[65]$_[76]"()
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...
#REXX
REXX
/*REXX program calls (invoke) a "foreign" (non-REXX) language routine/program. */   cmd = "MODE" /*define the command that is to be used*/ opts= 'CON: CP /status' /*define the options to be used for cmd*/   address 'SYSTEM' cmd opts ...
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...
#Ruby
Ruby
/* rc_strdup.c */ #include <stdlib.h> /* free() */ #include <string.h> /* strdup() */ #include <ruby.h>   static VALUE rc_strdup(VALUE obj, VALUE str_in) { VALUE str_out; char *c, *d;   /* * Convert Ruby value to C string. May raise TypeError if the * value isn't a string, or ArgumentError if...
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...
#Erlang
Erlang
  no_argument() one_argument( Arg ) optional_arguments( Arg, [{opt1, Opt1}, {another_opt, Another}] ) variable_arguments( [Arg1, Arg2 | Rest] ) names_arguments([{name1, Arg1}, {another_name, Another}] ) % Statement context? % First class context? Result = obtain_result( Arg1 ) % No way to distinguish builtin/user funct...
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: ...
#Sidef
Sidef
say (1..10 -> reduce('+')); say (1..10 -> reduce{|a,b| a + b});
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...
#Tcl
Tcl
  proc cartesianProduct {l1 l2} { set result {} foreach el1 $l1 { foreach el2 $l2 { lappend result [list $el1 $el2] } } return $result }   puts "simple" puts "result: [cartesianProduct {1 2} {3 4}]" puts "result: [cartesianProduct {3 4} {1 2}]" puts "result: [cartesianProduct {1 2} {}]" puts "resu...
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...
#jq
jq
def catalan: if . == 0 then 1 elif . < 0 then error("catalan is not defined on \(.)") else (2 * (2*. - 1) * ((. - 1) | catalan)) / (. + 1) 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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
(*The strategy is to first capture all special sub-expressions and reformat them so they are semantically clear. The built in function Distribute could then do the work of creating the alternatives, but the order wouldn't match that given in the instructions (although as a set the alternatives would be correct). I'll t...
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...
#Fortran
Fortran
  !Constructs a sieve of Brazilian numbers from the definition. !From the Algol W algorithm, somewhat "Fortranized" PROGRAM BRAZILIAN IMPLICIT NONE ! ! PARAMETER definitions ! INTEGER , PARAMETER :: MAX_NUMBER = 2000000 , NUMVARS = 20 ! ! Local variables ! LOGICAL , DIMENSION(1:MAX_NUMBER) ::...
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...
#F.23
F#
let getCalendar year = let day_of_week month year = let t = [|0; 3; 2; 5; 0; 3; 5; 1; 4; 6; 2; 4|] let y = if month < 3 then year - 1 else year let m = month let d = 1 (y + y / 4 - y / 100 + y / 400 + t.[m - 1] + d) % 7 //0 = Sunday, 1 = Monday, ...   let last_da...
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...
#Haskell
Haskell
import Control.Monad import Control.Monad.ST import Data.STRef import Data.Array.ST import System.Random import Bitmap import Bitmap.BW import Bitmap.Netpbm   main = do g <- getStdGen (t, _) <- stToIO $ drawTree (50, 50) (25, 25) 300 g writeNetpbm "/tmp/tree.pbm" t   drawTree :: (Int, Int) -> (Int, Int) -> ...
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...
#Common_Lisp
Common Lisp
(defun get-number () (do ((digits '())) ((>= (length digits) 4) digits) (pushnew (1+ (random 9)) digits)))   (defun compute-score (guess number) (let ((cows 0) (bulls 0)) (map nil (lambda (guess-digit number-digit) (cond ((= guess-digit number-digit) (incf bulls)) ...
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h>   #define caesar(x) rot(13, x) #define decaesar(x) rot(13, x) #define decrypt_rot(x, y) rot((26-x), y)   void rot(int c, char *str) { int l = strlen(str);   const char* alpha_low = "abcdefghijklmnopqrstuvwxyz";   const cha...
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
#langur
langur
mode divMaxScale = 104   val .epsilon = 1.0e-104   var .e = 2   for .fact, .n = 1, 2 ; ; .n += 1 { val .e0 = .e .fact x= .n .e += 1 / .fact if abs(.e - .e0) < .epsilon: break }   writeln ".e = ", .e   # compare to built-in constant e writeln " e = ", e
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Lua
Lua
EPSILON = 1.0e-15;   fact = 1 e = 2.0 e0 = 0.0 n = 2   repeat e0 = e fact = fact * n n = n + 1 e = e + 1.0 / fact until (math.abs(e - e0) < EPSILON)   io.write(string.format("e = %.15f\n", e))
http://rosettacode.org/wiki/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#PureBasic
PureBasic
#answerSize = 4 Structure history answer.s bulls.i cows.i EndStructure   Procedure evaluateGuesses(*answer.history, List remainingGuesses.s()) Protected i, cows, bulls   ForEach remainingGuesses() bulls = 0: cows = 0 For i = 1 To #answerSize If Mid(remainingGuesses(), i, 1) = Mid(*answer\answer...
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...
#REXX
REXX
/*REXX PROGRAM TO SHOW ANY YEAR'S (MONTHLY) CALENDAR (WITH/WITHOUT GRID)*/ @ABC= PARSE VALUE SCRSIZE() WITH SD SW . DO J=0 TO 255;_=D2C(J);IF DATATYPE(_,'L') THEN @ABC=@ABC||_;END @ABCU=@ABC; UPPER @ABCU DAYS_='SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY' MONTHS_='JANUARY FEBRUARY MARCH APRIL MAY JUNE J...
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the...
#Rust
Rust
extern crate libc;   //c function that returns the sum of two integers extern { fn add_input(in1: libc::c_int, in2: libc::c_int) -> libc::c_int; }   fn main() { let (in1, in2) = (5, 4); let output = unsafe { add_input(in1, in2) }; assert!( (output == (in1 + in2) ),"Error in sum calculation") ; }
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...
#Scala
Scala
object JNIDemo { try System.loadLibrary("JNIDemo")   private def callStrdup(s: String)   println(callStrdup("Hello World!")) }
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...
#F.23
F#
// No arguments noArgs()   // Fixed number of arguments oneArg x   // Optional arguments // In a normal function: optionalArgs <| Some(5) <| None // In a function taking a tuple: optionalArgsInTuple(Some(5), None) // In a function in a type: foo.optionalArgs 5;; // However, if you want to pass more than one paramter, t...
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: ...
#Standard_ML
Standard ML
- val nums = [1,2,3,4,5,6,7,8,9,10]; val nums = [1,2,3,4,5,6,7,8,9,10] : int list - val sum = foldl op+ 0 nums; val sum = 55 : int - val product = foldl op* 1 nums; val product = 3628800 : int
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...
#UNIX_Shell
UNIX Shell
$ printf '%s' "("{1,2},{3,4}")"; printf '\n' (1,3)(1,4)(2,3)(2,4) $ printf '%s' "("{3,4},{1,2}")"; printf '\n' (3,1)(3,2)(4,1)(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...
#Julia
Julia
catalannum(n::Integer) = binomial(2n, n) ÷ (n + 1)   @show catalannum.(1:15) @show catalannum(big(100))
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...
#Nim
Nim
proc expandBraces(str: string) =   var escaped = false depth = 0 bracePoints: seq[int] bracesToParse: seq[int]   for idx, ch in str: case ch of '\\': escaped = not escaped of '{': inc depth if not escaped and depth == 1: bracePoints = @[idx] of ',': if...
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...
#FreeBASIC
FreeBASIC
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 Wend Return True End Function   Function isBrazilian(Byval n As Integer) As Boolean If n < 7 Then Return False If n Mod 2...
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...
#Factor
Factor
USING: arrays calendar.format grouping io.streams.string kernel math.ranges prettyprint sequences sequences.interleaved ; IN: rosetta-code.calendar   : calendar ( year -- ) 12 [1,b] [ 2array [ month. ] with-string-writer ] with map 3 <groups> [ " " <interleaved> ] map 5 " " <repetition> <interleaved> simp...
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...
#Icon_and_Unicon
Icon and Unicon
link graphics,printf   procedure main() # brownian tree   Density := .08 # % particles to area SeedArea := .5 # central area to confine seed ParticleArea := .7 # central area to exclude particles appearing Height := Width := 400 # canvas   Particles := Height * Wi...
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...
#Crystal
Crystal
size = 4 secret = ('1'..'9').to_a.sample(size) guess = [] of Char   i = 0 loop do i += 1 loop do print "Guess #{i}: " guess = gets.not_nil!.chomp.chars exit if guess.empty?   break if guess.size == size && guess.all? { |x| ('1'..'9').includes? x } && guess.uniq.size == size...
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...
#C.23
C#
using System; using System.Linq;   namespace CaesarCypher { class Program { static char Encrypt(char ch, int code) { if (!char.IsLetter(ch)) return ch;   char offset = char.IsUpper(ch) ? 'A' : 'a'; return (char)((ch + code - offset) % 26 + offset); }  ...
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
#M2000_Interpreter
M2000 Interpreter
  Module FindE { Function comp_e (n){ \\ max 28 for decimal (in one line with less spaces) n/=28:For i=27to 1:n=1+n/i:Next i:=n } Clipboard Str$(comp_e(1@),"")+" Decimal"+{ }+Str$(comp_e(1),"")+" Double"+{ }+Str$(comp_e(1~),"")+" Float"+{ }+Str$(comp_e(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
#Maple
Maple
evalf[50](add(1/n!,n=0..100)); # 2.7182818284590452353602874713526624977572470937000   evalf[50](exp(1)); # 2.7182818284590452353602874713526624977572470937000
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...
#Python
Python
from itertools import permutations from random import shuffle   try: raw_input except: raw_input = input try: from itertools import izip except: izip = zip   digits = '123456789' size = 4   def parse_score(score): score = score.strip().split(',') return tuple(int(s.strip()) for s in score)   def...
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...
#Ring
Ring
  # PROJECT : CALENDAR - FOR "REAL" PROGRAMMERS # DATE  : 2018/06/28 # AUTHOR : GAL ZSOLT (~ CALMOSOFT ~) # EMAIL  : <CALMOSOFT@GMAIL.COM>   LOAD "GUILIB.RING" LOAD "STDLIB.RING"   NEW QAPP { WIN1 = NEW QWIDGET() { DAY = LIST(12) POS = NEWLIST(12,37) ...
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...
#Smalltalk
Smalltalk
Object subclass:'CallDemo'! !CallDemo class methods! strdup:arg <cdecl: mustFree char* 'strdup' (char*) module:'libc'> ! !   Transcript showCR:( CallDemo strdup:'Hello' )
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...
#Stata
Stata
#include <stdlib.h> #include "stplugin.h"   STDLL stata_call(int argc, char *argv[]) { int i, j, n = strtol(argv[1], NULL, 0);   for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { // Don't forget array indices are 1-based in Stata. SF_mat_store(argv[0], i, j, 1.0/(double)(i+j-...
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...
#Factor
Factor
foo
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: ...
#Swift
Swift
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]   print(nums.reduce(0, +)) print(nums.reduce(1, *)) print(nums.reduce("", { $0 + String($1) }))
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: ...
#Tailspin
Tailspin
  [1..5] -> \(@: $(1); $(2..last)... -> @: $@ + $; $@!\) -> '$; ' -> !OUT::write [1..5] -> \(@: $(1); $(2..last)... -> @: $@ - $; $@!\) -> '$; ' -> !OUT::write [1..5] -> \(@: $(1); $(2..last)... -> @: $@ * $; $@!\) -> '$; ' -> !OUT::write  
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...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Runtime.CompilerServices   Module Module1   <Extension()> Function CartesianProduct(Of T)(sequences As IEnumerable(Of IEnumerable(Of T))) As IEnumerable(Of IEnumerable(Of T)) Dim emptyProduct As IEnumerable(Of IEnumerable(Of T)) = {Enumerable.Empty(Of T)} Return sequences.Aggregat...
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...
#K
K
catalan: {_{*/(x-i)%1+i:!y-1}[2*x;x+1]%x+1} catalan'!:15 1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440
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...
#Perl
Perl
sub brace_expand { my $input = shift; my @stack = ([my $current = ['']]);   while ($input =~ /\G ((?:[^\\{,}]++ | \\(?:.|\z))++ | . )/gx) { if ($1 eq '{') { push @stack, [$current = ['']]; } elsif ($1 eq ',' && @stack > 1) { push @{$stack[-1]}, ($current = [''...
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...
#Go
Go
package main   import "fmt"   func sameDigits(n, b int) bool { f := n % b n /= b for n > 0 { if n%b != f { return false } n /= b } return true }   func isBrazilian(n int) bool { if n < 7 { return false } if n%2 == 0 && n >= 8 { return t...
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...
#Fortran
Fortran
  MODULE DATEGNASH !Assorted vexations. Time and calendar games, with local flavourings added.   TYPE DateBag !Pack three parts into one. INTEGER DAY,MONTH,YEAR !The usual suspects. END TYPE DateBag !Simple enough.   CHARACTER*9 MONTHNAME(12),DAYNAME(0:6) !Re-interpretations. ...
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...
#J
J
brtr=:4 :0 seed=. ?x clip=. 0 >. (<:x) <."1 ] near=. [: clip +"1/&(,"0/~i:1) p=.i.0 2 mask=. 1 (<"1 near seed)} x$0 field=.1 (<seed)} x$0 for.i.y do. p=. clip (p +"1 <:?3$~$p),?x b=.(<"1 p) { mask fix=. b#p if.#fix do. NB. if. works around j602 bug: 0(0#a:)}i.0 0 p=. (-.b)# p m...
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...
#D
D
void main() { import std.stdio, std.random, std.string, std.algorithm, std.range, std.ascii;   immutable hidden = "123456789"d.randomCover.take(4).array; while (true) { "Next guess: ".write; const d = readln.strip.array.sort().release; if (d.count == 4 && d.all!isDigit && ...
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...
#C.2B.2B
C++
#include <string> #include <iostream> #include <algorithm> #include <cctype>   class MyTransform { private : int shift ; public : MyTransform( int s ) : shift( s ) { }   char operator( )( char c ) { if ( isspace( c ) ) return ' ' ; else { static std::string letters( "abcdefghijklmnopqrstuvwxy...
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
1+Fold[1.+#1/#2&,1,Range[10,2,-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
#min
min
(:n (n 0 ==) ((0)) (-1 () ((succ dup) dip append) n times) if) :iota (iota 'succ '* map-reduce) :factorial   20 iota (factorial 1 swap /) '+ map-reduce print
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...
#R
R
bullsAndCowsPlayer <- function() { guesses <- 1234:9876 #The next line is terrible code, but it's the most R way to convert a set of 4-digit numbers to their 4 digits. guessDigits <- t(sapply(strsplit(as.character(guesses), ""), as.integer)) validGuesses <- guessDigits[apply(guessDigits, 1, function(x) length(u...
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...
#Ruby
Ruby
# loadup.rb - run UPPERCASE RUBY program   class Object alias lowercase_method_missing method_missing   # Allow UPPERCASE method calls. def method_missing(sym, *args, &block) str = sym.to_s if str == (down = str.downcase) lowercase_method_missing sym, *args, &block else send down, *args, &...
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...
#Swift
Swift
import Foundation   let hello = "Hello, World!" let fromC = strdup(hello) let backToSwiftString = String.fromCString(fromC)
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...
#Tcl
Tcl
package require critcl critcl::code { #include <math.h> } critcl::cproc tcl::mathfunc::ilogb {double value} int { return ilogb(value); } package provide ilogb 1.0
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...
#Forth
Forth
a-function \ requiring no arguments a-function \ with a fixed number of arguents a-function \ having optional arguments a-function \ having a variable number of arguments a-function \ having such named arguments as we have in Forth ' a-function var ! \ using a function in a first...
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: ...
#Tcl
Tcl
proc fold {lambda zero list} { set accumulator $zero foreach item $list { set accumulator [apply $lambda $accumulator $item] } return $accumulator }
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: ...
#uBasic.2F4tH
uBasic/4tH
Push 5, 4, 3, 2, 1: s = Used() - 1 For x = 0 To s: @(x) = Pop(): Next   Print "Sum is  : "; FUNC(_reduce(0, s, _add)) Print "Difference is : "; FUNC(_reduce(0, s, _subtract)) Print "Product is  : "; FUNC(_reduce(0, s, _multiply)) Print "Maximum is  : "; FUNC(_reduce(0, s, _max)) Print "Minimum is  : "; FUNC...
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...
#Wren
Wren
import "/seq" for Lst   var prod2 = Fn.new { |l1, l2| var res = [] for (e1 in l1) { for (e2 in l2) res.add([e1, e2]) } return res }   var prodN = Fn.new { |ll| if (ll.count < 2) Fiber.abort("There must be at least two lists.") var p2 = prod2.call(ll[0], ll[1]) return ll.skip(2).reduc...
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...
#Kotlin
Kotlin
abstract class Catalan { abstract operator fun invoke(n: Int) : Double   protected val m = mutableMapOf(0 to 1.0) }   object CatalanI : Catalan() { override fun invoke(n: Int): Double { if (n !in m) m[n] = Math.round(fact(2 * n) / (fact(n + 1) * fact(n))).toDouble() return m[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...
#Phix
Phix
-- demo\rosetta\Brace_expansion.exw with javascript_semantics function pair(sequence stems, sequence brest) sequence res = {} for i=1 to length(stems) do for j=1 to length(brest) do res = append(res,stems[i]&brest[j]) end for end for return res end function function brarse(s...
http://rosettacode.org/wiki/Brazilian_numbers
Brazilian numbers
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad Olimpiada Iberoamericana de Matematica in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number N has at least one natural number B where 1 < B < N-1 where the represent...
#Groovy
Groovy
import org.codehaus.groovy.GroovyBugError   class Brazilian { private static final List<Integer> primeList = new ArrayList<>(Arrays.asList( 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...
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...
#FreeBASIC
FreeBASIC
' version 17-02-2016 ' compile with: fbc -s console   ' TRUE/FALSE are built-in constants since FreeBASIC 1.04 ' For older versions they have to be defined. #Ifndef TRUE #Define FALSE 0 #Define TRUE Not FALSE #EndIf   Function WD(m As Integer, d As Integer, y As Integer) As Integer ' Zellerish '...
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...
#Java
Java
import java.awt.Graphics; import java.awt.image.BufferedImage; import java.util.*; import javax.swing.JFrame;   public class BrownianTree extends JFrame implements Runnable {   BufferedImage I; private List<Particle> particles; static Random rand = new Random();   public BrownianTree() { super("...
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...
#Delphi
Delphi
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...
#Clojure
Clojure
(defn encrypt-character [offset c] (if (Character/isLetter c) (let [v (int c) base (if (>= v (int \a)) (int \a) (int \A)) offset (mod offset 26)] ;works with negative offsets too! (char (+ (mod (+ (- v base) offset) 26) base))) c))   ...
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
#.D0.9C.D0.9A-61.2F52
МК-61/52
П0 П1 0 П2 1 П2 1 П3 ИП3 ИП2 ИП1 ИП0 - 1 + * П2 1/x + П3 ИП0 x#0 25 L0 08 ИП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
#Modula-2
Modula-2
MODULE CalculateE; FROM RealStr IMPORT RealToStr; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   CONST EPSILON = 1.0E-15;   PROCEDURE abs(n : REAL) : REAL; BEGIN IF n < 0.0 THEN RETURN -n END; RETURN n END abs;   VAR buf : ARRAY[0..31] OF CHAR; fact,n : LONGCARD; e,e0 : LONGREAL; B...
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...
#Racket
Racket
#lang racket/base (require racket/string racket/list)   (define (permutations-getall items size) (if (zero? size) '(()) (for/list ([tail (in-list (permutations-getall items (- size 1)))] #:when #t [i (in-list items)] #:unless (member i tail)) ...
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...
#Seed7
Seed7
$ INCLUDE "SEED7_05.S7I"; INCLUDE "TIME.S7I"; CONST FUNC STRING: CENTER (IN STRING: STRI, IN INTEGER: LENGTH) IS RETURN ("" LPAD (LENGTH - LENGTH(STRI)) DIV 2 <& STRI) RPAD LENGTH; CONST PROC: PRINTCALENDAR (IN INTEGER: YEAR, IN INTEGER: COLS) IS FUNC LOCAL VAR TIME: DATE IS TIME.VALUE; VAR INTEGER: D...
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...
#TXR
TXR
This is the TXR Lisp interactive listener of TXR 176. Use the :quit command or type Ctrl-D on empty line to exit. 1> (with-dyn-lib nil (deffi strdup "strdup" str-d (str))) #:lib-0177 2> (strdup "hello, world!") "hello, world!"
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...
#Wren
Wren
/* call_foreign_language_function.wren */   class C { foreign static strdup(s) }   var s = "Hello World!" System.print(C.strdup(s))