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/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...
#Julia
Julia
  # IF THIS SMALL FUNCTION IS PLACED IN THE STARTUP.JL # FILE, IT WILL BE LOADED ON STARTUP. THE REST OF # THIS EXAMPLE IS IN ALL UPPERCASE. function RUNUPPERCASECODE(CO) COD = replace(lowercase(CO), "date" => "Date") for E in Meta.parse(COD, 1) eval(E) end end     CODE = """BEGIN   USING DATES; CENTEROBJECT(X,...
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...
#Modula-2
Modula-2
#include <vga.h>   int Initialize (void) { if ( vga_init () == 0 ) return 1; else return 0; }   void SetMode (int newmode) { vga_setmode (newmode); }   int GetMode (void) { return vga_getcurrentmode (); }   int MaxWidth (void) { return vga_getxdim (); }   int MaxHeight (void) { retu...
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...
#CoffeeScript
CoffeeScript
  # Calling a function that requires no arguments foo()   # Calling a function with a fixed number of arguments foo 1   # Calling a function with optional arguments # (Optional arguments are done using an object with named keys) foo 1, optionalBar: 1, optionalBaz: 'bax'   # Calling a function with a variable number of ...
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Raku
Raku
sub cantor ( Int $height ) { my $width = 3 ** ($height - 1);   my @lines = ( "\c[FULL BLOCK]" x $width ) xx $height;   my sub _trim_middle_third ( $len, $start, $index ) { my $seg = $len div 3 or return;   for ( $index ..^ $height ) X ( 0 ..^ $seg ) -> ( $i, $j ) { @l...
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: ...
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   def add + enddef def sub - enddef def mul * enddef   def reduce >ps 1 get swap len 2 swap 2 tolist for get rot swap tps exec swap endfor ps> drop swap enddef     ( 1 2 3 4 5 ) getid add reduce ? getid sub reduce ? getid mul 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: ...
#PicoLisp
PicoLisp
(de reduce ("Fun" "Lst") (let "A" (car "Lst") (for "N" (cdr "Lst") (setq "A" ("Fun" "A" "N")) ) "A" ) )   (println (reduce + (1 2 3 4 5)) (reduce * (1 2 3 4 5)) )   (bye)
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...
#Ring
Ring
  # Project : Cartesian product of two or more lists   list1 = [[1,2],[3,4]] list2 = [[3,4],[1,2]] cartesian(list1) cartesian(list2)   func cartesian(list1) for n = 1 to len(list1[1]) for m = 1 to len(list1[2]) see "(" + list1[1][n] + ", " + list1[2][m] + ")" + nl next next ...
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...
#FunL
FunL
import integers.choose import util.TextTable   def catalan( n ) = choose( 2n, n )/(n + 1)   catalan2( n ) = product( (n + k)/k | k <- 2..n )   catalan3( 0 ) = 1 catalan3( n ) = 2*(2n - 1)/(n + 1)*catalan3( n - 1 )   t = TextTable() t.header( 'n', 'definition', 'product', 'recursive' ) t.line()   for i <- 1..4 ...
http://rosettacode.org/wiki/Brilliant_numbers
Brilliant numbers
Brilliant numbers are a subset of semiprime numbers. Specifically, they are numbers that are the product of exactly two prime numbers that both have the same number of digits when expressed in base 10. Brilliant numbers are useful in cryptography and when testing prime factoring algorithms. E.G. 3 × 3 (9) is a bri...
#XPL0
XPL0
  func NumDigits(N); \Return number of digits in N int N, Cnt; [Cnt:= 0; repeat N:= N/10; Cnt:= Cnt+1; until N = 0; return Cnt; ];   func Brilliant(N); \Return 'true' if N is a brilliant number int N, Limit, Cnt, F; int A(3); [Limit:= sqrt(N); Cnt:= 0; F:= 2; loop [if rem(N/F) = 0 then ...
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...
#C.23
C#
using System; using System.Collections; using System.Collections.Generic; using System.Text; using static System.Linq.Enumerable;   public static class BraceExpansion { enum TokenType { OpenBrace, CloseBrace, Separator, Text, Alternate, Concat } const char L = '{', R = '}', S = ',';   public static void Mai...
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...
#Arturo
Arturo
brazilian?: function [n][ if n < 7 -> return false if zero? and n 1 -> return true loop 2..n-2 'b [ if 1 = size unique digits.base:b n -> return true ] return false ]   printFirstByRule: function [rule,title][ print ~"First 20 |title|brazilian numbers:" i: 7 found: ne...
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...
#Batch_File
Batch File
::Calender Task from Rosetta Code Wiki ::Batch File Implementation   @echo off setlocal enabledelayedexpansion   %== Set a valid year [will not be validated] ==% set y=1969   %== Set the variables for months (feb_l=the normal 28 days) ==% set jan_l=31&set apr_l=30 set mar_l=31&set jun_l=30 set may_l=31&set sep_l=30 s...
http://rosettacode.org/wiki/Break_OO_privacy
Break OO privacy
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is...
#Java
Java
import java.lang.reflect.*;   class Example { private String _name; public Example(String name) { _name = name; } public String toString() { return "Hello, I am " + _name; } }   public class BreakPrivacy { public static final void main(String[] args) throws Exception { Example foo = new Example("Eric");   for (...
http://rosettacode.org/wiki/Break_OO_privacy
Break OO privacy
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is...
#Julia
Julia
import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.jvm.isAccessible   class ToBeBroken { @Suppress("unused") private val secret: Int = 42 }   fun main(args: Array<String>) { val tbb = ToBeBroken() val props = ToBeBroken::class.declaredMemberProperties for (prop in props) { ...
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...
#C.2B.2B
C++
#include <windows.h> #include <iostream> #include <string>   //-------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------- enum states { SEED, GROWING, MOVING, REST }; enum treeStates { NONE, MOVER, TREE }; const 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...
#Batch_File
Batch File
:: Bulls and Cows Task from Rosetta Code :: Batch File Implementation   @echo off setlocal enabledelayedexpansion :: initialization :begin set "list_chars=123456789" set "list_length=9" set "code=" set "code_length=4" %== this should be less than 10 ==% set "tries=0" %== number of tries ==% :: generate the code t...
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...
#Phix
Phix
-- demo\rosetta\burrows_wheeler.exw --/* The traditional method: 7 banana$ $banana 6 6 $banana ===> a$banan 5 5 a$banan ana$ban 3 4 na$bana sort anana$b 1 3 ana$ban banana$ 7 2 nana$ba ===> na$bana 4 1 anana$b nana$ba 2 ...
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...
#AutoIt
AutoIt
  $Caesar = Caesar("Hi", 2, True) MsgBox(0, "Caesar", $Caesar) Func Caesar($String, $int, $encrypt = True) If Not IsNumber($int) Or Not StringIsDigit($int) Then Return SetError(1, 0, 0) If $int < 1 Or $int > 25 Then Return SetError(2, 0, 0) Local $sLetters, $x $String = StringUpper($String) $split = StringSplit($S...
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
#Fortran
Fortran
  Program eee implicit none integer, parameter :: QP = selected_real_kind(16) real(QP), parameter :: one = 1.0 real(QP) :: ee   write(*,*) ' exp(1.) ', exp(1._QP)   ee = 1. +(one +(one +(one +(one +(one+ (one +(one +(one +(one +(one +(one & +(one +(one +(one +(one +(one +(one +(one +(one +(one +...
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...
#Java
Java
  public class BullsAndCowsPlayerGame {   private static int count; private static Console io = System.console();   private final GameNumber secret; private List<AutoGuessNumber> pool = new ArrayList<>();   public BullsAndCowsPlayerGame(GameNumber secret) { this.secret = secret; fill...
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...
#Kotlin
Kotlin
IMPORT JAVA.TEXT.* IMPORT JAVA.UTIL.* IMPORT JAVA.IO.PRINTSTREAM   INTERNAL FUN PRINTSTREAM.PRINTCALENDAR(YEAR: INT, NCOLS: BYTE, LOCALE: LOCALE?) { IF (NCOLS < 1 || NCOLS > 12) THROW ILLEGALARGUMENTEXCEPTION("ILLEGAL COLUMN WIDTH.") VAL W = NCOLS * 24 VAL NROWS = MATH.CEIL(12.0 / NCOLS).TOINT()   ...
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...
#Modula-3
Modula-3
UNSAFE MODULE Foreign EXPORTS Main;   IMPORT IO, Ctypes, Cstring, M3toC;   VAR string1, string2: Ctypes.const_char_star;   BEGIN string1 := M3toC.CopyTtoS("Foobar"); string2 := M3toC.CopyTtoS("Foobar2"); IF Cstring.strcmp(string1, string2) = 0 THEN IO.Put("string1 = string2\n"); ELSE IO.Put("string1 # s...
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...
#Mosaic
Mosaic
import clib   importdll msvcrt = clang function "_strdup" (ref char)ref char end   proc start= []char str:=z"hello strdup" ref char str2 str2:=_strdup(&.str) println str2 end
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Common_Lisp
Common Lisp
  ;Calling a function that requires no arguments (defun a () "This is the 'A' function") (a) ;Calling a function with a fixed number of arguments (defun b (x y) (list x y)) (b 1 2) ;Calling a function with optional arguments (defun c (&optional x y) (list x y)) (c 1) ;Calling a function with a variable number of argume...
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#REXX
REXX
/*REXX program displays an ASCII diagram of a Canter Set as a set of (character) lines. */ w= linesize() /*obtain the width of the display term.*/ if w==0 then w= 81 /*Can't obtain width? Use the default.*/ do lines=0; _ = 3 ** lines...
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: ...
#PowerShell
PowerShell
  1..5 | ForEach-Object -Begin {$result = 0} -Process {$result += $_} -End {$result}  
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: ...
#Prolog
Prolog
:- use_module(library(lambda)).   catamorphism :- numlist(1,10,L), foldl(\XS^YS^ZS^(ZS is XS+YS), L, 0, Sum), format('Sum of ~w is ~w~n', [L, Sum]), foldl(\XP^YP^ZP^(ZP is XP*YP), L, 1, Prod), format('Prod of ~w is ~w~n', [L, Prod]), string_to_list(LV, ""), foldl(\XC^YC^ZC^(string_to_atom(XS, XC),string_concat(Y...
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...
#Ruby
Ruby
p [1, 2].product([3, 4]) p [3, 4].product([1, 2]) p [1, 2].product([]) p [].product([1, 2]) p [1776, 1789].product([7, 12], [4, 14, 23], [0, 1]) p [1, 2, 3].product([30], [500, 100]) p [1, 2, 3].product([], [500, 100])  
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...
#F.C5.8Drmul.C3.A6
Fōrmulæ
Catalan1 := n -> Binomial(2*n, n) - Binomial(2*n, n - 1);   Catalan2 := n -> Binomial(2*n, n)/(n + 1);   Catalan3 := function(n) local k, c; c := 1; k := 0; while k < n do k := k + 1; c := 2*(2*k - 1)*c/(k + 1); od; return c; end;   Catalan4_memo := [1]; Catalan4 := function(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...
#Common_Lisp
Common Lisp
(defstruct alternation (alternatives nil :type list))   (defun alternatives-end-positions (string start) (assert (char= (char string start) #\{)) (loop with level = 0 with end-positions with escapep and commap for index from start below (length string) for c = (char string index) ...
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...
#AWK
AWK
  # syntax: GAWK -f BRAZILIAN_NUMBERS.AWK # converted from C BEGIN { split(",odd ,prime ",kinds,",") for (i=1; i<=3; ++i) { printf("first 20 %sBrazilian numbers:",kinds[i]) c = 0 n = 7 while (1) { if (is_brazilian(n)) { printf(" %d",n) if (++c == 20) { ...
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"DATELIB" VDU 23,22,640;570;8,15,16,128   year% = 1969 PRINT TAB(38); year% DIM dom%(2), mjd%(2), dim%(2)   FOR day% = 1 TO 7 days$ += LEFT$(FN_date$(FN_mjd(day%, 1, 1905), "ddd"), 2) + " " NEXT   FOR month% = 1 TO 10 STEP 3 PRINT FOR...
http://rosettacode.org/wiki/Break_OO_privacy
Break OO privacy
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is...
#Kotlin
Kotlin
import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.jvm.isAccessible   class ToBeBroken { @Suppress("unused") private val secret: Int = 42 }   fun main(args: Array<String>) { val tbb = ToBeBroken() val props = ToBeBroken::class.declaredMemberProperties for (prop in props) { ...
http://rosettacode.org/wiki/Break_OO_privacy
Break OO privacy
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is...
#Logtalk
Logtalk
:- object(foo).   % be sure that context switching calls are allowed :- set_logtalk_flag(context_switching_calls, allow).   % declare and define a private method :- private(bar/1). bar(1). bar(2). bar(3).   :- end_object.
http://rosettacode.org/wiki/Break_OO_privacy
Break OO privacy
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is...
#Lua
Lua
local function Counter() -- These two variables are "private" to this function and can normally -- only be accessed from within this scope, including by any function -- created inside here. local counter = {} local count = 0   function counter:increment() -- 'count' is an upvalue here and can thus be accessed...
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...
#Common_Lisp
Common Lisp
;;; brownian.lisp ;;; sbcl compile: first load and then (sb-ext:save-lisp-and-die "brownian" :executable t :toplevel #'brownian::main) (ql:quickload "cl-gd")   (defpackage #:brownian (:use #:cl #:cl-gd)) (in-package #:brownian)   (defvar *size* 512) (defparameter bitmap (make-array *size*)) (dotimes (i *size*) (set...
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...
#BBC_BASIC
BBC BASIC
secret$ = "" REPEAT c$ = CHR$(&30 + RND(9)) IF INSTR(secret$, c$) = 0 secret$ += c$ UNTIL LEN(secret$) = 4   PRINT "Guess a four-digit number with no digit used twice."' guesses% = 0 REPEAT   REPEAT INPUT "Enter your guess: " guess$ IF LEN(...
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...
#Python
Python
  def bwt(s): """Apply Burrows-Wheeler transform to input string.""" assert "\002" not in s and "\003" not in s, "Input string cannot contain STX and ETX characters" s = "\002" + s + "\003" # Add start and end of text marker table = sorted(s[i:] + s[:i] for i in range(len(s))) # Table of rotations of ...
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...
#AWK
AWK
  #!/usr/bin/awk -f   BEGIN { message = "My hovercraft is full of eels." key = 1   cypher = caesarEncode(key, message) clear = caesarDecode(key, cypher)   print "message: " message print " cypher: " cypher print " clear: " clear exit }   function caesarEncode(key, message) { return...
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
#Free_Pascal
Free Pascal
' version 02-07-2018 ' compile with: fbc -s console   Dim As Double e , e1 Dim As ULongInt n = 1, n1 = 1   e = 1 / 1   While e <> e1 e1 = e e += 1 / n n1 += 1 n *= n1 Wend   Print "The value of e ="; e   ' empty keyboard buffer While InKey <> "" : Wend Print : Print "hit any key to end program" Sleep En...
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
#FreeBASIC
FreeBASIC
' version 02-07-2018 ' compile with: fbc -s console   Dim As Double e , e1 Dim As ULongInt n = 1, n1 = 1   e = 1 / 1   While e <> e1 e1 = e e += 1 / n n1 += 1 n *= n1 Wend   Print "The value of e ="; e   ' empty keyboard buffer While InKey <> "" : Wend Print : Print "hit any key to end program" Sleep En...
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...
#Julia
Julia
  countbulls(a, b) = sum([a[i] == b[i] for i in 1:length(a)]) countcows(a, b) = sum([a[i] == b[j] for i in 1:length(a), j in 1:length(b) if i != j]) validate(a, b) = typeof(a) == Int && typeof(b) == Int && a >= 0 && b >= 0 && a + b < 5   function doguess() poss = [a for a in collect(Base.product(1:9,1:9,1:9,1:9)) 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...
#Kotlin
Kotlin
// version 1.1.2   import java.util.Random   fun countBullsAndCows(guess: IntArray, answer: IntArray): Pair<Int,Int> { var bulls = 0 var cows = 0 for ((i, d) in guess.withIndex()) { if (answer[i] == d) bulls++ else if (d in answer) cows++ } return bulls to cows }   fun main(args: Ar...
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...
#Lua
Lua
FUNCTION PRINT_CAL(YEAR) LOCAL MONTHS={"JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE", "JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"} LOCAL DAYSTITLE="MO TU WE TH FR SA SU" LOCAL DAYSPERMONTH={31,28,31,30,31,30,31,31,30,31,30,31} LOCAL STARTDAY=((YEAR-1)*365+MATH.FLOOR((YEAR-1)/...
http://rosettacode.org/wiki/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...
#Never
Never
extern "libm.so.6" func sinhf(x : float) -> float extern "libm.so.6" func coshf(x : float) -> float extern "libm.so.6" func powf(base : float, exp : float) -> float extern "libm.so.6" func atanf(x : float) -> float   func main() -> int { var v1 = sinhf(1.0); var v2 = coshf(1.0); var v3 = powf(10.0, 2.0); ...
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...
#NewLISP
NewLISP
; simple FFI interface on Mac OSX (import "libc.dylib" "strdup") (println (get-string (strdup "hello world")))   ; or extended FFI interface on Mac OSX (import "libc.dylib" "strdup" "char*" "char*") (println (strdup "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...
#Cubescript
Cubescript
  // No arguments myfunction   // All functions can take a variable number of arguments. // These can be accessed from within the function with the aliases: // $arg1, $arg2, $arg3... $numargs tells the amount of args passed. myfunction word "text string" 1 3.14   // Getting a function's return value retval = (myfunctio...
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Ring
Ring
  # Project : Cantor set   load "guilib.ring" paint = null   new qapp { win1 = new qwidget() { setwindowtitle("") setgeometry(100,100,800,600) label1 = new qlabel(win1) { setgeometry(10,10,800,600) ...
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Ruby
Ruby
lines = 5   (0..lines).each do |exp| seg_size = 3**(lines-exp-1) chars = (3**exp).times.map{ |n| n.digits(3).any?(1) ? " " : "█"} puts chars.map{ |c| c * seg_size }.join end  
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: ...
#PureBasic
PureBasic
Procedure.i reduce(List l(),op$="+") If FirstElement(l()) x=l() While NextElement(l()) Select op$ Case "+" : x+l() Case "-" : x-l() Case "*" : x*l() EndSelect Wend EndIf ProcedureReturn x EndProcedure   NewList fold() For i=1 To 5 : AddElement(fold()) : fold()=i : N...
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...
#Rust
Rust
fn cartesian_product(lists: &Vec<Vec<u32>>) -> Vec<Vec<u32>> { let mut res = vec![];   let mut list_iter = lists.iter(); if let Some(first_list) = list_iter.next() { for &i in first_list { res.push(vec![i]); } } for l in list_iter { let mut tmp = vec![]; f...
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#GAP
GAP
Catalan1 := n -> Binomial(2*n, n) - Binomial(2*n, n - 1);   Catalan2 := n -> Binomial(2*n, n)/(n + 1);   Catalan3 := function(n) local k, c; c := 1; k := 0; while k < n do k := k + 1; c := 2*(2*k - 1)*c/(k + 1); od; return c; end;   Catalan4_memo := [1]; Catalan4 := function(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...
#D
D
import std.stdio, std.typecons, std.array, std.range, std.algorithm, std.string;   Nullable!(Tuple!(string[], string)) getGroup(string s, in uint depth) pure nothrow @safe { string[] sout; auto comma = false;   while (!s.empty) { // {const g, s} = getItems(s, depth); const r = getItems(s, de...
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...
#C
C
#include <stdio.h>   typedef char bool;   #define TRUE 1 #define FALSE 0   bool same_digits(int n, int b) { int f = n % b; n /= b; while (n > 0) { if (n % b != f) return FALSE; n /= b; } return TRUE; }   bool is_brazilian(int n) { int b; if (n < 7) return FALSE; if (!(n %...
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#Befunge
Befunge
"P"00p&>:::4%!\"d"%*\45*:*%!+!!65*+31p:1-:::"I"5**\4/+\"d"/-\45*:*/+1+7%:0v J!F?M!A M!J J!A!S O!N D!SaFrThWeTuMoSuvp01:_1#!-#%:#\>#+6<v-2g1+1g01p1p01:< January February March April >:45**00g\-\1-:v:<<6>+7%:10g2+:38*\`| May June July August v02-1:+4*-4\`\4:/_$:^^:/*2+92+2:g00$$$< September Octobe...
http://rosettacode.org/wiki/Break_OO_privacy
Break OO privacy
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is...
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Group Alfa { Private: X=10, Y=20 Public: Module SetXY (.X, .Y) {} Module Print { Print .X, .Y } } Alfa.Print ' 10 20 \\ we have to KnΟw position in group \\ so we make references f...
http://rosettacode.org/wiki/Break_OO_privacy
Break OO privacy
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is...
#Nim
Nim
type Foo* = object a: string b: string c: int   proc createFoo*(a, b, c): Foo = Foo(a: a, b: b, c: c)
http://rosettacode.org/wiki/Break_OO_privacy
Break OO privacy
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   @interface Example : NSObject { @private NSString *_name; } - (instancetype)initWithName:(NSString *)name; @end   @implementation Example - (NSString *)description { return [NSString stringWithFormat:@"Hello, I am %@", _name]; } - (instancetype)initWithName:(NSString *)name { i...
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...
#D
D
void main() { import core.stdc.stdio, std.random, grayscale_image;   enum uint side = 600; // Square world side. enum uint num_particles = 10_000; static assert(side > 2 && num_particles < (side ^^ 2 * 0.7));   auto rng = unpredictableSeed.Xorshift; ubyte[side][side] W; // World. W[sid...
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...
#BCPL
BCPL
get "libhdr"   static $( randstate = ? $)   let randdigit() = valof $( let x = ? $( randstate := random(randstate) x := (randstate >> 7) & 15 $) repeatuntil 0 < x <= 9 resultis x $)   let gensecret(s) be for i=0 to 3 s!i := randdigit() repeatuntil valof $( for j=0 to i-1 if s!...
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...
#Raku
Raku
# STX can be any character that doesn't appear in the text. # Using a visible character here for ease of viewing.   constant \STX = '👍';   # Burrows-Wheeler transform sub transform (Str $s is copy) { note "String can't contain STX character." and exit if $s.contains: STX; $s = STX ~ $s; (^$s.chars).map({ ...
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...
#Babel
Babel
((main {"The quick brown fox jumps over the lazy dog.\n" dup <<   17 caesar_enc ! dup <<   17 caesar_dec ! <<})   (caesar_enc { 2 take { caesar_enc_loop ! } nest })   (caesar_enc_loop { give <- str2ar {({ dup is_upper ! } { 0x40 - ...
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
#F.C5.8Drmul.C3.A6
Fōrmulæ
  ###sysinclude math.uh 1.0e-15 sto EPSILON one fact 2. sto e 2 sto n (( @e sto e0 #g @n++ prd fact 1.0 @fact !(#d) / sum e ( @e @e0 - abs @EPSILON < ))) ."e = " @e printnl end { „EPSILON” } { „fact” } { „e” } { „e0” } { „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
#Furor
Furor
  ###sysinclude math.uh 1.0e-15 sto EPSILON one fact 2. sto e 2 sto n (( @e sto e0 #g @n++ prd fact 1.0 @fact !(#d) / sum e ( @e @e0 - abs @EPSILON < ))) ."e = " @e printnl end { „EPSILON” } { „fact” } { „e” } { „e0” } { „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...
#Liberty_BASIC
Liberty BASIC
  guesses =0   do while len( secret$) <4 ' zero not allowed <<<<<<<<< n$ =chr$( int( rnd( 1) *9) +49) if not( instr( secret$, n$)) then secret$ =secret$ +n$ loop   print " Secretly, my opponent just chose a number. But she didn't tell anyone! "; secret$; "." print...
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...
#M2000_Interpreter
M2000 Interpreter
  \\ Calendar - for "REAL" programmers \\ All statements in UPPERCASE \\ Output to 132 characters console - as a line printer \\ USE COURIER NEW (FONT "COURIER NEW")   \\ CHANGE THE VALUE OF PRINT_IT TO TRUE FOR PRINTING GLOBAL CONST PRINT_IT AS BOOLEAN=FALSE MODULE GLOBAL SNOOPY { IF NOT PRINT_IT THEN CURSOR 0,ROW E...
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...
#Nim
Nim
proc strcmp(a, b: cstring): cint {.importc: "strcmp", nodecl.} echo strcmp("abc", "def") echo strcmp("hello", "hello")   proc printf(formatstr: cstring) {.header: "<stdio.h>", varargs.}   var x = "foo" printf("Hello %d %s!\n", 12, x)
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...
#OCaml
OCaml
void myfunc_a(); float myfunc_b(int, float); char *myfunc_c(int *, int);
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...
#D
D
import std.traits;   enum isSubroutine(alias F) = is(ReturnType!F == void);   void main() { void foo1() {}   // Calling a function that requires no arguments: foo1(); foo1; // Alternative syntax.     void foo2(int x, int y) {}   immutable lambda = function int(int x) => x ^^ 2;   // Calling ...
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Rust
Rust
  use convert_base::Convert; use std::fmt;   struct CantorSet { cells: Vec<Vec<bool>>, } fn number_to_vec(n: usize) -> Vec<u32> { // for the conversion we need the digits in reverse order // i.e the least significant digit in the first element of the vector n.to_string() .chars() .rev() ...
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Scala
Scala
object CantorSetQD extends App { val (width, height) = (81, 5)   val lines = Seq.fill[Array[Char]](height)(Array.fill[Char](width)('*'))   def cantor(start: Int, len: Int, index: Int) { val seg = len / 3   println(start, len, index)   if (seg != 0) { for (i <- index until height; j <-...
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: ...
#Python
Python
>>> # Python 2.X >>> from operator import add >>> listoflists = [['the', 'cat'], ['sat', 'on'], ['the', 'mat']] >>> help(reduce) Help on built-in function reduce in module __builtin__:   reduce(...) reduce(function, sequence[, initial]) -> value   Apply a function of two arguments cumulatively to the items of a...
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...
#Scala
Scala
def cartesianProduct[T](lst: List[T]*): List[List[T]] = {   /** * Prepend single element to all lists of list * @param e single elemetn * @param ll list of list * @param a accumulator for tail recursive implementation * @return list of lists with prepended element e */ def pel(e: 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...
#Go
Go
package main   import ( "fmt" "math/big" )   func main() { var b, c big.Int for n := int64(0); n < 15; n++ { fmt.Println(c.Div(b.Binomial(n*2, n), c.SetInt64(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...
#Elixir
Elixir
defmodule Brace_expansion do def getitem(s), do: getitem(String.codepoints(s), 0, [""])   defp getitem([], _, out), do: {out,[]} defp getitem([c|_]=s, depth, out) when depth>0 and (c == "," or c == "}"), do: {out,s} defp getitem([c|t], depth, out) do x = getgroup(t, depth+1, [], false) if (c == "{") and...
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...
#Go
Go
package expand   // Expander is anything that can be expanded into a slice of strings. type Expander interface { Expand() []string }   // Text is a trivial Expander that expands to a slice with just itself. type Text string   func (t Text) Expand() []string { return []string{string(t)} }   // Alternation is an Expande...
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...
#C.23
C#
using System; class Program {   static bool sameDigits(int n, int b) { int f = n % b; while ((n /= b) > 0) if (n % b != f) return false; return true; }   static bool isBrazilian(int n) { if (n < 7) return false; if (n % 2 == 0) return true; for (int b = 2; b < n - 1; b++) if (sameDigits(n,...
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   int width = 80, year = 1969; int cols, lead, gap;   const char *wdays[] = { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; struct months { const char *name; int days, start_wday, at; } months[12] = { { "January", 31, 0, 0 }, { "February", 28, 0, 0 }, { "Mar...
http://rosettacode.org/wiki/Break_OO_privacy
Break OO privacy
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is...
#OCaml
OCaml
class point x y = object val mutable x = x val mutable y = y method print = Printf.printf "(%d, %d)\n" x y method dance = x <- x + Random.int 3 - 1; y <- y + Random.int 3 - 1 end   type evil_point { blah : int; blah2 : int; mutable x : int; mutable y : int; }   let evil_reset p =...
http://rosettacode.org/wiki/Break_OO_privacy
Break OO privacy
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is...
#Oforth
Oforth
package Foo; sub new { my $class = shift; my $self = { _bar => 'I am ostensibly private' }; return bless $self, $class; }   sub get_bar { my $self = shift; return $self->{_bar}; }   package main; my $foo = Foo->new(); print "$_\n" for $foo->get_bar(), $foo->{_bar};
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...
#Delphi
Delphi
const SIZE = 256; NUM_PARTICLES = 1000;   procedure TForm1.Button1Click(Sender: TObject); type TByteArray = array[0..0] of Byte; PByteArray = ^TByteArray; var B: TBitmap; I: Integer; P, D: TPoint; begin Randomize; B := TBitmap.Create; try B.Width := SIZE; B.Height...
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...
#Brat
Brat
secret_length = 4   secret = [1 2 3 4 5 6 7 8 9].shuffle.pop secret_length   score = { guess | cows = 0 bulls = 0   guess.each_with_index { digit, index | true? digit == secret[index] { bulls = bulls + 1 } { true? secret.include?(digit) { cows = cows + 1 } } }   [cows: cows, b...
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...
#REXX
REXX
/*REXX program performs a Burrows─Wheeler transform (BWT) on a character string(s). */ $.= /*the default text for (all) the inputs*/ parse arg $.1 /*obtain optional arguments from the CL*/ if $.1='' then do; $.1= "banana" ...
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...
#BaCon
BaCon
CONST lc$ = "abcdefghijklmnopqrstuvwxyz" CONST uc$ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"   CONST txt$ = "The quick brown fox jumps over the lazy dog."   FUNCTION Ceasar$(t$, k)   lk$ = MID$(lc$ & lc$, k+1, 26) uk$ = MID$(uc$ & uc$, k+1, 26)   RETURN REPLACE$(t$, lc$ & uc$, lk$ & uk$, 2)   END FUNCTION   tokey = RA...
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
#Go
Go
package main   import ( "fmt" "math" )   const epsilon = 1.0e-15   func main() { fact := uint64(1) e := 2.0 n := uint64(2) for { e0 := e fact *= n n++ e += 1.0 / float64(fact) if math.Abs(e - e0) < epsilon { break } } fmt.Printf...
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...
#Lua
Lua
local line = "---------+----------------------------------+-------+-------+" local digits = {1,2,3,4,5,6,7,8,9}   function and_bits (a, b) -- print (a, b) return a & b -- Lua 5.3 end   function or_bits (a, b) return a | b -- Lua 5.3 end     function get_digits (n) local tDigits = {} for i = 1, #digits do tDigits[i]...
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...
#Nim
Nim
import strutils   const progUpper = staticRead("calendar_upper.txt")   proc transformed(s: string): string {.compileTime.} = ## Return a transformed version (which can compile) of a program in uppercase.   let upper = s.toLower() # Convert all to lowercase. var inString = false # Text in string should be in up...
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...
#Ol
Ol
  (import (otus ffi))   (define self (load-dynamic-library #f)) (define strdup (self type-string "strdup" type-string))   (print (strdup "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...
#Oz
Oz
#include "mozart.h" #include <string.h>   OZ_BI_define(c_strdup,1,1) { OZ_declareVirtualString(0, s1); char* s2 = strdup(s1); OZ_Term s3 = OZ_string(s2); free( s2 ); OZ_RETURN( s3 ); } OZ_BI_end   OZ_C_proc_interface * oz_init_module(void) { static OZ_C_proc_interface table[] = { {"strdup",1,1,c_strdup}...
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...
#Dart
Dart
void main() { // Function definition // See the "Function definition" task for more info void noArgs() {} void fixedArgs(int arg1, int arg2) {} void optionalArgs([int arg1 = 1]) {} void namedArgs({required int arg1}) {} int returnsValue() {return 1;}   // Calling a function that requires no arguments ...
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Sidef
Sidef
func cantor (height) { var width = 3**(height - 1) var lines = height.of { "\N{FULL BLOCK}" * width }   func trim_middle_third (len, start, index) { var seg = (len // 3) || return()   for i, j in ((index ..^ height) ~X (0 ..^ seg)) { lines[i].replace!(Regex("^.{#{start + seg + j}...
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: ...
#Quackery
Quackery
/O> 0 ' [ 1 2 3 4 5 ] witheach + ... 1 ' [ 1 2 3 4 5 ] witheach * ...   Stack: 15 120
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: ...
#R
R
  Reduce('+', c(2,30,400,5000)) 5432  
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...
#Scheme
Scheme
  (define cartesian-product (lambda (xs ys) (if (or (zero? (length xs)) (zero? (length ys))) '() (fold append (map (lambda (x) (map (lambda (y) (list x y)) ys)) xs)))))   (define nary-cartesian-product (lambda (ls) (if (fold (lambda (a b) (or a b)) (map (compose zero? length) ls)) '() (map flatten...
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...
#Groovy
Groovy
  class Catalan { public static void main(String[] args) { BigInteger N = 15; BigInteger k,n,num,den; BigInteger catalan; print(1); for(n=2;n<=N;n++) { num = 1; den = 1; for(k=2;k<=n;k++) { num = num*(n+k);...
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...
#Groovy
Groovy
class BraceExpansion { static void main(String[] args) { for (String s : [ "It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", "{,{,gotta have{ ,\\, again\\, }}more }cowbell!", "{}} some }{,{\\\\{ edge, edge} \\,}{ 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...
#C.2B.2B
C++
#include <iostream>   bool sameDigits(int n, int b) { int f = n % b; while ((n /= b) > 0) { if (n % b != f) { return false; } } return true; }   bool isBrazilian(int n) { if (n < 7) return false; if (n % 2 == 0)return true; for (int b = 2; b < n - 1; b++) { ...
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...
#C.23
C#
    using System; using System.Collections.Generic; using System.Linq; using System.Text;   namespace CalendarStuff {   class Program { static void Main(string[] args) { Console.WindowHeight = 46; Console.Write(buildMonths(new DateTime(1969, 1, 1))); Console....
http://rosettacode.org/wiki/Break_OO_privacy
Break OO privacy
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is...
#Perl
Perl
package Foo; sub new { my $class = shift; my $self = { _bar => 'I am ostensibly private' }; return bless $self, $class; }   sub get_bar { my $self = shift; return $self->{_bar}; }   package main; my $foo = Foo->new(); print "$_\n" for $foo->get_bar(), $foo->{_bar};
http://rosettacode.org/wiki/Break_OO_privacy
Break OO privacy
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is...
#Phix
Phix
without js -- (no class under p2js) class test private string msg = "this is a test" procedure show() ?this.msg end procedure end class test t = new() t.show() --?t.msg -- illegal --t.msg = "this is broken" -- illegal include builtins\structs.e as structs constant ctx...