task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#EasyLang
EasyLang
color3 0 1 1 len f[] 200 * 200 move 50 50 rect 0.5 0.5 f[100 * 200 + 100] = 1 n = 9000 while i < n repeat x = random 200 y = random 200 until f[y * 200 + x] <> 1 . while 1 = 1 xo = x yo = y x += random 3 - 1 y += random 3 - 1 if x < 0 or y < 0 or x >= 200 or y >= 200 break 1 ...
http://rosettacode.org/wiki/Bulls_and_cows
Bulls and cows
Bulls and Cows Task Create a four digit random number from the digits   1   to   9,   without duplication. The program should:   ask for guesses to this number   reject guesses that are malformed   print the score for the guess The score is computed as: The player wins if the guess is the same as the random...
#C
C
#include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <stdbool.h> #include <curses.h> #include <string.h>   #define MAX_NUM_TRIES 72 #define LINE_BEGIN 7 #define LAST_LINE 18   int yp=LINE_BEGIN, xp=0;   char number[5]; char guess[5];   #define MAX_STR 256 void mvaddstrf(int y, int x, const char *fmt, ......
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...
#Ruby
Ruby
STX = "\u0002" ETX = "\u0003"   def bwt(s) for c in s.split('') if c == STX or c == ETX then raise ArgumentError.new("Input can't contain STX or ETX") end end   ss = ("%s%s%s" % [STX, s, ETX]).split('') table = [] for i in 0 .. ss.length - 1 table.append(ss.join) ...
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...
#bash
bash
  caesar_cipher() {   # michaeltd 2019-11-30 # https://en.wikipedia.org/wiki/Caesar_cipher # E n ( x ) = ( x + n ) mod 26. # D n ( x ) = ( x − n ) mod 26.   local -a _ABC=( "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z" ) local -a _abc=( "a" "b" "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
#Groovy
Groovy
def ε = 1.0e-15 def φ = 1/ε   def generateAddends = { def addends = [] def n = 0.0 def fact = 1.0 while (true) { fact *= (n < 2 ? 1.0 : n) as double addends << 1.0/fact if (fact > φ) break // any further addends would not pass the tolerance test n++ } addends.sort...
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
#Haskell
Haskell
------ APPROXIMATION OF E OBTAINED AFTER N ITERATIONS ----   eApprox :: Int -> Double eApprox n = (sum . take n) $ (1 /) <$> scanl (*) 1 [1 ..]   --------------------------- TEST ------------------------- main :: IO () main = print $ eApprox 20
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
bullCow={Count[#1-#2,0],Length[#1\[Intersection]#2]-Count[#1-#2,0]}&; Module[{r,input,candidates=Permutations[Range[9],{4}]}, While[True, r=InputString[]; If[r===$Canceled,Break[], input=ToExpression/@StringSplit@r; If[Length@input!=3,Print["Input the guess, number of bulls, number of cows, delimited by space."],...
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...
#Perl
Perl
$PROGRAM = '\'   MY @START_DOW = (3, 6, 6, 2, 4, 0, 2, 5, 1, 3, 6, 1); MY @DAYS = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);   MY @MONTHS; FOREACH MY $M (0 .. 11) { FOREACH MY $R (0 .. 5) { $MONTHS[$M][$R] = JOIN " ", MAP { $_ < 1 || $_ > $DAYS[$M] ? " " : 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...
#PARI.2FGP
PARI/GP
use Inline C => q{ char *copy; char * c_dup(char *orig) { return copy = strdup(orig); } void c_free() { free(copy); } }; print c_dup('Hello'), "\n"; c_free();
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...
#Pascal
Pascal
use Inline C => q{ char *copy; char * c_dup(char *orig) { return copy = strdup(orig); } void c_free() { free(copy); } }; print c_dup('Hello'), "\n"; c_free();
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...
#Delphi
Delphi
foo()
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Smalltalk
Smalltalk
Object subclass: CantorSet [   | intervals |   CantorSet class >> new [^self basicNew initialize; yourself]   initialize [intervals := Array with: (CantorInterval from: 0 to: 1)]   split [intervals := intervals gather: [:each | each...
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: ...
#Racket
Racket
  #lang racket (define (fold f xs init) (if (empty? xs) init (f (first xs) (fold f (rest xs) init))))   (fold + '(1 2 3) 0)  ; the result is 6  
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: ...
#Raku
Raku
my @list = 1..10; say [+] @list; say [*] @list; say [~] @list; say min @list; say max @list; say [lcm] @list;
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...
#Sidef
Sidef
cartesian([[1,2], [3,4], [5,6]]).say cartesian([[1,2], [3,4], [5,6]], {|*arr| say arr })
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...
#Harbour
Harbour
  PROCEDURE Main() LOCAL i   FOR i := 0 to 15 ? PadL( i, 2 ) + ": " + hb_StrFormat("%d", Catalan( i )) NEXT   RETURN   STATIC FUNCTION Catalan( n ) LOCAL i, nCatalan := 1   FOR i := 1 TO n nCatalan := nCatalan * 2 * (2 * i - 1) / (i + 1) NEXT   RETURN nCatalan  
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...
#Haskell
Haskell
import qualified Text.Parsec as P   showExpansion :: String -> String showExpansion = (<>) . (<> "\n-->\n") <*> (either show unlines . P.parse parser [])   parser :: P.Parsec String u [String] parser = expansion P.anyChar   expansion :: P.Parsec String u Char -> P.Parsec String u [String] expansion = fmap expand . ...
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...
#D
D
import std.stdio;   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.2B.2B
C++
  #include <windows.h> #include <iostream>   //-------------------------------------------------------------------------------------------------- using namespace std;     //-------------------------------------------------------------------------------------------------- class calender { public: void drawCalender( ...
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...
#PHP
PHP
<?php class SimpleClass { private $answer = "hello\"world\nforever :)"; }   $class = new SimpleClass; ob_start();   // var_export() expects class to contain __set_state() method which would import // data from array. But let's ignore this and remove from result the method which // sets state and just leave data whi...
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...
#PicoLisp
PicoLisp
(class +Example) # "_name"   (dm T (Name) (=: "_name" Name) )   (dm string> () (pack "Hello, I am " (: "_name")) )   (====) # Close transient scope   (setq Foo (new '(+Example) "Eric"))
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...
#Python
Python
>>> class MyClassName: __private = 123 non_private = __private * 2     >>> mine = MyClassName() >>> mine.non_private 246 >>> mine.__private Traceback (most recent call last): File "<pyshell#23>", line 1, in <module> mine.__private AttributeError: 'MyClassName' object has no attribute '__private' >>> mine._MyCla...
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...
#Factor
Factor
USING: accessors images images.loader kernel literals math math.vectors random sets ; FROM: sets => in? ; EXCLUDE: sequences => move ; IN: rosetta-code.brownian-tree   CONSTANT: size 512 CONSTANT: num-particles 30000 CONSTANT: seed { 256 256 } CONSTANT: spawns { { 10 10 } { 502 10 } { 10 502 } { 502 502 } } CONSTANT: b...
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...
#C.23
C#
using System;   namespace BullsnCows { class Program {   static void Main(string[] args) { int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; KnuthShuffle<int>(ref nums); int[] chosenNum = new int[4]; Array.Copy(nums, chosenNum, 4);   ...
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...
#Rust
Rust
  use core::cmp::Ordering;   const STX: char = '\u{0002}'; const ETX: char = '\u{0003}';   // this compare uses simple alphabetical sort, but for the special characters (ETX, STX) // it sorts them later than alphanumeric characters pub fn special_cmp(lhs: &str, rhs: &str) -> Ordering { let mut iter1 = lhs.chars(); ...
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...
#Scala
Scala
import scala.collection.mutable.ArrayBuffer   object BWT { val STX = '\u0002' val ETX = '\u0003'   def bwt(s: String): String = { if (s.contains(STX) || s.contains(ETX)) { throw new RuntimeException("String can't contain STX or ETX") } var ss = STX + s + ETX var table = new ArrayBuffer[Strin...
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...
#BASIC256
BASIC256
  # Caeser Cipher # basic256 1.1.4.0   dec$ = "" type$ = "cleartext "   input "If decrypting enter " + "<d> " + " -- else press enter > ",dec$ # it's a klooj I know... input "Enter offset > ", iOffset   if dec$ = "d" then iOffset = 26 - iOffset type$ = "ciphertext " end if   input "Enter " + type$ + "> ", str$...
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
#Icon_and_Unicon
Icon and Unicon
$define EPSILON 1.0e-15   procedure main() local e0 local e := 2.0 local fact := 1 local n := 2   repeat { e0 := e fact *:= n n +:= 1 e +:= (1.0 / fact) if abs(e - e0) < EPSILON then break } write("computed e ", e) write("keyword &e ", &e) end
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
#IS-BASIC
IS-BASIC
100 PROGRAM "e.bas" 110 LET E1=0:LET E,N,N1=1 120 DO WHILE E<>E1 130 LET E1=E:LET E=E+1/N 140 LET N1=N1+1:LET N=N*N1 150 LOOP 160 PRINT "The value of e =";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...
#MATLAB
MATLAB
function BullsAndCowsPlayer % Plays the game Bulls and Cows as the player   % Generate list of all possible numbers nDigits = 4; lowVal = 1; highVal = 9; combs = nchoosek(lowVal:highVal, nDigits); nCombs = size(combs, 1); nPermsPerComb = factorial(nDigits); gList = zeros(nCombs.*nPermsPe...
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...
#Phix
Phix
return repeat(' ',left)&s&repeat(' ',right)
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...
#Perl
Perl
use Inline C => q{ char *copy; char * c_dup(char *orig) { return copy = strdup(orig); } void c_free() { free(copy); } }; print c_dup('Hello'), "\n"; c_free();
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...
#Phix
Phix
without js -- not from a browser, mate! constant shlwapi = open_dll("shlwapi.dll"), kernel32 = open_dll("kernel32.dll") constant xStrDup = define_c_func(shlwapi,"StrDupA",{C_PTR},C_PTR), xLocalFree = define_c_func(kernel32,"LocalFree",{C_PTR},C_PTR) constant HelloWorld = "Hello World!" atom pMem = c...
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...
#Dragon
Dragon
myMethod()
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Const WIDTH = 81 Const HEIGHT = 5 Dim lines(HEIGHT, WIDTH) As Char   Sub Init() For i = 0 To HEIGHT - 1 For j = 0 To WIDTH - 1 lines(i, j) = "*" Next Next End Sub   Sub Cantor(start As Integer, len As Integer, index As Inte...
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: ...
#REXX
REXX
/*REXX program demonstrates a method for catamorphism for some simple functions. */ @list= 1 2 3 4 5 6 7 8 9 10 say 'list:' fold(@list, "list") say ' sum:' fold(@list, "+" ) say 'prod:' fold(@list, "*...
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...
#SQL
SQL
-- set up list 1 CREATE TABLE L1 (VALUE INTEGER); INSERT INTO L1 VALUES (1); INSERT INTO L1 VALUES (2); -- set up list 2 CREATE TABLE L2 (VALUE INTEGER); INSERT INTO L2 VALUES (3); INSERT INTO L2 VALUES (4); -- get the product SELECT * FROM L1, L2;
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...
#Haskell
Haskell
-- Three infinite lists, corresponding to the three -- definitions in the problem statement.   cats1 :: [Integer] cats1 = (div . product . (enumFromTo . (2 +) <*> (2 *))) <*> (product . enumFromTo 1) <$> [0 ..]   cats2 :: [Integer] cats2 = 1 : fmap (\n -> sum (zipWith (*) (reverse (take n cats2)) cats2)) ...
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...
#J
J
  NB. legit { , and } do not follow a legit backslash: legit=: 1,_1}.4>(3;(_2[\"1".;._2]0 :0);('\';a.);0 _1 0 1)&;:&.(' '&,) 2 1 1 1 NB. result 0 or 1: initial state 2 2 1 2 NB. result 2 or 3: after receiving a non backslash 1 2 1 2 NB. result 4 or 5: after receiving a backslash )   expand=:3 :0 Ch=. u:inv y...
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...
#Delphi
Delphi
  program Brazilian_numbers;   {$APPTYPE CONSOLE}   {$R *.res}   uses System.SysUtils;   type TBrazilianNumber = record private FValue: Integer; FIsBrazilian: Boolean; FIsPrime: Boolean; class function SameDigits(a, b: Integer): Boolean; static; class function CheckIsBrazilian(a: Integer): Boo...
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...
#Clojure
Clojure
(require '[clojure.string :only [join] :refer [join]])   (def day-row "Su Mo Tu We Th Fr Sa")   (def col-width (count day-row))   (defn month-to-word "Translate a month from 0 to 11 into its word representation." [month] ((vec (.getMonths (new java.text.DateFormatSymbols))) month))   (defn month [date] (.get d...
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...
#Raku
Raku
class Foo { has $!shyguy = 42; } my Foo $foo .= new;   say $foo.^attributes.first('$!shyguy').get_value($foo);
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...
#Ruby
Ruby
  class Example def initialize @private_data = "nothing" # instance variables are always private end private def hidden_method "secret" end end example = Example.new p example.private_methods(false) # => [:hidden_method] #p example.hidden_method # => NoMethodError: private method `name' called 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...
#Scala
Scala
class Example(private var name: String) { override def toString = s"Hello, I am $name" }   object BreakPrivacy extends App { val field = classOf[Example].getDeclaredField("name") field.setAccessible(true)   val foo = new Example("Erik") println(field.get(foo)) field.set(foo, "Edith") println(foo) }
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...
#Fantom
Fantom
  using fwt using gfx   class Main { public static Void main () { particles := Particles (300, 200) 1000.times { particles.addParticle } // add 1000 particles Window // open up a display for the final tree { title = "Brownian Tree" EdgePane { center = ScrollPane { content...
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...
#C.2B.2B
C++
#include <iostream> #include <string> #include <algorithm> #include <cstdlib>   bool contains_duplicates(std::string s) { std::sort(s.begin(), s.end()); return std::adjacent_find(s.begin(), s.end()) != s.end(); }   void game() { typedef std::string::size_type index;   std::string symbols = "0123456789"; unsig...
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...
#Sidef
Sidef
class BurrowsWheelerTransform (String L = "\002") {   method encode(String s) { assert(!s.contains(L), "String cannot contain `#{L.dump}`") s = (L + s) s.len.of{|i| s.substr(i) + s.substr(0, i) }.sort.map{.last}.join }   method decode(String s) { var t = s.len.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...
#BBC_BASIC
BBC BASIC
plaintext$ = "Pack my box with five dozen liquor jugs" PRINT plaintext$   key% = RND(25) cyphertext$ = FNcaesar(plaintext$, key%) PRINT cyphertext$   decyphered$ = FNcaesar(cyphertext$, 26-key%) PRINT decyphered$   END   DEF FNcaesar(text$, key%) LOCAL I%, 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
#J
J
NB. rational one half times pi to the first power NB. pi to the power of negative two NB. two oh in base 111 NB. complex number length 1, angle in degrees 180 1r2p1 1p_2 111b20 1ad270 1.5708 0.101321 222 0j_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
#Java
Java
public class CalculateE { public static final double EPSILON = 1.0e-15;   public static void main(String[] args) { long fact = 1; double e = 2.0; int n = 2; double e0; do { e0 = e; fact *= n++; e += 1.0 / fact; } while (Math.abs...
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...
#Nim
Nim
import parseutils import random import sequtils import strformat import strutils   const Digits = "123456789" DigitSet = {Digits[0]..Digits[^1]} Size = 4 InvalidScore = -1   type   Digit = range['1'..'9'] Score = tuple[bulls, cows: int] HistItem = tuple[guess: string, bulls, cows: int]   #----------------...
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...
#PHP
PHP
<?PHP ECHO <<<REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT JANUARY FEBRUARY MARCH APRIL MAY JUNE MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA SO MO TU WE TH FR SA 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...
#PicoLisp
PicoLisp
(load "@lib/gcc.l")   (gcc "str" NIL # The 'gcc' function passes all text 'duptest ) # until /**/ to the C compiler   any duptest(any ex) { any x = evSym(cdr(ex)); // Accept a symbol (string) char str[bufSize(x)]; // Create a buffer to unpack the name char *s;   buf...
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...
#PL.2FI
PL/I
declare strdup entry (character (30) varyingz) options (fastcall16);   put (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...
#Dyalect
Dyalect
func foo() { } foo()
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Vlang
Vlang
const ( width = 81 height = 5 )   fn cantor(mut lines [][]u8, start int, len int, index int) { seg := len / 3 if seg == 0 { return } for i in index.. height { for j in start + seg..start + 2 * seg { lines[i][j] = ' '[0] } } cantor(mut lines, start, seg...
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Wren
Wren
var width = 81 var height = 5   var lines = [[]] * height for (i in 0...height) lines[i] = ["*"] * width   var cantor // recursive so need to declare variable first cantor = Fn.new { |start, len, index| var seg = (len/3).floor if (seg == 0) return for (i in index...height) { for (j in (start+seg)......
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: ...
#Ring
Ring
  n = list(10) for i = 1 to 10 n[i] = i next   see " +: " + cat(10,"+") + nl+ " -: " + cat(10,"-") + nl + " *: " + cat(10,"*") + nl + " /: " + cat(10,"/") + nl+ " ^: " + cat(10,"^") + nl + "min: " + cat(10,"min") + nl+ "max: " + cat(10,"max") + nl+ "avg: " + cat(10,"avg") + nl + ...
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: ...
#Ruby
Ruby
# sum: p (1..10).inject(:+) # smallest number divisible by all numbers from 1 to 20: p (1..20).inject(:lcm) #lcm: lowest common multiple  
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...
#Standard_ML
Standard ML
fun prodList (nil, _) = nil | prodList ((x::xs), ys) = map (fn y => (x,y)) ys @ prodList (xs, ys)   fun naryProdList zs = foldl (fn (xs, ys) => map op:: (prodList (xs, ys))) [[]] (rev zs)
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...
#Icon_and_Unicon
Icon and Unicon
procedure main() every writes(catalan(0 to 14)," ") end   procedure catalan(n) # return catalan(n) or fail static M initial M := table() n=0 & return 1   if n > 0 then return (n = 1) | \M[n] | ( M[n] := (2*(2*n-1)*catalan(n-1))/(n+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...
#Java
Java
public class BraceExpansion {   public static void main(String[] args) { for (String s : new String[]{"It{{em,alic}iz,erat}e{d,}, please.", "~/{Downloads,Pictures}/*.{jpg,gif,png}", "{,{,gotta have{ ,\\, again\\, }}more }cowbell!", "{}} some }{,{\\\\{ edge, edge} \\,}{ ca...
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.23
F#
  // Generate Brazilian sequence. Nigel Galloway: August 13th., 2019 let isBraz α=let mutable n,i,g=α,α+1,1 in (fun β->(while (i*g)<β do if g<α-1 then g<-g+1 else (n<-n*α; i<-n+i; g<-1)); β=i*g)   let Brazilian()=let rec fN n g=seq{if List.exists(fun α->α n) g then yield n yield! fN (...
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...
#COBOL
COBOL
  IDENTIFICATION DIVISION. PROGRAM-ID. CALEND. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. DATA DIVISION.   WORKING-STORAGE SECTION. 01 WS-DAY-NAMES-DEF. 03 FILLER PIC X(09) VALUE 'SUNDAY '. 03 FILLER PIC X(09) VALUE 'MONDAY '. 03 FILLER ...
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...
#Sidef
Sidef
class Example { has public = "foo" method init { self{:private} = "secret" } }   var obj = Example();   # Access public attributes say obj.public; #=> "foo" say obj{:public}; #=> "foo"   # Access private attributes say obj{:private}; #=> "secret"
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...
#Swift
Swift
struct Example { var notSoSecret = "Hello!" private var secret = 42 }   let e = Example() let mirror = Mirror(reflecting: e)   if let secret = mirror.children.filter({ $0.label == "secret" }).first?.value { print("Value of the secret is \(secret)") }  
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...
#Tcl
Tcl
package require Tcl 8.6   oo::class create Example { variable name constructor n {set name $n} method print {} {puts "Hello, I am $name"} } set e [Example new "Eric"] $e print set [info object namespace $e]::name "Edith" $e print
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...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Reflection   ' MyClass is a VB keyword. Public Class MyClazz Private answer As Integer = 42 End Class   Public Class Program Public Shared Sub Main() Dim myInstance = New MyClazz() Dim fieldInfo = GetType(MyClazz).GetField("answer", BindingFlags.NonPublic Or BindingFlags.Instance)...
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...
#Fortran
Fortran
program BrownianTree use RCImageBasic use RCImageIO   implicit none   integer, parameter :: num_particles = 1000 integer, parameter :: wsize = 800   integer, dimension(wsize, wsize) :: world type(rgbimage) :: gworld integer :: x, y   ! init seed call init_random_seed   world = 0 call dra...
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...
#Ceylon
Ceylon
import ceylon.random { DefaultRandom }   shared void run() {   value random = DefaultRandom();   function generateDigits() => random.elements(1..9).distinct.take(4).sequence();   function validate(String guess) { variable value ok = true; if (!guess.every((Character element) ...
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...
#Swift
Swift
import Foundation   private let stx = "\u{2}" private let etx = "\u{3}"   func bwt(_ str: String) -> String? { guard !str.contains(stx), !str.contains(etx) else { return nil }   let ss = stx + str + etx let table = ss.indices.map({i in ss[i...] + ss[ss.startIndex..<i] }).sorted()   return String(table.map...
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...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   ReadOnly STX As Char = Chr(&H2) ReadOnly ETX As Char = Chr(&H3)   Sub Rotate(Of T)(a As T()) Dim o = a.Last For i = a.Length - 1 To 1 Step -1 a(i) = a(i - 1) Next a(0) = o End Sub   Private Function Compare(s1 As String, s2 As String) As I...
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...
#Beads
Beads
beads 1 program 'Caesar cipher' calc main_init var str = "The five boxing wizards (🤖) jump quickly." log "Plain: {str}" str = Encrypt(str, 3) log "Encrypted: {str}" str = Decrypt(str, 3) log "Decrypted: {str}"   // encrypt a string by shifting the letters over by a number of slots // pass through any character...
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
#JavaScript
JavaScript
(() => { "use strict";   // - APPROXIMATION OF E OBTAINED AFTER N ITERATIONS --   // eApprox : Int -> Float const eApprox = n => sum( scanl(mul)(1)( enumFromTo(1)(n) ) .map(x => 1 / x) );     // ---------------------- TEST ---------...
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...
#Perl
Perl
#!/usr/bin/perl use warnings; use strict; use v5.10;   # Build a list of all possible solutions. The regular expression weeds # out numbers containing zeroes or repeated digits. See how Perl # automatically converts numbers to strings for us, just because we # use them as if they were strings: my @candidates = grep {...
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...
#PicoLisp
PicoLisp
(DE CAL (YEAR) (PRINL "====== " YEAR " ======") (FOR DAT (RANGE (DATE YEAR 1 1) (DATE YEAR 12 31)) (LET D (DATE DAT) (TAB (3 3 4 8) (WHEN (= 1 (CADDR D)) (GET `(INTERN (PACK (MAPCAR CHAR (42 77 111 110)))) (CADR D)) ) (CADDR D) (DAY DAT `(INTERN (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...
#Prolog
Prolog
:- module(plffi, [strdup/2]). :- use_foreign_library(plffi).
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...
#PureBasic
PureBasic
  ; Call_a_foreign_language_function.fasm -> Call_a_foreign_language_function.obj ; the assembler code...   ; format COFF or ; format COFF64 classic (DJGPP) variants of COFF file   ; format MS COFF or ; format MS COFF64 Microsoft's variants of COFF file   format MS COFF   include "Win32A.Inc"   section ".text" exec...
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.C3.A9j.C3.A0_Vu
Déjà Vu
# all functions used are from the standard library # calling a function with no arguments: random-int # calling a function with a fixed number of arguments: + 1 2 # calling a function with optional arguments: # optional arguments are not really possible as such # generally differently named functions are used: sort [ ...
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#XPL0
XPL0
proc Cantor(N, LineSeg, Len); \Delete middle third of LineSeg int N; char LineSeg; int Len, Third, I; [if N>0 and Len>1 then [Third:= Len/3; for I:= Third, 2*Third-1 do LineSeg(I):= ^ ; Cantor(N-1, LineSeg, Third); Cantor(N-1, LineSeg+2*Third, Third); ]; ];   char LineSeg, N; [LineSeg:= "########...
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#zkl
zkl
const WIDTH=81, HEIGHT=5; var lines=HEIGHT.pump(List,List.createLong(WIDTH,"\U2588;").copy); // full block   fcn cantor(start,len,index){ (seg:=len/3) or return(); foreach i,j in ([index..HEIGHT-1], [start + seg .. start + seg*2 - 1]){ lines[i][j]=" "; } cantor(start, seg, index + 1); cantor(start...
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: ...
#Run_BASIC
Run BASIC
for i = 1 to 10 :n(i) = i:next i   print " +: ";" ";cat(10,"+") print " -: ";" ";cat(10,"-") print " *: ";" ";cat(10,"*") print " /: ";" ";cat(10,"/") print " ^: ";" ";cat(10,"^") print "min: ";" ";cat(10,"min") print "max: ";" ";cat(10,"max") print "avg: ";" ";cat(10,"avg") print "cat: ";" ";cat(10,"cat")   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: ...
#Rust
Rust
fn main() { println!("Sum: {}", (1..10).fold(0, |acc, n| acc + n)); println!("Product: {}", (1..10).fold(1, |acc, n| acc * n)); let chars = ['a', 'b', 'c', 'd', 'e']; println!("Concatenation: {}", chars.iter().map(|&c| (c as u8 + 1) as char).collect::<String>()); }
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...
#Stata
Stata
. list   +-------+ | a b | |-------| 1. | 1 3 | 2. | 2 4 | +-------+   . fillin a b . list   +-----------------+ | a b _fillin | |-----------------| 1. | 1 3 0 | 2. | 1 4 1 | 3. | 2 3 1 | 4. | 2 4 0 | +----------------...
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...
#J
J
((! +:) % >:) i.15x 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...
#JavaScript
JavaScript
(function () { 'use strict'   // Index of any closing brace matching the opening // brace at iPosn, // with the indices of any immediately-enclosed commas. function bracePair(tkns, iPosn, iNest, lstCommas) { if (iPosn >= tkns.length || iPosn < 0) return null;   var t = tkns[iPosn], ...
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...
#Factor
Factor
USING: combinators grouping io kernel lists lists.lazy math math.parser math.primes.lists math.ranges namespaces prettyprint prettyprint.config sequences ;   : (brazilian?) ( n -- ? ) 2 over 2 - [a,b] [ >base all-equal? ] with find nip >boolean ;   : brazilian? ( n -- ? ) { { [ dup 7 < ] [ drop f ] } ...
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...
#Common_Lisp
Common Lisp
(ql:quickload '(date-calc))   (defparameter *day-row* "Su Mo Tu We Th Fr Sa") (defparameter *calendar-margin* 3)   (defun month-to-word (month) "Translate a MONTH from 1 to 12 into its word representation." (svref #("January" "February" "March" "April" "May" "June" "July" "August" "September" ...
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...
#Wren
Wren
class Safe { construct new() { _safe = 42 } // the field _safe is private safe { _safe } // provides public access to field doubleSafe { notSoSafe_ } // another public method notSoSafe_ { _safe * 2 } // intended only for private use but still accesible externally }   var s = 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...
#zkl
zkl
class C{var [private] v; fcn [private] f{123} class [private] D {}} C.v; C.f; C.D; // all generate NotFoundError exceptions However: C.fcns //-->L(Fcn(nullFcn),Fcn(f)) C.fcns[1]() //-->123 C.classes //-->L(Class(D)) C.vars //-->L(L("",Void)) (name,value) pairs
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...
#FreeBASIC
FreeBASIC
' version 16-03-2017 ' compile with: fbc -s gui   Const As ULong w = 400 Const As ULong w1 = w -1   Dim As Long x, y, lastx, lasty Dim As Long count, max = w * w \ 4   ScreenRes w, w, 8 ' windowsize 400 * 400, 8bit ' hit any key to stop or mouseclick on close window [X] WindowTitle "hit any key to stop and close the 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...
#Clojure
Clojure
  (ns bulls-and-cows)   (defn bulls [guess solution] (count (filter true? (map = guess solution))))   (defn cows [guess solution] (- (count (filter (set solution) guess)) (bulls guess solution)))   (defn valid-input? "checks whether the string is a 4 digit number with unique digits" [user-input] (if (re...
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...
#Wren
Wren
import "/sort" for Sort   var stx = "\x02" var etx = "\x03"   var bwt = Fn.new { |s| if (s.indexOf(stx) >= 0 || s.indexOf(etx) >= 0) return null s = stx + s + etx var len = s.count var table = [""] * len table[0] = s for (i in 1...len) table[i] = s[i..-1] + s[0...i] Sort.quick(table) var...
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...
#Befunge
Befunge
65+>>>>10p100p1>:v:+>#*,#g1#0-#0:#!<< "`"::_@#!`\*84:<~<$<^+"A"%*2+9<v"{"\` **-"A"-::0\`\55*`+#^_\0g+"4"+4^>\`*48
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
#jq
jq
1|exp #=> 2.718281828459045
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
#Julia
Julia
module NeperConstant   export NeperConst   struct NeperConst{T} val::T end   Base.show(io::IO, nc::NeperConst{T}) where T = print(io, "ℯ (", T, ") = ", nc.val)   function NeperConst{T}() where T local e::T = 2.0 local e2::T = 1.0 local den::(T ≡ BigFloat ? BigInt : Int128) = 1 local n::typeof(den) ...
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...
#Phix
Phix
with javascript_semantics constant line = " +---------+-----------------------------+-------+------+\n", digits = "123456789" function mask(integer ch) return power(2,ch-'1') end function function score(string guess, goal) integer bits = 0, bulls = 0, cows = 0 for i=1 to length(guess) do ...
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...
#PL.2FI
PL/I
(SUBRG, SIZE, FOFL): CALENDAR: PROCEDURE (YEAR) OPTIONS (MAIN); DECLARE YEAR CHARACTER (4) VARYING; DECLARE (A, B, C) (0:5,0:6) CHARACTER (3); DECLARE NAME_MONTH(12) STATIC CHARACTER (9) VARYING INITIAL ( 'JANUARY', 'FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE', 'JULY', 'AUGUST', 'SEP...
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...
#Python_2
Python
import ctypes libc = ctypes.CDLL("/lib/libc.so.6") libc.strcmp("abc", "def") # -1 libc.strcmp("hello", "hello") # 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...
#Racket
Racket
  #lang racket/base (require ffi/unsafe)   (provide strdup)   ;; Helper: create a Racket string from a C string pointer. (define make-byte-string (get-ffi-obj "scheme_make_byte_string" #f (_fun _pointer -> _scheme)))   ;; Take special care not to allow NULL (#f) to be passed as an input, ;; as that will crash strdup....