task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Bulls_and_cows/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 equivalent score to how your last guess was scored. Your next guess can be any number from the pruned list. Either you guess correctly or run out of numbers to guess, which indicates a problem with the scoring. Related tasks   Bulls and cows   Guess the number   Guess the number/With Feedback (Player)
#Ada
Ada
with Ada.Text_IO; with Ada.Containers.Vectors; with Ada.Numerics.Discrete_Random;   procedure Bulls_Player is   -- package for In-/Output of natural numbers package Nat_IO is new Ada.Text_IO.Integer_IO (Natural);   -- for comparing length of the vectors use type Ada.Containers.Count_Type;   -- number of digits Guessing_Length : constant := 4;   -- digit has to be from 1 to 9 type Digit is range 1 .. 9; -- a sequence has specified length of digits type Sequence is array (1 .. Guessing_Length) of Digit;   -- data structure to store the possible answers package Sequence_Vectors is new Ada.Containers.Vectors (Element_Type => Sequence, Index_Type => Positive);   -- check if sequence contains each digit only once function Is_Valid (S : Sequence) return Boolean is Appeared : array (Digit) of Boolean := (others => False); begin for I in S'Range loop if Appeared (S (I)) then return False; end if; Appeared (S (I))  := True; end loop; return True; end Is_Valid;   -- calculate all possible sequences and store them in the vector procedure Fill_Pool (Pool : in out Sequence_Vectors.Vector) is Finished : exception; -- count the sequence up by one function Next (S : Sequence) return Sequence is Result : Sequence := S; Index  : Positive := S'Last; begin loop -- overflow at a position causes next position to increase if Result (Index) = Digit'Last then Result (Index) := Digit'First; -- overflow at maximum position -- we have processed all possible values if Index = Result'First then raise Finished; end if; Index := Index - 1; else Result (Index) := Result (Index) + 1; return Result; end if; end loop; end Next; X  : Sequence := (others => 1); begin loop -- append all valid values if Is_Valid (X) then Pool.Append (X); end if; X := Next (X); end loop; exception when Finished => -- the exception tells us that we have added all possible values -- simply return and do nothing. null; end Fill_Pool;   -- generate a random index from the pool function Random_Index (Pool : Sequence_Vectors.Vector) return Positive is subtype Possible_Indexes is Positive range Pool.First_Index .. Pool.Last_Index; package Index_Random is new Ada.Numerics.Discrete_Random (Possible_Indexes); Index_Gen : Index_Random.Generator; begin Index_Random.Reset (Index_Gen); return Index_Random.Random (Index_Gen); end Random_Index;   -- get the answer from the player, simple validity tests procedure Get_Answer (S : Sequence; Bulls, Cows : out Natural) is Valid : Boolean := False; begin Bulls := 0; Cows  := 0; while not Valid loop -- output the sequence Ada.Text_IO.Put ("How is the score for:"); for I in S'Range loop Ada.Text_IO.Put (Digit'Image (S (I))); end loop; Ada.Text_IO.New_Line; begin Ada.Text_IO.Put ("Bulls:"); Nat_IO.Get (Bulls); Ada.Text_IO.Put ("Cows:"); Nat_IO.Get (Cows); if Bulls + Cows <= Guessing_Length then Valid := True; else Ada.Text_IO.Put_Line ("Invalid answer, try again."); end if; exception when others => null; end; end loop; end Get_Answer;   -- remove all sequences that wouldn't give an equivalent score procedure Strip (V  : in out Sequence_Vectors.Vector; S  : Sequence; Bulls, Cows : Natural) is function Has_To_Be_Removed (Position : Positive) return Boolean is Testant  : constant Sequence := V.Element (Position); Bull_Score : Natural  := 0; Cows_Score : Natural := 0; begin for I in Testant'Range loop for J in S'Range loop if Testant (I) = S (J) then -- same digit at same position: Bull! if I = J then Bull_Score := Bull_Score + 1; else Cow_Score := Cow_Score + 1; end if; end if; end loop; end loop; return Cow_Score /= Cows or else Bull_Score /= Bulls; end Has_To_Be_Removed; begin for Index in reverse V.First_Index .. V.Last_Index loop if Has_To_Be_Removed (Index) then V.Delete (Index); end if; end loop; end Strip;   -- main routine procedure Solve is All_Sequences : Sequence_Vectors.Vector; Test_Index  : Positive; Test_Sequence : Sequence; Bulls, Cows  : Natural; begin -- generate all possible sequences Fill_Pool (All_Sequences); loop -- pick at random Test_Index  := Random_Index (All_Sequences); Test_Sequence := All_Sequences.Element (Test_Index); -- ask player Get_Answer (Test_Sequence, Bulls, Cows); -- hooray, we have it! exit when Bulls = 4; All_Sequences.Delete (Test_Index); Strip (All_Sequences, Test_Sequence, Bulls, Cows); exit when All_Sequences.Length <= 1; end loop; if All_Sequences.Length = 0 then -- oops, shouldn't happen Ada.Text_IO.Put_Line ("I give up, there has to be a bug in" & "your scoring or in my algorithm."); else if All_Sequences.Length = 1 then Ada.Text_IO.Put ("The sequence you thought has to be:"); Test_Sequence := All_Sequences.First_Element; else Ada.Text_IO.Put ("The sequence you thought of was:"); end if; for I in Test_Sequence'Range loop Ada.Text_IO.Put (Digit'Image (Test_Sequence (I))); end loop; end if; end Solve;   begin -- output blah blah Ada.Text_IO.Put_Line ("Bulls and Cows, Your turn!"); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line ("Think of a sequence of" & Integer'Image (Guessing_Length) & " different digits."); Ada.Text_IO.Put_Line ("I will try to guess it. For each correctly placed"); Ada.Text_IO.Put_Line ("digit I score 1 Bull. For each digit that is on"); Ada.Text_IO.Put_Line ("the wrong place I score 1 Cow. After each guess"); Ada.Text_IO.Put_Line ("you tell me my score."); Ada.Text_IO.New_Line; Ada.Text_IO.Put_Line ("Let's start."); Ada.Text_IO.New_Line; -- solve the puzzle Solve; end Bulls_Player;
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 all UPPERCASE) This task also is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983. THE REAL PROGRAMMER'S NATURAL HABITAT "Taped to the wall is a line-printer Snoopy calender for the year 1969." Moreover this task is further inspired by the long lost corollary article titled: "Real programmers think in UPPERCASE"! Note: Whereas today we only need to worry about ASCII, UTF-8, UTF-16, UTF-32, UTF-7 and UTF-EBCDIC encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into 36-bit words as 6 lots of 6-bit characters. More extreme words sizes include 60-bit words of the CDC 6000 series computers. The Soviets even had a national character set that was inclusive of all 4-bit, 5-bit, 6-bit & 7-bit depending on how the file was opened... And one rogue Soviet university went further and built a 1.5-bit based computer. Of course... as us Boomers have turned into Geezers we have become HARD OF HEARING, and suffer from chronic Presbyopia, hence programming in UPPERCASE is less to do with computer architecture and more to do with practically. :-) For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. FYI: a nice ASCII art file of Snoopy can be found at textfiles.com. Save with a .txt extension. Trivia: The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed minuscule letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, majuscule letters, ended up in the harder to reach upper cases.
#AutoHotkey
AutoHotkey
CALENDAR(YR){ LASTDAY := [], DAY := [] TITLES = (LTRIM ______JANUARY_________________FEBRUARY_________________MARCH_______ _______APRIL____________________MAY____________________JUNE________ ________JULY___________________AUGUST_________________SEPTEMBER_____ ______OCTOBER_________________NOVEMBER________________DECEMBER______ ) STRINGSPLIT, TITLE, TITLES, % CHR(10) RES := "________________________________" YR CHR(13) CHR(10)   LOOP 4 { ; 4 VERTICAL SECTIONS DAY[1]:=YR SUBSTR("0" A_INDEX*3 -2, -1) 01 DAY[2]:=YR SUBSTR("0" A_INDEX*3 -1, -1) 01 DAY[3]:=YR SUBSTR("0" A_INDEX*3 , -1) 01 RES .= CHR(13) CHR(10) TITLE%A_INDEX% CHR(13) CHR(10) "SU MO TU WE TH FR SA SU MO TU WE TH FR SA SU MO TU WE TH FR SA" LOOP , 6 { ; 6 WEEKS MAX PER MONTH WEEK := A_INDEX, RES .= CHR(13) CHR(10) LOOP, 21 { ; 3 WEEKS TIMES 7 DAYS MON := CEIL(A_INDEX/7), THISWD := MOD(A_INDEX-1,7)+1 FORMATTIME, WD, % DAY[MON], WDAY ;~ MSGBOX % WD FORMATTIME, DD, % DAY[MON], % CHR(100) CHR(100) IF (WD>THISWD) { RES .= "__ " CONTINUE } DD := ((WEEK>3) && DD <10) ? "__" : DD, RES .= DD " ", LASTDAY[MON] := DAY[MON], DAY[MON] +=1, D RES .= ((WD=7) && A_INDEX < 21) ? "___" : "" FORMATTIME, DD, % DAY[MON], % CHR(100) CHR(100) } } RES .= CHR(13) CHR(10) } STRINGREPLACE, RES, RES,_,%A_SPACE%, ALL STRINGREPLACE, RES, RES,%A_SPACE%0,%A_SPACE%%A_SPACE%, ALL RETURN RES }
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 result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#Delphi
Delphi
  {$O myhello.obj}  
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 result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#Factor
Factor
FUNCTION: char* strdup ( c-string s ) ;   : my-strdup ( str -- str' ) strdup [ utf8 alien>string ] [ (free) ] bi ;
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#Arturo
Arturo
printHello: $[][ print "Hello World!" ]   sayHello: $[name][ print ["Hello" name "!"] ]   printAll: $[args][ loop args [arg][ print arg ] ]   getNumber: $[][3]   ; Calling a function that requires no arguments printHello   ; Calling a function with a fixed number of arguments sayHello "John"   ; Calling a function with a variable number of arguments printAll ["one" "two" "three"]   ; Using a function in statement context if true [printHello] print getNumber   ; Using a function in first-class context within an expression if getNumber=3 [print "yep, it worked"]   ; Obtaining the return value of a function: num: getNumber   print num  
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#IS-BASIC
IS-BASIC
100 PROGRAM "Cantor.bas" 110 GRAPHICS HIRES 2 120 SET PALETTE BLACK,WHITE 130 CALL CANTOR(28,500,1216,32) 140 DEF CANTOR(X,Y,L,HEIGHT) 150 IF L>3 THEN 160 PLOT X,Y;X+L,Y,X,Y+4;X+L,Y+4 170 CALL CANTOR(X,Y-HEIGHT,L/3,HEIGHT) 180 CALL CANTOR(X+2*L/3,Y-HEIGHT,L/3,HEIGHT) 190 END IF 200 END DEF
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#J
J
  odometer =: [: (4 $. $.) $&1   cantor_dust =: monad define shape =. ,~ 3 ^ y a =. shape $ ' ' i =. odometer shape < (}:"1) 1j1 #"1 '#' (([: <"1 [: ;/"1 (#~ 1 e."1 [: (,/"2) 3 3&#:)) i)}a )  
http://rosettacode.org/wiki/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to use a rational number data type. It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this: [a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1] Example The fraction   9/4   has odd continued fraction representation     2; 3, 1,     giving a binary representation of   100011, which means   9/4   appears as the   35th   term of the sequence. Task part 2 Find the position of the number   83116/51639   in the Calkin-Wilf sequence. See also Wikipedia entry: Calkin-Wilf tree Continued fraction Continued fraction/Arithmetic/Construct from rational number
#Prolog
Prolog
  % John Devou: 26-Nov-2021   % g(N,X):- consecutively generate in X the first N elements of the Calkin-Wilf sequence   g(N,[A/B|_]-_,A/B):- N > 0. g(N,[A/B|Ls]-[A/C,C/B|Ys],X):- N > 1, M is N-1, C is A+B, g(M,Ls-Ys,X). g(N,X):- g(N,[1/1|Ls]-Ls,X).   % t(A/B,X):- generate in X the index of A/B in the Calkin-Wilf sequence   t(A/1,S,C,X):- X is C*(2**(A-1+S)-S). t(A/B,S,C,X):- B > 1, divmod(A,B,M,N), T is 1-S, D is C*2**M, t(B/N,T,D,Y), X is Y + S*C*(2**M-1). t(A/B,X):- t(A/B,1,1,X), !.  
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)). note that 318682 {\displaystyle 318682} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ); note that 101558217124 {\displaystyle 101558217124} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); note that this implies that for Kaprekar numbers the checksum of k {\displaystyle k} equals the checksum of k 2 {\displaystyle k^{2}} . Demonstrate that your procedure can be used to generate or filter a range of numbers with the property c o 9 ( k ) = c o 9 ( k 2 ) {\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} is the residual of x {\displaystyle x} mod 9 {\displaystyle 9} ; the procedure can be extended to bases other than 9. Demonstrate your algorithm by generating or filtering a range of numbers with the property k % ( B a s e − 1 ) == ( k 2 ) % ( B a s e − 1 ) {\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. related tasks First perfect square in base N with N unique digits Kaprekar numbers
#Raku
Raku
sub cast-out(\BASE = 10, \MIN = 1, \MAX = BASE**2 - 1) { my \B9 = BASE - 1; my @ran = ($_ if $_ % B9 == $_**2 % B9 for ^B9); my $x = MIN div B9; gather loop { for @ran -> \n { my \k = B9 * $x + n; take k if k >= MIN; } $x++; } ...^ * > MAX; }   say cast-out; say cast-out 16; say cast-out 17;
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a method based on   Carmichael numbers,   as suggested in   Notes by G.J.O Jameson March 2010. Task Find Carmichael numbers of the form: Prime1 × Prime2 × Prime3 where   (Prime1 < Prime2 < Prime3)   for all   Prime1   up to   61. (See page 7 of   Notes by G.J.O Jameson March 2010   for solutions.) Pseudocode For a given   P r i m e 1 {\displaystyle Prime_{1}} for 1 < h3 < Prime1 for 0 < d < h3+Prime1 if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3 then Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d) next d if Prime2 is not prime Prime3 = 1 + (Prime1*Prime2/h3) next d if Prime3 is not prime next d if (Prime2*Prime3) mod (Prime1-1) not equal 1 Prime1 * Prime2 * Prime3 is a Carmichael Number related task Chernick's Carmichael numbers
#Prolog
Prolog
  show(Limit) :- forall( carmichael(Limit, P1, P2, P3, C), format("~w * ~w * ~w ~t~20| = ~w~n", [P1, P2, P3, C])).   carmichael(Upto, P1, P2, P3, X) :- between(2, Upto, P1), prime(P1), Limit is P1 - 1, between(2, Limit, H3), MaxD is H3 + P1 - 1, between(1, MaxD, D), (H3 + P1)*(P1 - 1) mod D =:= 0, -P1*P1 mod H3 =:= D mod H3, P2 is 1 + (P1 - 1)*(H3 + P1) div D, prime(P2), P3 is 1 + P1*P2 div H3, prime(P3), X is P1*P2*P3.   wheel235(L) :- W = [4, 2, 4, 2, 4, 6, 2, 6 | W], L = [1, 2, 2 | W].   prime(N) :- N >= 2, wheel235(W), prime(N, 2, W).   prime(N, D, _) :- D*D > N, !. prime(N, D, [A|As]) :- N mod D =\= 0, D2 is D + A, prime(N, D2, As).  
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:   Fold Wikipedia article:   Catamorphism
#Logtalk
Logtalk
  :- object(folding_examples).   :- public(show/0). show :- integer::sequence(1, 10, List), write('List: '), write(List), nl, meta::fold_left([Acc,N,Sum0]>>(Sum0 is Acc+N), 0, List, Sum), write('Sum of all elements: '), write(Sum), nl, meta::fold_left([Acc,N,Product0]>>(Product0 is Acc*N), 1, List, Product), write('Product of all elements: '), write(Product), nl, meta::fold_left([Acc,N,Concat0]>>(number_codes(N,NC), atom_codes(NA,NC), atom_concat(Acc,NA,Concat0)), '', List, Concat), write('Concatenation of all elements: '), write(Concat), nl.   :- end_object.  
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#TI-83_BASIC
TI-83 BASIC
"CATALAN 15→N seq(0,I,1,N+2)→L1 1→L1(1) For(I,1,N) For(J,I+1,2,-1) L1(J)+L1(J-1)→L1(J) End L1(I)→L1(I+1) For(J,I+2,2,-1) L1(J)+L1(J-1)→L1(J) End Disp L1(I+1)-L1(I) End
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#Vala
Vala
void main() { const int N = 15; uint64[] t = {0, 1}; for (int i = 1; i <= N; i++) { for (int j = i; j > 1; j--) t[j] = t[j] + t[j - 1]; t[i + 1] = t[i]; for (int j = i + 1; j > 1; j--) t[j] = t[j] + t[j - 1]; print(@"$(t[i + 1] - t[i]) "); } print("\n"); }
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Quackery
Quackery
[ $ 'Benjamin' ] is dog ( --> $ )   [ $ 'Samba' ] is Dog ( --> $ )   [ $ 'Bernie' ] is DOG ( --> $ )   say 'There are three dogs named ' dog echo$ say ', ' Dog echo$ say ', and ' DOG echo$ say '.' cr
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#R
R
dog <- 'Benjamin' Dog <- 'Samba' DOG <- 'Bernie'   # Having fun with cats and dogs cat('The three dogs are named ') cat(dog) cat(', ') cat(Dog) cat(' and ') cat(DOG) cat('.\n') # In one line it would be: # cat('The three dogs are named ', dog, ', ', Dog, ' and ', DOG, '.\n', sep = '')
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Racket
Racket
  #lang racket (define dog "Benjamin") (define Dog "Samba") (define DOG "Bernie")   (if (equal? dog DOG) (displayln (~a "There is one dog named " DOG ".")) (displayln (~a "The three dogs are named " dog ", " Dog ", and, " DOG ".")))  
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 your function/method, that the product of an empty list with any other list is empty. {1, 2} × {} = {} {} × {1, 2} = {} For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists. Use your n-ary Cartesian product function to show the following products: {1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1} {1, 2, 3} × {30} × {500, 100} {1, 2, 3} × {} × {500, 100}
#Modula-2
Modula-2
MODULE CartesianProduct; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE WriteInt(a : INTEGER); VAR buf : ARRAY[0..9] OF CHAR; BEGIN FormatString("%i", buf, a); WriteString(buf) END WriteInt;   PROCEDURE Cartesian(a,b : ARRAY OF INTEGER); VAR i,j : CARDINAL; BEGIN WriteString("["); FOR i:=0 TO HIGH(a) DO FOR j:=0 TO HIGH(b) DO IF (i>0) OR (j>0) THEN WriteString(","); END; WriteString("["); WriteInt(a[i]); WriteString(","); WriteInt(b[j]); WriteString("]") END END; WriteString("]"); WriteLn END Cartesian;   TYPE AP = ARRAY[0..1] OF INTEGER; E = ARRAY[0..0] OF INTEGER; VAR a,b : AP; BEGIN a := AP{1,2}; b := AP{3,4}; Cartesian(a,b);   a := AP{3,4}; b := AP{1,2}; Cartesian(a,b);   (* If there is a way to create an empty array, I do not know of it *)   ReadChar END CartesianProduct.
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#EDSAC_order_code
EDSAC order code
  [Calculation of Catalan numbers. EDSAC program, Initial Orders 2.]   [Define where to store the list of Catalan numbers.] T 54 K [store address in location 54, so that values are accessed by code letter C (for Catalan)] P 200 F [<------ address here]   [Modification of library subroutine P7. Prints signed integer up to 10 digits, right-justified. 54 storage locations; working position 4D. Must be loaded at an even address. Input: Number is at 0D.] T 56 K GKA3FT42@A47@T31@ADE10@T31@A48@T31@SDTDH44#@NDYFLDT4DS43@TF H17@S17@A43@G23@UFS43@T1FV4DAFG50@SFLDUFXFOFFFSFL4FT4DA49@T31@ A1FA43@G20@XFP1024FP610D@524D!FO46@O26@XFO46@SFL8FT4DE39@   [Main routine] T 120 K [load at 120] G K [set @ (theta) to load address] [Variables] [0] P F [index of Catalan number] [Constants] [1] P 7 D [maximum index required] [2] P D [single-word 1] [3] P 2 F [to change addresses by 2] [4] H #C [these 3 are used to manufacture EDSAC orders] [5] T #C [6] V #C [7] K 4096 F [(1) add to change T order into H order (2) teleprinter null] [8] # F [figures shift] [9]  ! F [space] [10] @ F [carriage return] [11] & F [line feed]   [Enter with acc = 0] [12] O 8 @ [set teleprinter to figures] T 4 D [clear 5F and sandwich bit] A 2 @ [load single-word 1] T 4 F [store as double word at 4D; clear acc] [Here with index in acc, Catalan number in 4D] [16] U @ [store index] L 1 F [times 4 by shifting] A 5 @ [make T order to store Catalan number] U 27 @ [plant in code] A 7 @ [make H order with same address] U 45 @ [plant in code] S 47 @ [make A order with same address] T 34 @ [plant in code] A 6 @ [load V order for start of list] T 46 @ [plant in code] A 4 D [Catalan number from temp store] [27] T #C [store in list (manufactured order)] T D [clear 1F and sandwich bit] A @ [load single-word index] T F [store as double word at 0D] [31] A 31 @ [for return from print subroutine] G 56 F [print index] O 9 @ [followed by space] [34] A #C [load Catalan number (manufactured order)] T D [to 0D for printing] [36] A 36 @ [for return from print subroutine] G 56 F [print Catalan number] O 10 @ [followed by new line] O 11 @ T 4 D [clear partial sum] A @ [load index] S 1 @ [reached the maximum?] E 64 @ [if so, jump to exit] [Inner loop to compute sum of products C{i}*C(n-1}] [44] T F [clear acc] [45] H #C [C{n-i} to mult reg (manufactured order)] [46] V #C [acc := C{i}*C{n-i} (manufactiured order)] [Multiply product by 2^34 (see preamble). The 'L F' order is also exploited above to convert an H order into an A order.] [47] L F [shift acc left by 13 (the maximum available)] L F [shift 13 more] L 64 F [shift 8 more, total 34] A 4 D [add partial sum] T 4 D [update partial sum] A 46 @ [inc i in V order] A 3 @ T 46 @ A 45 @ [dec (n - i) in H order] S 3 @ U 45 @ S 4 @ [is (n - i) now negative?] E 44 @ [if not, loop back] [Here with latest Catalan number in temp store 4D] T F [clear acc] A @ [load index] A 2 @ [add 1] E 16 @ [back to start of outer loop] [64] O 7 @ [exit; print null to flush teleprinter buffer] Z F [stop] E 12 Z [define entry point] P F [acc = 0 on entry]  
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Object_Pascal
Object Pascal
// Static (known in Pascal as class method) MyClass.method(someParameter);   // Instance myInstance.method(someParameter);  
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Objective-C
Objective-C
// Class [MyClass method:someParameter]; // or equivalently: id foo = [MyClass class]; [foo method:someParameter];   // Instance [myInstance method:someParameter];   // Method with multiple arguments [myInstance methodWithRed:arg1 green:arg2 blue:arg3];   // Method with no arguments [myInstance method];
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#OCaml
OCaml
my_obj#my_meth params
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#PARI.2FGP
PARI/GP
install("function_name","G","gp_name","./test.gp.so");
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#Pascal
Pascal
use Inline C => "DATA", ENABLE => "AUTOWRAP", LIBS => "-lm";   print 4*atan(1) . "\n";   __DATA__ __C__ double atan(double x);
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-sorting compression) rearranges a character string into runs of similar characters. This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. More importantly, the transformation is reversible, without needing to store any additional data. The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation. Source: Burrows–Wheeler transform
#BQN
BQN
stx←@+2 BWT ← { # Burrows-Wheeler Transform and its inverse as an invertible function 𝕊: "Input contained STX"!⊑stx¬∘∊𝕩 ⋄ (⍋↓𝕩) ⊏ stx∾𝕩; 𝕊⁼: 1↓(⊑˜⍟(↕≠𝕩)⟜⊑ ⍋)⊸⊏ 𝕩 }  
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-sorting compression) rearranges a character string into runs of similar characters. This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. More importantly, the transformation is reversible, without needing to store any additional data. The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation. Source: Burrows–Wheeler transform
#C
C
#include <string.h> #include <stdio.h> #include <stdlib.h>   const char STX = '\002', ETX = '\003';   int compareStrings(const void *a, const void *b) { char *aa = *(char **)a; char *bb = *(char **)b; return strcmp(aa, bb); }   int bwt(const char *s, char r[]) { int i, len = strlen(s) + 2; char *ss, *str; char **table; if (strchr(s, STX) || strchr(s, ETX)) return 1; ss = calloc(len + 1, sizeof(char)); sprintf(ss, "%c%s%c", STX, s, ETX); table = malloc(len * sizeof(const char *)); for (i = 0; i < len; ++i) { str = calloc(len + 1, sizeof(char)); strcpy(str, ss + i); if (i > 0) strncat(str, ss, i); table[i] = str; } qsort(table, len, sizeof(const char *), compareStrings); for(i = 0; i < len; ++i) { r[i] = table[i][len - 1]; free(table[i]); } free(table); free(ss); return 0; }   void ibwt(const char *r, char s[]) { int i, j, len = strlen(r); char **table = malloc(len * sizeof(const char *)); for (i = 0; i < len; ++i) table[i] = calloc(len + 1, sizeof(char)); for (i = 0; i < len; ++i) { for (j = 0; j < len; ++j) { memmove(table[j] + 1, table[j], len); table[j][0] = r[j]; } qsort(table, len, sizeof(const char *), compareStrings); } for (i = 0; i < len; ++i) { if (table[i][len - 1] == ETX) { strncpy(s, table[i] + 1, len - 2); break; } } for (i = 0; i < len; ++i) free(table[i]); free(table); }   void makePrintable(const char *s, char t[]) { strcpy(t, s); for ( ; *t != '\0'; ++t) { if (*t == STX) *t = '^'; else if (*t == ETX) *t = '|'; } }   int main() { int i, res, len; char *tests[6], *t, *r, *s; tests[0] = "banana"; tests[1] = "appellee"; tests[2] = "dogwood"; tests[3] = "TO BE OR NOT TO BE OR WANT TO BE OR NOT?"; tests[4] = "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES", tests[5] = "\002ABC\003"; for (i = 0; i < 6; ++i) { len = strlen(tests[i]); t = calloc(len + 1, sizeof(char)); makePrintable(tests[i], t); printf("%s\n", t); printf(" --> "); r = calloc(len + 3, sizeof(char)); res = bwt(tests[i], r); if (res == 1) { printf("ERROR: String can't contain STX or ETX\n"); } else { makePrintable(r, t); printf("%s\n", t); } s = calloc(len + 1, sizeof(char)); ibwt(r, s); makePrintable(s, t); printf(" --> %s\n\n", t); free(t); free(r); free(s); } return 0; }
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#11l
11l
F caesar(string, =key, decode = 0B) I decode key = 26 - key   V r = ‘ ’ * string.len L(c) string r[L.index] = S c ‘a’..‘z’ Char(code' (c.code - ‘a’.code + key) % 26 + ‘a’.code) ‘A’..‘Z’ Char(code' (c.code - ‘A’.code + key) % 26 + ‘A’.code) E c R r   V msg = ‘The quick brown fox jumped over the lazy dogs’ print(msg) V enc = caesar(msg, 11) print(enc) print(caesar(enc, 11, decode' 1B))
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
#BASIC
BASIC
n = 1  : n1 = 1 e1 = 0 : e = 1 / 1   while e <> e1 e1 = e e += 1 / n n1 += 1 n *= n1 end while   print "The value of 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
#Befunge
Befunge
52*92*1->01p:01g1-:v v *_$101p011p54*21p>:11g1+:01g*01p:11p/21g1-:v v < ^ _$$>\:^ ^ p12_$>+\:#^_$554**/@
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 equivalent score to how your last guess was scored. Your next guess can be any number from the pruned list. Either you guess correctly or run out of numbers to guess, which indicates a problem with the scoring. Related tasks   Bulls and cows   Guess the number   Guess the number/With Feedback (Player)
#AutoHotkey
AutoHotkey
length:=4, i:=0, S:=P(9,length)   Gui, Add, Text, w83 vInfo, Think of a %length%-digit number with no duplicate digits. Gui, Add, Edit, w40 vBulls Gui, Add, Text, x+3, Bulls Gui, Add, Edit, xm w40 vCows Gui, Add, Text, x+3, Cows Gui, Add, Button, xm w83 Default vDefault, Start Gui, Add, Edit, ym w130 r8 vHistory ReadOnly Gui, Show Return   ButtonStart: If Default = Restart Reload Gui, Submit, NoHide GuiControl, Focus, Bulls If (Bulls = length) { GuiControl, , Info, Guessed in %i% tries! GuiControl, , Default, Restart Default = Restart } Else { If i = 0 { GuiControl, , Default, Submit GuiControl, , History } Else { If (StrLen(Bulls) != 1 || StrLen(Cows) != 1) Return If Bulls is not digit Return If Cows is not digit Return GuiControl, , History, % History .= ": " Bulls " Bulls " Cows " Cows`n" GuiControl, , Bulls GuiControl, , Cows   S:=Remove(S, Guess, Bulls, Cows) } If !S { GuiControl, , Info, Invalid response. GuiControl, , Default, Restart Default = Restart } Else { Guess := SubStr(S,1,length) GuiControl, , History, % History . Guess GuiControl, , Info, Enter a single digit number of bulls and cows. i++ } } Return   GuiEscape: GuiClose: ExitApp   Remove(S, Guess, Bulls, Cows) { Loop, Parse, S, `n If (Bulls "," Cows = Response(Guess, A_LoopField)) S2 .= A_LoopField . "`n" Return SubStr(S2,1,-1) }   ; from http://rosettacode.org/wiki/Bulls and Cows#AutoHotkey Response(Guess,Code) { Bulls := 0, Cows := 0 Loop, % StrLen(Code) If (SubStr(Guess, A_Index, 1) = SubStr(Code, A_Index, 1)) Bulls++ Else If (InStr(Code, SubStr(Guess, A_Index, 1))) Cows++ Return Bulls "," Cows }   ; from http://rosettacode.org/wiki/Permutations#Alternate_Version P(n,k="",opt=0,delim="",str="") { i:=0 If !InStr(n,"`n") If n in 2,3,4,5,6,7,8,9 Loop, %n% n := A_Index = 1 ? A_Index : n "`n" A_Index Else Loop, Parse, n, %delim% n := A_Index = 1 ? A_LoopField : n "`n" A_LoopField If (k = "") RegExReplace(n,"`n","",k), k++ If k is not Digit Return "k must be a digit." If opt not in 0,1,2,3 Return "opt invalid." If k = 0 Return str Else Loop, Parse, n, `n If (!InStr(str,A_LoopField) || opt & 1) s .= (!i++ ? (opt & 2 ? str "`n" : "") : "`n" ) . P(n,k-1,opt,delim,str . A_LoopField . delim) Return s }
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 all UPPERCASE) This task also is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983. THE REAL PROGRAMMER'S NATURAL HABITAT "Taped to the wall is a line-printer Snoopy calender for the year 1969." Moreover this task is further inspired by the long lost corollary article titled: "Real programmers think in UPPERCASE"! Note: Whereas today we only need to worry about ASCII, UTF-8, UTF-16, UTF-32, UTF-7 and UTF-EBCDIC encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into 36-bit words as 6 lots of 6-bit characters. More extreme words sizes include 60-bit words of the CDC 6000 series computers. The Soviets even had a national character set that was inclusive of all 4-bit, 5-bit, 6-bit & 7-bit depending on how the file was opened... And one rogue Soviet university went further and built a 1.5-bit based computer. Of course... as us Boomers have turned into Geezers we have become HARD OF HEARING, and suffer from chronic Presbyopia, hence programming in UPPERCASE is less to do with computer architecture and more to do with practically. :-) For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. FYI: a nice ASCII art file of Snoopy can be found at textfiles.com. Save with a .txt extension. Trivia: The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed minuscule letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, majuscule letters, ended up in the harder to reach upper cases.
#BaCon
BaCon
DECLARE MON$[] = { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" } DECLARE MON[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } Y$ = "1969" ' Leap year INCR MON[1], IIF(MOD(VAL(Y$), 4) = 0 OR MOD(VAL(Y$), 100) = 0 AND MOD(VAL(Y$), 400) <> 0, 1, 0) PRINT ALIGN$("[SNOOPY HERE]", 132, 2) PRINT ALIGN$(Y$, 132, 2) FOR NR = 0 TO 11 ROW = 3 GOTOXY 1+(NR %6)*22, ROW+(NR/6)*9 PRINT ALIGN$(MON$[NR], 21, 2); INCR ROW GOTOXY 1+(NR %6)*22, ROW+(NR/6)*9 PRINT ALIGN$("MO TU WE TH FR SA SU", 21, 2); INCR ROW ' Each day FOR D = 1 TO MON[NR] ' Zeller J = VAL(LEFT$(Y$, 2)) K = VAL(MID$(Y$, 3, 2)) M = NR+1 IF NR < 2 THEN INCR M, 12 DECR K END IF H = (D + ((M+1)*26)/10 + K + (K/4) + (J/4) + 5*J) DAYNR = MOD(H, 7) - 2 IF DAYNR < 0 THEN INCR DAYNR, 7 IF DAYNR = 0 AND D > 1 THEN INCR ROW GOTOXY 1+(NR %6)*22+DAYNR*3, ROW+(NR/6)*9 PRINT D; NEXT NEXT
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 result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#FBSL
FBSL
c-library cstrings   \c #include <string.h> c-function strdup strdup a -- a ( c-string -- duped string ) c-function strlen strlen a -- n ( c-string -- length )   end-c-library   \ convenience function (not used here) : c-string ( addr u -- addr' ) tuck pad swap move pad + 0 swap c! pad ;   create test s" testing" mem, 0 c,   test strdup value duped   test . test 7 type \ testing cr duped . \ different address duped dup strlen type \ testing   duped free throw \ gforth ALLOCATE and FREE map directly to C's malloc() and 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 result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#Forth
Forth
c-library cstrings   \c #include <string.h> c-function strdup strdup a -- a ( c-string -- duped string ) c-function strlen strlen a -- n ( c-string -- length )   end-c-library   \ convenience function (not used here) : c-string ( addr u -- addr' ) tuck pad swap move pad + 0 swap c! pad ;   create test s" testing" mem, 0 c,   test strdup value duped   test . test 7 type \ testing cr duped . \ different address duped dup strlen type \ testing   duped free throw \ gforth ALLOCATE and FREE map directly to C's malloc() and 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   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#AutoHotkey
AutoHotkey
; Call a function without arguments: f()   ; Call a function with a fixed number of arguments: f("string", var, 15.5)   ; Call a function with optional arguments: f("string", var, 15.5)   ; Call a function with a variable number of arguments: f("string", var, 15.5)   ; Call a function with named arguments: ; AutoHotkey does not have named arguments. However, in v1.1+, ; we can pass an object to the function: f({named: "string", otherName: var, thirdName: 15.5})   ; Use a function in statement context: f(1), f(2) ; What is statement context?   ; No first-class functions in AHK   ; Obtaining the return value of a function: varThatGetsReturnValue := f(1, "a")   ; Cannot distinguish built-in functions   ; Subroutines are called with GoSub; functions are called as above. ; Subroutines cannot be passed variables   ; Stating whether arguments are passed by value or by reference: ; [v1.1.01+]: The IsByRef() function can be used to determine ; whether the caller supplied a variable for a given ByRef parameter. ; A variable cannot be passed by value to a byRef parameter. Instead, do this: f(tmp := varIdoNotWantChanged) ; the function f will receive the value of varIdoNotWantChanged, but any ; modifications will be made to the variable tmp.   ; Partial application is impossible.  
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Java
Java
public class App { private static final int WIDTH = 81; private static final int HEIGHT = 5;   private static char[][] lines; static { lines = new char[HEIGHT][WIDTH]; for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { lines[i][j] = '*'; } } }   private static void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { lines[i][j] = ' '; } } cantor(start, seg, index + 1); cantor(start + seg * 2, seg, index + 1); }   public static void main(String[] args) { cantor(0, WIDTH, 1); for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { System.out.print(lines[i][j]); } System.out.println(); } } }  
http://rosettacode.org/wiki/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to use a rational number data type. It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this: [a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1] Example The fraction   9/4   has odd continued fraction representation     2; 3, 1,     giving a binary representation of   100011, which means   9/4   appears as the   35th   term of the sequence. Task part 2 Find the position of the number   83116/51639   in the Calkin-Wilf sequence. See also Wikipedia entry: Calkin-Wilf tree Continued fraction Continued fraction/Arithmetic/Construct from rational number
#Python
Python
from fractions import Fraction from math import floor from itertools import islice, groupby     def cw(): a = Fraction(1) while True: yield a a = 1 / (2 * floor(a) + 1 - a)   def r2cf(rational): num, den = rational.numerator, rational.denominator while den: num, (digit, den) = den, divmod(num, den) yield digit   def get_term_num(rational): ans, dig, pwr = 0, 1, 0 for n in r2cf(rational): for _ in range(n): ans |= dig << pwr pwr += 1 dig ^= 1 return ans     if __name__ == '__main__': print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20))) x = Fraction(83116, 51639) print(f"\n{x} is the {get_term_num(x):_}'th term.")
http://rosettacode.org/wiki/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to use a rational number data type. It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this: [a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1] Example The fraction   9/4   has odd continued fraction representation     2; 3, 1,     giving a binary representation of   100011, which means   9/4   appears as the   35th   term of the sequence. Task part 2 Find the position of the number   83116/51639   in the Calkin-Wilf sequence. See also Wikipedia entry: Calkin-Wilf tree Continued fraction Continued fraction/Arithmetic/Construct from rational number
#Quackery
Quackery
[ $ "bigrat.qky" loadfile ] now!   [ ' [ [ 1 1 ] ] swap 1 - times [ dup -1 peek do 2dup proper 2drop 2 * n->v 2swap -v 1 n->v v+ v+ 1/v join nested join ] ] is calkin-wilf ( n --> [ )   [ 1 & ] is odd ( n --> b )   [ dup size odd not if [ -1 split do 1 - join 1 join ] ] is oddcf ( [ --> [ )   [ 0 swap reverse witheach [ i odd iff << done dup dip << bit 1 - | ] ] is rl->n ( [ --> n )   [ cf oddcf rl->n ] is cw-term ( n/d --> n )   20 calkin-wilf witheach [ do vulgar$ echo$ sp ] cr cr 83116 51639 cw-term echo
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)). note that 318682 {\displaystyle 318682} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ); note that 101558217124 {\displaystyle 101558217124} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); note that this implies that for Kaprekar numbers the checksum of k {\displaystyle k} equals the checksum of k 2 {\displaystyle k^{2}} . Demonstrate that your procedure can be used to generate or filter a range of numbers with the property c o 9 ( k ) = c o 9 ( k 2 ) {\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} is the residual of x {\displaystyle x} mod 9 {\displaystyle 9} ; the procedure can be extended to bases other than 9. Demonstrate your algorithm by generating or filtering a range of numbers with the property k % ( B a s e − 1 ) == ( k 2 ) % ( B a s e − 1 ) {\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. related tasks First perfect square in base N with N unique digits Kaprekar numbers
#REXX
REXX
/*REXX program demonstrates the casting─out─nines algorithm (with Kaprekar numbers). */ parse arg LO HI base . /*obtain optional arguments from the CL*/ if LO=='' | LO=="," then do; LO=1; HI=1000; end /*Not specified? Then use the default*/ if HI=='' | HI=="," then HI= LO /* " " " " " " */ if base=='' | base=="," then base= 10 /* " " " " " " */ numeric digits max(9, 2*length(HI**2) ) /*insure enough decimal digits for HI².*/ numbers= castOut(LO, HI, base) /*generate a list of (cast out) numbers*/ @cast_out= 'cast-out-' || (base-1) "test" /*construct a shortcut text for output.*/ say 'For' LO "through" HI', the following passed the' @cast_out":" say numbers; say /*display the list of cast out numbers.*/ q= HI - LO + 1 /*Q: is the range of numbers in list.*/ p= words(numbers) /*P" " " number " " " " */ pc= format(p/q * 100, , 2) / 1 || '%' /*calculate the percentage (%) cast out*/ say 'For' q "numbers," p 'passed the' @cast_out "("pc') for base' base"." if base\==10 then exit /*if radix isn't ten, then exit program*/ Kaps= Kaprekar(LO, HI) /*generate a list of Kaprekar numbers. */ say; say 'The Kaprekar numbers in the same range are:' Kaps say do i=1 for words(Kaps); x= word(Kaps, i) /*verify 'em in list.*/ if wordpos(x, numbers)\==0 then iterate /*it's OK so far ··· */ say 'Kaprekar number' x "isn't in the numbers list." /*oops─ay! */ exit 13 /*go spank the coder.*/ end /*i*/   say 'All Kaprekar numbers are in the' @cast_out "numbers list." /*OK*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ castOut: procedure; parse arg low,high,radix; rm= word(radix 10, 1) - 1; $= do j=low to word(high low, 1) /*test a range of numbers. */ if j//rm == j*j//rm then $= $ j /*did number pass the test?*/ end /*j*/ /* [↑] Then add # to list.*/ return strip($) /*strip and leading blanks from result.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ Kaprekar: procedure; parse arg L,H; $=; if L<=1 then $= 1 /*add unity if in range*/ do j=max(2, L) to H; s= j*j /*a slow way to find Kaprekar numbers. */ do m=1 for length(s)%2 if j==left(s, m) + substr(s, m+1) then do; $= $ j; leave; end end /*m*/ /* [↑] found a Kaprekar number. */ end /*j*/ return strip($) /*return Kaprekar numbers to invoker. */
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a method based on   Carmichael numbers,   as suggested in   Notes by G.J.O Jameson March 2010. Task Find Carmichael numbers of the form: Prime1 × Prime2 × Prime3 where   (Prime1 < Prime2 < Prime3)   for all   Prime1   up to   61. (See page 7 of   Notes by G.J.O Jameson March 2010   for solutions.) Pseudocode For a given   P r i m e 1 {\displaystyle Prime_{1}} for 1 < h3 < Prime1 for 0 < d < h3+Prime1 if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3 then Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d) next d if Prime2 is not prime Prime3 = 1 + (Prime1*Prime2/h3) next d if Prime3 is not prime next d if (Prime2*Prime3) mod (Prime1-1) not equal 1 Prime1 * Prime2 * Prime3 is a Carmichael Number related task Chernick's Carmichael numbers
#Python
Python
class Isprime(): ''' Extensible sieve of Eratosthenes   >>> isprime.check(11) True >>> isprime.multiples {2, 4, 6, 8, 9, 10} >>> isprime.primes [2, 3, 5, 7, 11] >>> isprime(13) True >>> isprime.multiples {2, 4, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 18, 20, 21, 22} >>> isprime.primes [2, 3, 5, 7, 11, 13, 17, 19] >>> isprime.nmax 22 >>> ''' multiples = {2} primes = [2] nmax = 2   def __init__(self, nmax): if nmax > self.nmax: self.check(nmax)   def check(self, n): if type(n) == float: if not n.is_integer(): return False n = int(n) multiples = self.multiples if n <= self.nmax: return n not in multiples else: # Extend the sieve primes, nmax = self.primes, self.nmax newmax = max(nmax*2, n) for p in primes: multiples.update(range(p*((nmax + p + 1) // p), newmax+1, p)) for i in range(nmax+1, newmax+1): if i not in multiples: primes.append(i) multiples.update(range(i*2, newmax+1, i)) self.nmax = newmax return n not in multiples   __call__ = check     def carmichael(p1): ans = [] if isprime(p1): for h3 in range(2, p1): g = h3 + p1 for d in range(1, g): if (g * (p1 - 1)) % d == 0 and (-p1 * p1) % h3 == d % h3: p2 = 1 + ((p1 - 1)* g // d) if isprime(p2): p3 = 1 + (p1 * p2 // h3) if isprime(p3): if (p2 * p3) % (p1 - 1) == 1: #print('%i X %i X %i' % (p1, p2, p3)) ans += [tuple(sorted((p1, p2, p3)))] return ans   isprime = Isprime(2)   ans = sorted(sum((carmichael(n) for n in range(62) if isprime(n)), [])) print(',\n'.join(repr(ans[i:i+5])[1:-1] for i in range(0, len(ans)+1, 5)))
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:   Fold Wikipedia article:   Catamorphism
#LOLCODE
LOLCODE
HAI 1.3   HOW IZ I reducin YR array AN YR size AN YR fn I HAS A val ITZ array'Z SRS 0 IM IN YR LOOP UPPIN YR i TIL BOTH SAEM i AN DIFF OF size AN 1 val R I IZ fn YR val AN YR array'Z SRS SUM OF i AN 1 MKAY IM OUTTA YR LOOP FOUND YR val IF U SAY SO   O HAI IM array I HAS A SRS 0 ITZ 1 I HAS A SRS 1 ITZ 2 I HAS A SRS 2 ITZ 3 I HAS A SRS 3 ITZ 4 I HAS A SRS 4 ITZ 5 KTHX   HOW IZ I add YR a AN YR b, FOUND YR SUM OF a AN b, IF U SAY SO HOW IZ I sub YR a AN YR b, FOUND YR DIFF OF a AN b, IF U SAY SO HOW IZ I mul YR a AN YR b, FOUND YR PRODUKT OF a AN b, IF U SAY SO   VISIBLE I IZ reducin YR array AN YR 5 AN YR add MKAY VISIBLE I IZ reducin YR array AN YR 5 AN YR sub MKAY VISIBLE I IZ reducin YR array AN YR 5 AN YR mul MKAY   KTHXBYE
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#VBScript
VBScript
dim t() if Wscript.arguments.count=1 then n=Wscript.arguments.item(0) else n=15 end if redim t(n+1) 't(*)=0 t(1)=1 for i=1 to n ip=i+1 for j = i to 1 step -1 t(j)=t(j)+t(j-1) next 'j t(i+1)=t(i) for j = i+1 to 1 step -1 t(j)=t(j)+t(j-1) next 'j Wscript.echo t(i+1)-t(i) next 'i
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#Visual_Basic
Visual Basic
  Sub catalan() Const n = 15 Dim t(n + 2) As Long Dim i As Integer, j As Integer t(1) = 1 For i = 1 To n For j = i + 1 To 2 Step -1 t(j) = t(j) + t(j - 1) Next j t(i + 1) = t(i) For j = i + 2 To 2 Step -1 t(j) = t(j) + t(j - 1) Next j Debug.Print i, t(i + 1) - t(i) Next i End Sub 'catalan
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Raku
Raku
my $dog = 'Benjamin'; my $Dog = 'Samba'; my $DOG = 'Bernie'; say "The three dogs are named $dog, $Dog, and $DOG."
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Retro
Retro
: dog ( -$ ) "Benjamin" ; : Dog ( -$ ) "Samba" ; : DOG ( -$ ) "Bernie" ;   DOG Dog dog "The three dogs are named %s, %s, and %s.\n" puts
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#REXX
REXX
/*REXX program demonstrate case insensitivity for simple REXX variable names. */   /* ┌──◄── all 3 left─hand side REXX variables are identical (as far as assignments). */ /* │ */ /* ↓ */ dog= 'Benjamin' /*assign a lowercase variable (dog)*/ Dog= 'Samba' /* " " capitalized " Dog */ DOG= 'Bernie' /* " an uppercase " DOG */   say center('using simple variables', 35, "─") /*title.*/ say   if dog\==Dog | DOG\==dog then say 'The three dogs are named:' dog"," Dog 'and' DOG"." else say 'There is just one dog named:' dog"."   /*stick a fork in it, we're all done. */
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 your function/method, that the product of an empty list with any other list is empty. {1, 2} × {} = {} {} × {1, 2} = {} For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists. Use your n-ary Cartesian product function to show the following products: {1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1} {1, 2, 3} × {30} × {500, 100} {1, 2, 3} × {} × {500, 100}
#Nim
Nim
iterator product[T1, T2](a: openArray[T1]; b: openArray[T2]): tuple[a: T1, b: T2] = # Yield the element of the cartesian product of "a" and "b". # Yield tuples rather than arrays as it allows T1 and T2 to be different.   for x in a: for y in b: yield (x, y)   #———————————————————————————————————————————————————————————————————————————————————————————————————   when isMainModule:   from seqUtils import toSeq import strformat from strutils import addSep   #-------------------------------------------------------------------------------------------------   proc `$`[T1, T2](t: tuple[a: T1, b: T2]): string = ## Overloading of `$` to display a tuple without the field names. &"({t.a}, {t.b})"   proc `$$`[T](s: seq[T]): string = ## New operator to display a sequence using mathematical set notation. result = "{" for item in s: result.addSep(", ", 1) result.add($item) result.add('}')   #-------------------------------------------------------------------------------------------------   const Empty = newSeq[int]() # Empty list of "int".   for (a, b) in [(@[1, 2], @[3, 4]), (@[3, 4], @[1, 2]), (@[1, 2], Empty ), ( Empty, @[1, 2])]:   echo &"{$$a} x {$$b} = {$$toSeq(product(a, b))}"
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#Eiffel
Eiffel
  class APPLICATION   create make   feature {NONE}   make do across 0 |..| 14 as c loop io.put_double (nth_catalan_number (c.item)) io.new_line end end   nth_catalan_number (n: INTEGER): DOUBLE --'n'th number in the sequence of Catalan numbers. require n_not_negative: n >= 0 local s, t: DOUBLE do if n = 0 then Result := 1.0 else t := 4 * n.to_double - 2 s := n.to_double + 1 Result := t / s * nth_catalan_number (n - 1) end end   end      
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Oforth
Oforth
1.2 sqrt
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#ooRexx
ooRexx
say "pi:" .circle~pi c=.circle~new(1) say "c~area:" c~area Do r=2 To 10 c.r=.circle~new(r) End say .circle~instances('') 'circles were created'   ::class circle ::method pi class -- a class method return 3.14159265358979323   ::method instances class -- another class method expose in use arg a If datatype(in)<>'NUM' Then in=0 If a<>'' Then in+=1 Return in   ::method init expose radius use arg radius self~class~instances('x')   ::method area -- an instance method expose radius Say self~class Say self return self~class~pi * radius * radius
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Perl
Perl
# Class method MyClass->classMethod($someParameter); # Equivalently using a class name my $foo = 'MyClass'; $foo->classMethod($someParameter);     # Instance method $myInstance->method($someParameter);   # Calling a method with no parameters $myInstance->anotherMethod;   # Class and instance method calls are made behind the scenes by getting the function from # the package and calling it on the class name or object reference explicitly MyClass::classMethod('MyClass', $someParameter); MyClass::method($myInstance, $someParameter);
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#Perl
Perl
use Inline C => "DATA", ENABLE => "AUTOWRAP", LIBS => "-lm";   print 4*atan(1) . "\n";   __DATA__ __C__ double atan(double x);
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#Phix
Phix
without js -- not from a browser, mate! string {libname,funcname} = iff(platform()=WINDOWS?{"user32","CharLowerA"}:{"libc","tolower"}) atom lib = open_dll(libname) integer func = define_c_func(lib,funcname,{C_INT},C_INT) if func=-1 then ?{{lower('A')}} -- (you don't //have// to crash!) else ?c_func(func,{'A'}) -- ('A'==65) end if
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-sorting compression) rearranges a character string into runs of similar characters. This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. More importantly, the transformation is reversible, without needing to store any additional data. The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation. Source: Burrows–Wheeler transform
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   namespace BurrowsWheeler { class Program { const char STX = (char)0x02; const char ETX = (char)0x03;   private static void Rotate(ref char[] a) { char t = a.Last(); for (int i = a.Length - 1; i > 0; --i) { a[i] = a[i - 1]; } a[0] = t; }   // For some reason, strings do not compare how whould be expected private static int Compare(string s1, string s2) { for (int i = 0; i < s1.Length && i < s2.Length; ++i) { if (s1[i] < s2[i]) { return -1; } if (s2[i] < s1[i]) { return 1; } } if (s1.Length < s2.Length) { return -1; } if (s2.Length < s1.Length) { return 1; } return 0; }   static string Bwt(string s) { if (s.Any(a => a == STX || a == ETX)) { throw new ArgumentException("Input can't contain STX or ETX"); } char[] ss = (STX + s + ETX).ToCharArray(); List<string> table = new List<string>(); for (int i = 0; i < ss.Length; ++i) { table.Add(new string(ss)); Rotate(ref ss); } table.Sort(Compare); return new string(table.Select(a => a.Last()).ToArray()); }   static string Ibwt(string r) { int len = r.Length; List<string> table = new List<string>(new string[len]); for (int i = 0; i < len; ++i) { for (int j = 0; j < len; ++j) { table[j] = r[j] + table[j]; } table.Sort(Compare); } foreach (string row in table) { if (row.Last() == ETX) { return row.Substring(1, len - 2); } } return ""; }   static string MakePrintable(string s) { return s.Replace(STX, '^').Replace(ETX, '|'); }   static void Main() { string[] tests = new string[] { "banana", "appellee", "dogwood", "TO BE OR NOT TO BE OR WANT TO BE OR NOT?", "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES", "\u0002ABC\u0003" };   foreach (string test in tests) { Console.WriteLine(MakePrintable(test)); Console.Write(" --> ");   string t = ""; try { t = Bwt(test); Console.WriteLine(MakePrintable(t)); } catch (Exception e) { Console.WriteLine("ERROR: {0}", e.Message); }   string r = Ibwt(t); Console.WriteLine(" --> {0}", r); Console.WriteLine(); } } } }
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#360_Assembly
360 Assembly
* Caesar cypher 04/01/2019 CAESARO PROLOG XPRNT PHRASE,L'PHRASE print phrase LH R3,OFFSET offset BAL R14,CYPHER call cypher LNR R3,R3 -offset BAL R14,CYPHER call cypher EPILOG CYPHER LA R4,REF(R3) @ref+offset MVC A,0(R4) for A to I MVC J,9(R4) for J to R MVC S,18(R4) for S to Z TR PHRASE,TABLE translate XPRNT PHRASE,L'PHRASE print phrase BR R14 return OFFSET DC H'22' between -25 and +25 PHRASE DC CL37'THE FIVE BOXING WIZARDS JUMP QUICKLY' DC CL26'ABCDEFGHIJKLMNOPQRSTUVWXYZ' REF DC CL26'ABCDEFGHIJKLMNOPQRSTUVWXYZ' DC CL26'ABCDEFGHIJKLMNOPQRSTUVWXYZ' TABLE DC CL256' ' translate table for TR ORG TABLE+C'A' A DS CL9 ORG TABLE+C'J' J DS CL9 ORG TABLE+C'S' S DS CL8 ORG YREGS END CAESARO
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
#Burlesque
Burlesque
  blsq ) 70rz?!{10 100**\/./}ms36.+Sh'.1iash 2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274  
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
#C
C
#include <stdio.h> #include <math.h>   int main(int argc, char* argv[]) { double e;   puts("The double precision in C give about 15 significant digits.\n" "Values below are presented with 16 digits after the decimal point.\n");   // The most direct way to compute Euler constant. // e = exp(1); printf("Euler constant e = %.16lf\n", e);   // The fast and independed method: e = lim (1 + 1/n)**n // int n = 8192; e = 1.0 + 1.0 / n; for (int i = 0; i < 13; i++) e *= e; printf("Euler constant e = %.16lf\n", e);   // Taylor expansion e = 1 + 1/1 + 1/2 + 1/2/3 + 1/2/3/4 + 1/2/3/4/5 + ... // Actually Kahan summation may improve the accuracy, but is not necessary. // const int N = 1000; double a[1000]; a[0] = 1.0; for (int i = 1; i < N; i++) { a[i] = a[i-1] / i; } e = 1.; for (int i = N - 1; i > 0; i--) e += a[i]; printf("Euler constant e = %.16lf\n", e);   return 0; }
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 equivalent score to how your last guess was scored. Your next guess can be any number from the pruned list. Either you guess correctly or run out of numbers to guess, which indicates a problem with the scoring. Related tasks   Bulls and cows   Guess the number   Guess the number/With Feedback (Player)
#BBC_BASIC
BBC BASIC
secret$ = "" REPEAT c$ = CHR$(&30 + RND(9)) IF INSTR(secret$, c$) = 0 secret$ += c$ UNTIL LEN(secret$) = 4   FOR i% = 1234 TO 9876 possible$ += STR$(i%) NEXT   PRINT "Guess a four-digit number with no digit used twice." guesses% = 0 REPEAT   IF LEN(possible$) = 4 THEN guess$ = possible$ ELSE guess$ = MID$(possible$, 4*RND(LEN(possible$) / 4) - 3, 4) ENDIF   PRINT '"Computer guesses " guess$ guesses% += 1   IF guess$ = secret$ PRINT "Correctly guessed after "; guesses% " guesses!" : END   PROCcount(secret$, guess$, bulls%, cows%) PRINT "giving " ;bulls% " bull(s) and " ;cows% " cow(s)."   i% = 1 REPEAT temp$ = MID$(possible$, i%, 4) PROCcount(temp$, guess$, testbulls%, testcows%) IF bulls%=testbulls% IF cows%=testcows% THEN i% += 4 ELSE possible$ = LEFT$(possible$, i%-1) + MID$(possible$, i%+4) ENDIF UNTIL i% > LEN(possible$)   IF INSTR(possible$, secret$) = 0 STOP   UNTIL FALSE END   DEF PROCcount(secret$, guess$, RETURN bulls%, RETURN cows%) LOCAL i%, c$ bulls% = 0 cows% = 0 FOR i% = 1 TO 4 c$ = MID$(secret$, i%, 1) IF MID$(guess$, i%, 1) = c$ THEN bulls% += 1 ELSE IF INSTR(guess$, c$) THEN cows% += 1 ENDIF ENDIF NEXT i% ENDPROC  
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 all UPPERCASE) This task also is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983. THE REAL PROGRAMMER'S NATURAL HABITAT "Taped to the wall is a line-printer Snoopy calender for the year 1969." Moreover this task is further inspired by the long lost corollary article titled: "Real programmers think in UPPERCASE"! Note: Whereas today we only need to worry about ASCII, UTF-8, UTF-16, UTF-32, UTF-7 and UTF-EBCDIC encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into 36-bit words as 6 lots of 6-bit characters. More extreme words sizes include 60-bit words of the CDC 6000 series computers. The Soviets even had a national character set that was inclusive of all 4-bit, 5-bit, 6-bit & 7-bit depending on how the file was opened... And one rogue Soviet university went further and built a 1.5-bit based computer. Of course... as us Boomers have turned into Geezers we have become HARD OF HEARING, and suffer from chronic Presbyopia, hence programming in UPPERCASE is less to do with computer architecture and more to do with practically. :-) For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. FYI: a nice ASCII art file of Snoopy can be found at textfiles.com. Save with a .txt extension. Trivia: The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed minuscule letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, majuscule letters, ended up in the harder to reach upper cases.
#BBC_BASIC
BBC BASIC
VDU 23,22,1056;336;8,16,16,128   YEAR = 1969 PRINT TAB(62) "[SNOOPY]" TAB(64); YEAR DIM DOM(5), MJD(5), DM(5), MONTH$(11) DAYS$ = "SU MO TU WE TH FR SA" MONTH$() = "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", \ \ "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"   FOR MONTH = 1 TO 7 STEP 6 PRINT FOR COL = 0 TO 5 MJD(COL) = FNMJD(1, MONTH + COL, YEAR) MONTH$ = MONTH$(MONTH + COL - 1) PRINT TAB(COL*22 + 11 - LEN(MONTH$)/2) MONTH$; NEXT FOR COL = 0 TO 5 PRINT TAB(COL*22 + 1) DAYS$; DM(COL) = FNDIM(MONTH + COL, YEAR) NEXT DOM() = 1 COL = 0 REPEAT DOW = FNDOW(MJD(COL)) IF DOM(COL)<=DM(COL) THEN PRINT TAB(COL*22 + DOW*3 + 1); DOM(COL); DOM(COL) += 1 MJD(COL) += 1 ENDIF IF DOW=6 OR DOM(COL)>DM(COL) COL = (COL + 1) MOD 6 UNTIL DOM(0)>DM(0) AND DOM(1)>DM(1) AND DOM(2)>DM(2) AND \ \ DOM(3)>DM(3) AND DOM(4)>DM(4) AND DOM(5)>DM(5) PRINT NEXT END   DEF FNMJD(D%,M%,Y%) : M% -= 3 : IF M% < 0 M% += 12 : Y% -= 1 = D% + (153*M%+2)DIV5 + Y%*365 + Y%DIV4 - Y%DIV100 + Y%DIV400 - 678882   DEF FNDOW(J%) = (J%+2400002) MOD 7   DEF FNDIM(M%,Y%) CASE M% OF WHEN 2: = 28 + (Y%MOD4=0) - (Y%MOD100=0) + (Y%MOD400=0) WHEN 4,6,9,11: = 30 OTHERWISE = 31 ENDCASE
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 result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#Fortran
Fortran
module c_api use iso_c_binding implicit none   interface function strdup(ptr) bind(C) import c_ptr type(c_ptr), value :: ptr type(c_ptr) :: strdup end function end interface   interface subroutine free(ptr) bind(C) import c_ptr type(c_ptr), value :: ptr end subroutine end interface   interface function puts(ptr) bind(C) import c_ptr, c_int type(c_ptr), value :: ptr integer(c_int) :: puts end function end interface end module   program c_example use c_api implicit none   character(20), target :: str = "Hello, World!" // c_null_char type(c_ptr) :: ptr integer(c_int) :: res   ptr = strdup(c_loc(str))   res = puts(c_loc(str)) res = puts(ptr)   print *, transfer(c_loc(str), 0_c_intptr_t), & transfer(ptr, 0_c_intptr_t) call free(ptr) end program
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#AWK
AWK
BEGIN { sayhello() # Call a function with no parameters in statement context b=squareit(3) # Obtain the return value from a function with a single parameter in first class context }
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#JavaScript
JavaScript
(() => { "use strict";   // -------------- CANTOR BOOL-INT PAIRS --------------   // cantor :: [(Bool, Int)] -> [(Bool, Int)] const cantor = xs => { const go = ([bln, n]) => bln && 1 < n ? (() => { const x = Math.floor(n / 3);   return [ [true, x], [false, x], [true, x] ]; })() : [ [bln, n] ];   return xs.flatMap(go); };   // ---------------------- TEST ----------------------- // main :: IO () const main = () => cantorLines(5);     // --------------------- DISPLAY ---------------------   // cantorLines :: Int -> String const cantorLines = n => take(n)( iterate(cantor)([ [true, 3 ** (n - 1)] ]) ) .map(showCantor) .join("\n");     // showCantor :: [(Bool, Int)] -> String const showCantor = xs => xs.map( ([bln, n]) => ( bln ? ( "*" ) : " " ).repeat(n) ) .join("");   // ---------------- GENERIC FUNCTIONS ----------------   // iterate :: (a -> a) -> a -> Gen [a] const iterate = f => // An infinite list of repeated // applications of f to x. function* (x) { let v = x;   while (true) { yield v; v = f(v); } };     // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = n => // The first n elements of a list, // string of characters, or stream. xs => "GeneratorFunction" !== xs .constructor.constructor.name ? ( xs.slice(0, n) ) : [].concat(...Array.from({ length: n }, () => { const x = xs.next();   return x.done ? [] : [x.value]; }));   // MAIN --- return main(); })();
http://rosettacode.org/wiki/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to use a rational number data type. It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this: [a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1] Example The fraction   9/4   has odd continued fraction representation     2; 3, 1,     giving a binary representation of   100011, which means   9/4   appears as the   35th   term of the sequence. Task part 2 Find the position of the number   83116/51639   in the Calkin-Wilf sequence. See also Wikipedia entry: Calkin-Wilf tree Continued fraction Continued fraction/Arithmetic/Construct from rational number
#Raku
Raku
my @calkin-wilf = Any, 1, {1 / (.Int × 2 + 1 - $_)} … *;   # Rational to Calkin-Wilf index sub r2cw (Rat $rat) { :2( join '', flat (flat (1,0) xx *) Zxx reverse r2cf $rat ) }   # The task   say "First twenty terms of the Calkin-Wilf sequence: ", @calkin-wilf[1..20]».&prat.join: ', ';   say "\n99991st through 100000th: ", (my @tests = @calkin-wilf[99_991 .. 100_000])».&prat.join: ', ';   say "\nCheck reversibility: ", @tests».Rat».&r2cw.join: ', ';   say "\n83116/51639 is at index: ", r2cw 83116/51639;     # Helper subs sub r2cf (Rat $rat is copy) { # Rational to continued fraction gather loop { $rat -= take $rat.floor; last if !$rat; $rat = 1 / $rat; } }   sub prat ($num) { # pretty Rat return $num unless $num ~~ Rat|FatRat; return $num.numerator if $num.denominator == 1; $num.nude.join: '/'; }
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)). note that 318682 {\displaystyle 318682} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ); note that 101558217124 {\displaystyle 101558217124} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); note that this implies that for Kaprekar numbers the checksum of k {\displaystyle k} equals the checksum of k 2 {\displaystyle k^{2}} . Demonstrate that your procedure can be used to generate or filter a range of numbers with the property c o 9 ( k ) = c o 9 ( k 2 ) {\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} is the residual of x {\displaystyle x} mod 9 {\displaystyle 9} ; the procedure can be extended to bases other than 9. Demonstrate your algorithm by generating or filtering a range of numbers with the property k % ( B a s e − 1 ) == ( k 2 ) % ( B a s e − 1 ) {\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. related tasks First perfect square in base N with N unique digits Kaprekar numbers
#Ring
Ring
  # Project : Casting out nines   co9(1, 10, 99, [1,9,45,55,99]) co9(1, 10, 1000, [1,9,45,55,99,297,703,999])   func co9(start,base,lim,kaprekars) c1=0 c2=0 s = [] for k = start to lim c1 = c1 + 1 if k % (base-1) = (k*k) % (base-1) c2 = c2 + 1 add(s,k) ok next msg = "Valid subset" + nl for i = 1 to len(kaprekars) if not find(s,kaprekars[i]) msg = "***Invalid***" + nl exit ok next showarray(s) see "Kaprekar numbers:" + nl showarray(kaprekars) see msg see "Trying " + c2 + " numbers instead of " + c1 + " saves " + (100-(c2/c1)*100) + "%" + nl + nl   func showarray(vect) see "{" svect = "" for n = 1 to len(vect) svect = svect + vect[n] + ", " next svect = left(svect, len(svect) - 2) see svect + "}" + nl  
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)). note that 318682 {\displaystyle 318682} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ); note that 101558217124 {\displaystyle 101558217124} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); note that this implies that for Kaprekar numbers the checksum of k {\displaystyle k} equals the checksum of k 2 {\displaystyle k^{2}} . Demonstrate that your procedure can be used to generate or filter a range of numbers with the property c o 9 ( k ) = c o 9 ( k 2 ) {\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} is the residual of x {\displaystyle x} mod 9 {\displaystyle 9} ; the procedure can be extended to bases other than 9. Demonstrate your algorithm by generating or filtering a range of numbers with the property k % ( B a s e − 1 ) == ( k 2 ) % ( B a s e − 1 ) {\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. related tasks First perfect square in base N with N unique digits Kaprekar numbers
#Ruby
Ruby
N = 2 base = 10 c1 = 0 c2 = 0   for k in 1 .. (base ** N) - 1 c1 = c1 + 1 if k % (base - 1) == (k * k) % (base - 1) then c2 = c2 + 1 print "%d " % [k] end end   puts print "Trying %d numbers instead of %d numbers saves %f%%" % [c2, c1, 100.0 - 100.0 * c2 / c1]
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a method based on   Carmichael numbers,   as suggested in   Notes by G.J.O Jameson March 2010. Task Find Carmichael numbers of the form: Prime1 × Prime2 × Prime3 where   (Prime1 < Prime2 < Prime3)   for all   Prime1   up to   61. (See page 7 of   Notes by G.J.O Jameson March 2010   for solutions.) Pseudocode For a given   P r i m e 1 {\displaystyle Prime_{1}} for 1 < h3 < Prime1 for 0 < d < h3+Prime1 if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3 then Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d) next d if Prime2 is not prime Prime3 = 1 + (Prime1*Prime2/h3) next d if Prime3 is not prime next d if (Prime2*Prime3) mod (Prime1-1) not equal 1 Prime1 * Prime2 * Prime3 is a Carmichael Number related task Chernick's Carmichael numbers
#Racket
Racket
  #lang racket (require math)   (for ([p1 (in-range 3 62)] #:when (prime? p1)) (for ([h3 (in-range 2 p1)]) (define g (+ p1 h3)) (let next ([d 1]) (when (< d g) (when (and (zero? (modulo (* g (- p1 1)) d)) (= (modulo (- (sqr p1)) h3) (modulo d h3))) (define p2 (+ 1 (quotient (* g (- p1 1)) d))) (when (prime? p2) (define p3 (+ 1 (quotient (* p1 p2) h3))) (when (and (prime? p3) (= 1 (modulo (* p2 p3) (- p1 1)))) (displayln (list p1 p2 p3 '=> (* p1 p2 p3)))))) (next (+ d 1))))))  
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a method based on   Carmichael numbers,   as suggested in   Notes by G.J.O Jameson March 2010. Task Find Carmichael numbers of the form: Prime1 × Prime2 × Prime3 where   (Prime1 < Prime2 < Prime3)   for all   Prime1   up to   61. (See page 7 of   Notes by G.J.O Jameson March 2010   for solutions.) Pseudocode For a given   P r i m e 1 {\displaystyle Prime_{1}} for 1 < h3 < Prime1 for 0 < d < h3+Prime1 if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3 then Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d) next d if Prime2 is not prime Prime3 = 1 + (Prime1*Prime2/h3) next d if Prime3 is not prime next d if (Prime2*Prime3) mod (Prime1-1) not equal 1 Prime1 * Prime2 * Prime3 is a Carmichael Number related task Chernick's Carmichael numbers
#Raku
Raku
for (2..67).grep: *.is-prime -> \Prime1 { for 1 ^..^ Prime1 -> \h3 { my \g = h3 + Prime1; for 0 ^..^ h3 + Prime1 -> \d { if (h3 + Prime1) * (Prime1 - 1) %% d and -Prime1**2 % h3 == d % h3 { my \Prime2 = floor 1 + (Prime1 - 1) * g / d; next unless Prime2.is-prime; my \Prime3 = floor 1 + Prime1 * Prime2 / h3; next unless Prime3.is-prime; next unless (Prime2 * Prime3) % (Prime1 - 1) == 1; say "{Prime1} × {Prime2} × {Prime3} == {Prime1 * Prime2 * Prime3}"; } } } }
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:   Fold Wikipedia article:   Catamorphism
#Lua
Lua
  table.unpack = table.unpack or unpack -- 5.1 compatibility local nums = {1,2,3,4,5,6,7,8,9}   function add(a,b) return a+b end   function mult(a,b) return a*b end   function cat(a,b) return tostring(a)..tostring(b) end   local function reduce(fun,a,b,...) if ... then return reduce(fun,fun(a,b),...) else return fun(a,b) end end   local arithmetic_sum = function (...) return reduce(add,...) end local factorial5 = reduce(mult,5,4,3,2,1)   print("Σ(1..9)  : ",arithmetic_sum(table.unpack(nums))) print("5!  : ",factorial5) print("cat {1..9}: ",reduce(cat,table.unpack(nums)))    
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#Wren
Wren
var n = 15 var t = List.filled(n+2, 0) t[1] = 1 for (i in 1..n) { if (i > 1) for (j in i..2) t[j] = t[j] + t[j-1] t[i+1] = t[i] if (i > 0) for (j in i+1..2) t[j] = t[j] + t[j-1] System.write("%(t[i+1]-t[i]) ") } System.print()
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Ring
Ring
  dog = "Benjamin" doG = "Smokey" Dog = "Samba" DOG = "Bernie" see "The 4 dogs are : " + dog + ", " + doG + ", " + Dog + " and " + DOG + "."  
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Ruby
Ruby
module FiveDogs dog = "Benjamin" dOg = "Dogley" doG = "Fido" Dog = "Samba" # this constant is FiveDogs::Dog DOG = "Bernie" # this constant is FiveDogs::DOG   names = [dog, dOg, doG, Dog, DOG] names.uniq! puts "There are %d dogs named %s." % [names.length, names.join(", ")] puts puts "The local variables are %s." % local_variables.join(", ") puts "The constants are %s." % constants.join(", ") end
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Run_BASIC
Run BASIC
  dog$ = "Benjamin" doG$ = "Smokey" Dog$ = "Samba" DOG$ = "Bernie" print "The 4 dogs are "; dog$; ", "; doG$; ", "; Dog$; " and "; DOG$; "."  
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 your function/method, that the product of an empty list with any other list is empty. {1, 2} × {} = {} {} × {1, 2} = {} For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists. Use your n-ary Cartesian product function to show the following products: {1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1} {1, 2, 3} × {30} × {500, 100} {1, 2, 3} × {} × {500, 100}
#OCaml
OCaml
let rec product l1 l2 = match l1, l2 with | [], _ | _, [] -> [] | h1::t1, h2::t2 -> (h1,h2)::(product [h1] t2)@(product t1 l2) ;;   product [1;2] [3;4];; (*- : (int * int) list = [(1, 3); (1, 4); (2, 3); (2, 4)]*) product [3;4] [1;2];; (*- : (int * int) list = [(3, 1); (3, 2); (4, 1); (4, 2)]*) product [1;2] [];; (*- : (int * 'a) list = []*) product [] [1;2];; (*- : ('a * int) list = []*)
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#Elixir
Elixir
defmodule Catalan do def cat(n), do: div( factorial(2*n), factorial(n+1) * factorial(n) )   defp factorial(n), do: fac1(n,1)   defp fac1(0, acc), do: acc defp fac1(n, acc), do: fac1(n-1, n*acc)   def cat_r1(0), do: 1 def cat_r1(n), do: Enum.sum(for i <- 0..n-1, do: cat_r1(i) * cat_r1(n-1-i))   def cat_r2(0), do: 1 def cat_r2(n), do: div(cat_r2(n-1) * 2 * (2*n - 1), n + 1)   def test do range = 0..14  :io.format "Directly:~n~p~n", [(for n <- range, do: cat(n))]  :io.format "1st recusive method:~n~p~n", [(for n <- range, do: cat_r1(n))]  :io.format "2nd recusive method:~n~p~n", [(for n <- range, do: cat_r2(n))] end end   Catalan.test
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Phix
Phix
without js -- (no class in p2js) class test string msg = "this is a test" procedure show() ?this.msg end procedure procedure inst() ?"this is dynamic" end procedure end class test t = new() t.show() -- prints "this is a test" t.inst() -- prints "this is dynamic" t.inst = t.show t.inst() -- prints "this is a test"
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#PHP
PHP
// Static method MyClass::method($someParameter); // In PHP 5.3+, static method can be called on a string of the class name $foo = 'MyClass'; $foo::method($someParameter);     // Instance method $myInstance->method($someParameter);
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#PicoLisp
PicoLisp
(foo> MyClass) (foo> MyObject)
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#PicoLisp
PicoLisp
(load "@lib/gcc.l")   (gcc "x11" '("-lX11") 'xOpenDisplay 'xCloseDisplay)   #include <X11/Xlib.h>   any xOpenDisplay(any ex) { any x = evSym(cdr(ex)); // Get display name char display[bufSize(x)]; // Create a buffer for the name   bufString(x, display); // Upack the name return boxCnt((long)XOpenDisplay(display)); }   any xCloseDisplay(any ex) { return boxCnt(XCloseDisplay((Display*)evCnt(ex, cdr(ex)))); } /**/   # With that we can open and close the display: : (setq Display (xOpenDisplay ":0.7")) # Wrong -> 0 : (setq Display (xOpenDisplay ":0.0")) # Correct -> 158094320 : (xCloseDisplay Display) -> 0
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#PowerBASIC
PowerBASIC
#INCLUDE "Win32API.inc"   FUNCTION PBMAIN () AS LONG DIM hWnd AS LONG DIM msg AS ASCIIZ * 14, titl AS ASCIIZ * 8   hWnd = LoadLibrary ("user32") msg = "Hello, world!" titl = "Example" IF ISTRUE (hWnd) THEN funcAddr& = GetProcAddress (hWnd, "MessageBoxA") IF ISTRUE (funcAddr&) THEN ASM push 0& tAdr& = VARPTR(titl) ASM push tAdr& mAdr& = VARPTR(msg) ASM push mAdr& ASM push 0& CALL DWORD funcAddr& ELSE GOTO epicFail END IF ELSE GOTO epicFail END IF   GOTO getMeOuttaHere   epicFail: MSGBOX msg, , titl   getMeOuttaHere: IF ISTRUE(hWnd) THEN tmp& = FreeLibrary (hWnd) IF ISFALSE(tmp&) THEN MSGBOX "Error freeing library... [shrug]" END IF END FUNCTION
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-sorting compression) rearranges a character string into runs of similar characters. This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. More importantly, the transformation is reversible, without needing to store any additional data. The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation. Source: Burrows–Wheeler transform
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <vector>   const int STX = 0x02; const int ETX = 0x03;   void rotate(std::string &a) { char t = a[a.length() - 1]; for (int i = a.length() - 1; i > 0; i--) { a[i] = a[i - 1]; } a[0] = t; }   std::string bwt(const std::string &s) { for (char c : s) { if (c == STX || c == ETX) { throw std::runtime_error("Input can't contain STX or ETX"); } }   std::string ss; ss += STX; ss += s; ss += ETX;   std::vector<std::string> table; for (size_t i = 0; i < ss.length(); i++) { table.push_back(ss); rotate(ss); } //table.sort(); std::sort(table.begin(), table.end());   std::string out; for (auto &s : table) { out += s[s.length() - 1]; } return out; }   std::string ibwt(const std::string &r) { int len = r.length(); std::vector<std::string> table(len); for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { table[j] = r[j] + table[j]; } std::sort(table.begin(), table.end()); } for (auto &row : table) { if (row[row.length() - 1] == ETX) { return row.substr(1, row.length() - 2); } } return {}; }   std::string makePrintable(const std::string &s) { auto ls = s; for (auto &c : ls) { if (c == STX) { c = '^'; } else if (c == ETX) { c = '|'; } } return ls; }   int main() { auto tests = { "banana", "appellee", "dogwood", "TO BE OR NOT TO BE OR WANT TO BE OR NOT?", "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES", "\u0002ABC\u0003" };   for (auto &test : tests) { std::cout << makePrintable(test) << "\n"; std::cout << " --> ";   std::string t; try { t = bwt(test); std::cout << makePrintable(t) << "\n"; } catch (std::runtime_error &e) { std::cout << "Error " << e.what() << "\n"; }   std::string r = ibwt(t); std::cout << " --> " << r << "\n\n"; }   return 0; }
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys. Caesar cipher is identical to Vigenère cipher with a key of length 1. Also, Rot-13 is identical to Caesar cipher with key 13. Related tasks Rot-13 Substitution Cipher Vigenère Cipher/Cryptanalysis
#8th
8th
\ Ensure the output char is in the correct range: : modulate \ char base -- char tuck n:- 26 n:+ 26 n:mod n:+ ;   \ Symmetric Caesar cipher. Input is text and number of characters to advance \ (or retreat, if negative). That value should be in the range 1..26 : caesar \ intext key -- outext >r ( \ Ignore anything below '.' as punctuation: dup '. n:> if \ Do the conversion dup r@ n:+ swap \ Wrap appropriately 'A 'Z between if 'A else 'a then modulate then ) s:map rdrop ;   "The five boxing wizards jump quickly!" dup . cr 1 caesar dup . cr -1 caesar . cr bye
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
#C.23
C#
using System;   namespace CalculateE { class Program { public const double EPSILON = 1.0e-15;   static void Main(string[] args) { ulong fact = 1; double e = 2.0; double e0; uint n = 2; do { e0 = e; fact *= n++; e += 1.0 / fact; } while (Math.Abs(e - e0) >= EPSILON); Console.WriteLine("e = {0:F15}", 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 equivalent score to how your last guess was scored. Your next guess can be any number from the pruned list. Either you guess correctly or run out of numbers to guess, which indicates a problem with the scoring. Related tasks   Bulls and cows   Guess the number   Guess the number/With Feedback (Player)
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h>   char *list; const char *line = "--------+--------------------\n"; int len = 0;   int irand(int n) { int r, rand_max = RAND_MAX - (RAND_MAX % n); do { r = rand(); } while(r >= rand_max); return r / (rand_max / n); }   char* get_digits(int n, char *ret) { int i, j; char d[] = "123456789";   for (i = 0; i < n; i++) { j = irand(9 - i); ret[i] = d[i + j]; if (j) d[i + j] = d[i], d[i] = ret[i]; } return ret; }   #define MASK(x) (1 << (x - '1')) int score(const char *digits, const char *guess, int *cow) { int i, bits = 0, bull = *cow = 0;   for (i = 0; guess[i] != '\0'; i++) if (guess[i] != digits[i]) bits |= MASK(digits[i]); else ++bull;   while (i--) *cow += ((bits & MASK(guess[i])) != 0);   return bull; }   void pick(int n, int got, int marker, char *buf) { int i, bits = 1; if (got >= n) strcpy(list + (n + 1) * len++, buf); else for (i = 0; i < 9; i++, bits *= 2) { if ((marker & bits)) continue; buf[got] = i + '1'; pick(n, got + 1, marker | bits, buf); } }   void filter(const char *buf, int n, int bull, int cow) { int i = 0, c; char *ptr = list;   while (i < len) { if (score(ptr, buf, &c) != bull || c != cow) strcpy(ptr, list + --len * (n + 1)); else ptr += n + 1, i++; } }   void game(const char *tgt, char *buf) { int i, p, bull, cow, n = strlen(tgt);   for (i = 0, p = 1; i < n && (p *= 9 - i); i++); list = malloc(p * (n + 1));   pick(n, 0, 0, buf); for (p = 1, bull = 0; n - bull; p++) { strcpy(buf, list + (n + 1) * irand(len)); bull = score(tgt, buf, &cow);   printf("Guess %2d| %s (from: %d)\n" "Score | %d bull, %d cow\n%s", p, buf, len, bull, cow, line);   filter(buf, n, bull, cow); } }   int main(int c, char **v) { int n = c > 1 ? atoi(v[1]) : 4;   char secret[10] = "", answer[10] = ""; srand(time(0));   printf("%sSecret | %s\n%s", line, get_digits(n, secret), line); game(secret, answer);   return 0; }
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 all UPPERCASE) This task also is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983. THE REAL PROGRAMMER'S NATURAL HABITAT "Taped to the wall is a line-printer Snoopy calender for the year 1969." Moreover this task is further inspired by the long lost corollary article titled: "Real programmers think in UPPERCASE"! Note: Whereas today we only need to worry about ASCII, UTF-8, UTF-16, UTF-32, UTF-7 and UTF-EBCDIC encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into 36-bit words as 6 lots of 6-bit characters. More extreme words sizes include 60-bit words of the CDC 6000 series computers. The Soviets even had a national character set that was inclusive of all 4-bit, 5-bit, 6-bit & 7-bit depending on how the file was opened... And one rogue Soviet university went further and built a 1.5-bit based computer. Of course... as us Boomers have turned into Geezers we have become HARD OF HEARING, and suffer from chronic Presbyopia, hence programming in UPPERCASE is less to do with computer architecture and more to do with practically. :-) For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. FYI: a nice ASCII art file of Snoopy can be found at textfiles.com. Save with a .txt extension. Trivia: The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed minuscule letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, majuscule letters, ended up in the harder to reach upper cases.
#C
C
tcc -DSTRUCT=struct -DCONST=const -DINT=int -DCHAR=char -DVOID=void -DMAIN=main -DIF=if -DELSE=else -DWHILE=while -DFOR=for -DDO=do -DBREAK=break -DRETURN=return -DPUTCHAR=putchar UCCALENDAR.c
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 result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   'Using StrDup function in Shlwapi.dll Dim As Any Ptr library = DyLibLoad("Shlwapi") Dim strdup As Function (ByVal As Const ZString Ptr) As ZString Ptr strdup = DyLibSymbol(library, "StrDupA")   'Using LocalFree function in kernel32.dll Dim As Any Ptr library2 = DyLibLoad("kernel32") Dim localfree As Function (ByVal As Any Ptr) As Any Ptr localfree = DyLibSymbol(library2, "LocalFree")   Dim As ZString * 10 z = "duplicate" '' 10 characters including final zero byte Dim As Zstring Ptr pcz = strdup(@z) '' pointer to the duplicate string Print *pcz '' print duplicate string by dereferencing pointer localfree(pcz) '' free the memory which StrDup allocated internally pcz = 0 '' set pointer to null DyLibFree(library) '' unload first dll DyLibFree(library2) '' unload second fll End
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 result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#Go
Go
package main   // #include <string.h> // #include <stdlib.h> import "C" import ( "fmt" "unsafe" )   func main() { // a go string go1 := "hello C" // allocate in C and convert from Go representation to C representation c1 := C.CString(go1) // go string can now be garbage collected go1 = "" // strdup, per task. this calls the function in the C library. c2 := C.strdup(c1) // free the source C string. again, this is free() in the C library. C.free(unsafe.Pointer(c1)) // create a new Go string from the C copy go2 := C.GoString(c2) // free the C copy C.free(unsafe.Pointer(c2)) // demonstrate we have string contents intact fmt.Println(go2) }
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#Axe
Axe
NOARG() ARGS(1,5,42)
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#jq
jq
# cantor(width; height) def cantor($w; $h): def init: [range(0; $h) | [range(0; $w) | "*"]];   def cantor($start; $leng; $ix): ($leng/3|floor) as $seg | if $seg == 0 then . else reduce range($ix; $h) as $i (.; reduce range($start+$seg; $start + 2*$seg) as $j (.; .[$i][$j] = " ")) | cantor($start; $seg; $ix+1) | cantor($start + 2*$seg; $seg; $ix+1) end ; init | cantor(0; $w; 1);   def pp: .[] | join("");   cantor($width; $height) | pp
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Julia
Julia
const width = 81 const height = 5   function cantor!(lines, start, len, idx) seg = div(len, 3) if seg > 0 for i in idx+1:height, j in start + seg + 1: start + seg * 2 lines[i, j] = ' ' end cantor!(lines, start, seg, idx + 1) cantor!(lines, start + 2 * seg, seg, idx + 1) end end   lines = fill(UInt8('#'), height, width) cantor!(lines, 0, width, 1)   for i in 1:height, j in 1:width print(Char(lines[i, j]), j == width ? "\n" : "") end  
http://rosettacode.org/wiki/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to use a rational number data type. It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this: [a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1] Example The fraction   9/4   has odd continued fraction representation     2; 3, 1,     giving a binary representation of   100011, which means   9/4   appears as the   35th   term of the sequence. Task part 2 Find the position of the number   83116/51639   in the Calkin-Wilf sequence. See also Wikipedia entry: Calkin-Wilf tree Continued fraction Continued fraction/Arithmetic/Construct from rational number
#REXX
REXX
/*REXX pgm finds the Nth value of the Calkin─Wilf sequence (which will be a fraction),*/ /*────────────────────── or finds which sequence number contains a specified fraction). */ numeric digits 2000 /*be able to handle ginormic integers. */ parse arg LO HI te . /*obtain optional arguments from the CL*/ if LO=='' | LO=="," then LO= 1 /*Not specified? Then use the default.*/ if HI=='' | HI=="," then HI= 20 /* " " " " " " */ if te=='' | te=="," then te= '/' /* " " " " " " */ if datatype(LO, 'W') then call CW_terms /*Is LO numeric? Then show some terms.*/ if pos('/', te)>0 then call CW_frac te /*Does TE have a / ? Then find term #*/ exit 0 /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? th: parse arg th; return word('th st nd rd', 1+(th//10) *(th//100%10\==1) *(th//10<4)) /*──────────────────────────────────────────────────────────────────────────────────────*/ CW_frac: procedure; parse arg p '/' q .; say if q=='' then do; p= 83116; q= 51639; end n= rle2dec( frac2cf(p q) ); @CWS= 'the Calkin─Wilf sequence' say 'for ' p"/"q', the element number for' @CWS "is: " commas(n)th(n) if length(n)<10 then return say; say 'The above number has ' commas(length(n)) " decimal digits." return /*──────────────────────────────────────────────────────────────────────────────────────*/ CW_term: procedure; parse arg z; dd= 1; nn= 0 do z parse value dd dd*(2*(nn%dd)+1)-nn with nn dd end /*z*/ return nn'/'dd /*──────────────────────────────────────────────────────────────────────────────────────*/ CW_terms: $=; if LO\==0 then do j=LO to HI; $= $ CW_term(j)',' end /*j*/ if $=='' then return say 'Calkin─Wilf sequence terms for ' commas(LO) " ──► " commas(HI) ' are:' say strip( strip($), 'T', ",") return /*──────────────────────────────────────────────────────────────────────────────────────*/ frac2cf: procedure; parse arg p q; if q=='' then return p; cf= p % q; m= q p= p - cf*q; n= p; if p==0 then return cf do k=1 until n==0; @.k= m % n m= m - @.k * n; parse value n m with m n /*swap N M*/ end /*k*/ /*for inverse Calkin─Wilf, K must be even.*/ if k//2 then do; @.k= @.k - 1; k= k + 1; @.k= 1; end do k=1 for k; cf= cf @.k; end /*k*/ return cf /*──────────────────────────────────────────────────────────────────────────────────────*/ rle2dec: procedure; parse arg f1 rle; obin= copies(1, f1) do until rle==''; parse var rle f0 f1 rle obin= copies(1, f1)copies(0, f0)obin end /*until*/ return x2d( b2x(obin) ) /*RLE2DEC: Run Length Encoding ──► decimal*/
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)). note that 318682 {\displaystyle 318682} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ); note that 101558217124 {\displaystyle 101558217124} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); note that this implies that for Kaprekar numbers the checksum of k {\displaystyle k} equals the checksum of k 2 {\displaystyle k^{2}} . Demonstrate that your procedure can be used to generate or filter a range of numbers with the property c o 9 ( k ) = c o 9 ( k 2 ) {\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} is the residual of x {\displaystyle x} mod 9 {\displaystyle 9} ; the procedure can be extended to bases other than 9. Demonstrate your algorithm by generating or filtering a range of numbers with the property k % ( B a s e − 1 ) == ( k 2 ) % ( B a s e − 1 ) {\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. related tasks First perfect square in base N with N unique digits Kaprekar numbers
#Rust
Rust
fn compare_co9_efficiency(base: u64, upto: u64) { let naive_candidates: Vec<u64> = (1u64..upto).collect(); let co9_candidates: Vec<u64> = naive_candidates.iter().cloned() .filter(|&x| x % (base - 1) == (x * x) % (base - 1)) .collect(); for candidate in &co9_candidates { print!("{} ", candidate); } println!(); println!( "Trying {} numbers instead of {} saves {:.2}%", co9_candidates.len(), naive_candidates.len(), 100.0 - 100.0 * (co9_candidates.len() as f64 / naive_candidates.len() as f64) ); }   fn main() { compare_co9_efficiency(10, 100); compare_co9_efficiency(16, 256); }
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)). note that 318682 {\displaystyle 318682} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ); note that 101558217124 {\displaystyle 101558217124} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); note that this implies that for Kaprekar numbers the checksum of k {\displaystyle k} equals the checksum of k 2 {\displaystyle k^{2}} . Demonstrate that your procedure can be used to generate or filter a range of numbers with the property c o 9 ( k ) = c o 9 ( k 2 ) {\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} is the residual of x {\displaystyle x} mod 9 {\displaystyle 9} ; the procedure can be extended to bases other than 9. Demonstrate your algorithm by generating or filtering a range of numbers with the property k % ( B a s e − 1 ) == ( k 2 ) % ( B a s e − 1 ) {\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. related tasks First perfect square in base N with N unique digits Kaprekar numbers
#Scala
Scala
  object kaprekar{ // PART 1 val co_base = ((x:Int,base:Int) => (x%(base-1) == (x*x)%(base-1))) //PART 2 def get_cands(n:Int,base:Int):List[Int] = { if(n==1) List[Int]() else if (co_base(n,base)) n :: get_cands(n-1,base) else get_cands(n-1,base) } def main(args:Array[String]) : Unit = { //PART 3 val base = 31 println("Candidates for Kaprekar numbers found by casting out method with base %d:".format(base)) println(get_cands(1000,base)) } }  
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a method based on   Carmichael numbers,   as suggested in   Notes by G.J.O Jameson March 2010. Task Find Carmichael numbers of the form: Prime1 × Prime2 × Prime3 where   (Prime1 < Prime2 < Prime3)   for all   Prime1   up to   61. (See page 7 of   Notes by G.J.O Jameson March 2010   for solutions.) Pseudocode For a given   P r i m e 1 {\displaystyle Prime_{1}} for 1 < h3 < Prime1 for 0 < d < h3+Prime1 if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3 then Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d) next d if Prime2 is not prime Prime3 = 1 + (Prime1*Prime2/h3) next d if Prime3 is not prime next d if (Prime2*Prime3) mod (Prime1-1) not equal 1 Prime1 * Prime2 * Prime3 is a Carmichael Number related task Chernick's Carmichael numbers
#REXX
REXX
/*REXX program calculates Carmichael 3─strong pseudoprimes (up to and including N). */ numeric digits 18 /*handle big dig #s (9 is the default).*/ parse arg N .; if N=='' | N=="," then N=61 /*allow user to specify for the search.*/ tell= N>0; N= abs(N) /*N>0? Then display Carmichael numbers*/ #= 0 /*number of Carmichael numbers so far. */ @.=0; @.2=1; @.3=1; @.5=1; @.7=1; @.11=1; @.13=1; @.17=1; @.19=1; @.23=1; @.29=1; @.31=1 /*[↑] prime number memoization array. */ do p=3 to N by 2; pm= p-1; bot=0; top=0 /*step through some (odd) prime numbers*/ if \isPrime(p) then iterate; nps= -p*p /*is P a prime? No, then skip it.*/ c.= 0 /*the list of Carmichael #'s (so far).*/ do h3=2 for pm-1; g= h3 + p /*get Carmichael numbers for this prime*/ npsH3= ((nps // h3) + h3) // h3 /*define a couple of shortcuts for pgm.*/ gPM= g * pm /*define a couple of shortcuts for pgm.*/ /* [↓] perform some weeding of D values*/ do d=1 for g-1; if gPM // d \== 0 then iterate if npsH3 \== d//h3 then iterate q= 1 + gPM  % d; if \isPrime(q) then iterate r= 1 + p * q % h3; if q * r // pm \== 1 then iterate if \isPrime(r) then iterate #= # + 1; c.q= r /*bump Carmichael counter; add to array*/ if bot==0 then bot= q; bot= min(bot, q); top= max(top, q) end /*d*/ end /*h3*/ $= /*build list of some Carmichael numbers*/ if tell then do j=bot to top by 2; if c.j\==0 then $= $ p"∙"j'∙'c.j end /*j*/   if $\=='' then say 'Carmichael number: ' strip($) end /*p*/ say say '──────── ' # " Carmichael numbers found." exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ isPrime: parse arg x; if @.x then return 1 /*is X a known prime?*/ if x<37 then return 0; if x//2==0 then return 0; if x// 3==0 then return 0 parse var x '' -1 _; if _==5 then return 0; if x// 7==0 then return 0 if x//11==0 then return 0; if x//13==0 then return 0; if x//17==0 then return 0 if x//19==0 then return 0; if x//23==0 then return 0; if x//29==0 then return 0 do k=29 by 6 until k*k>x; if x//k ==0 then return 0 if x//(k+2) ==0 then return 0 end /*k*/ @.x=1; return 1
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article:   Fold Wikipedia article:   Catamorphism
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Function Reduce (a, f) { if len(a)=0 then Error "Nothing to reduce" if len(a)=1 then =Array(a) : Exit k=each(a, 2, -1) m=Array(a) While k { m=f(m, array(k)) } =m } a=(1, 2, 3, 4, 5) Print "Array", a Print "Sum", Reduce(a, lambda (x,y)->x+y) Print "Difference", Reduce(a, lambda (x,y)->x-y) Print "Product", Reduce(a, lambda (x,y)->x*y) Print "Minimum", Reduce(a, lambda (x,y)->if(x<y->x, y)) Print "Maximum", Reduce(a, lambda (x,y)->if(x>y->x, y)) } CheckIt  
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:   Fold Wikipedia article:   Catamorphism
#Maple
Maple
> nums := seq( 1 .. 10 ); nums := 1, 2, 3, 4, 5, 6, 7, 8, 9, 10   > foldl( `+`, 0, nums ); # compute sum using foldl 55   > foldr( `*`, 1, nums ); # compute product using foldr 3628800
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#Zig
Zig
  const std = @import("std"); const stdout = std.io.getStdOut().outStream();   pub fn main() !void { var n: u32 = 1; while (n <= 15) : (n += 1) { const row = binomial(n * 2).?; try stdout.print("{d:2} {d:8}\n", .{ n, row[n] - row[n + 1] }); } }   pub fn binomial(n: u32) ?[]const u64 { if (n >= rmax) return null else { const k = n * (n + 1) / 2; return pascal[k .. k + n + 1]; } }   const rmax = 68;   const pascal = build: { @setEvalBranchQuota(100_000); var coefficients: [(rmax * (rmax + 1)) / 2]u64 = undefined; coefficients[0] = 1; var j: u32 = 0; var k: u32 = 1; var n: u32 = 1; while (n < rmax) : (n += 1) { var prev = coefficients[j .. j + n]; var next = coefficients[k .. k + n + 1]; next[0] = 1; var i: u32 = 1; while (i < n) : (i += 1) next[i] = prev[i] + prev[i - 1]; next[i] = 1; j = k; k += n + 1; } break :build coefficients; };  
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#zkl
zkl
fcn binomial(n,k){ (1).reduce(k,fcn(p,i,n){ p*(n-i+1)/i },1,n) } (1).pump(15,List,fcn(n){ binomial(2*n,n)-binomial(2*n,n+1) })
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Rust
Rust
fn main() { let dog = "Benjamin"; let Dog = "Samba"; let DOG = "Bernie"; println!("The three dogs are named {}, {} and {}.", dog, Dog, DOG); }
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Sather
Sather
class MAIN is main is dog ::= "Benjamin"; Dog ::= "Samba"; DOG ::= "Bernie"; #OUT + #FMT("The three dogs are %s, %s and %s\n", dog, Dog, DOG); end; end;
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Scala
Scala
val dog = "Benjamin" val Dog = "Samba" val DOG = "Bernie" println("There are three dogs named " + dog + ", " + Dog + ", and " + DOG + ".")
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 your function/method, that the product of an empty list with any other list is empty. {1, 2} × {} = {} {} × {1, 2} = {} For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists. Use your n-ary Cartesian product function to show the following products: {1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1} {1, 2, 3} × {30} × {500, 100} {1, 2, 3} × {} × {500, 100}
#Perl
Perl
sub cartesian { my $sets = shift @_; for (@$sets) { return [] unless @$_ }   my $products = [[]]; for my $set (reverse @$sets) { my $partial = $products; $products = []; for my $item (@$set) { for my $product (@$partial) { push @$products, [$item, @$product]; } } } $products; }   sub product { my($s,$fmt) = @_; my $tuples; for $a ( @{ cartesian( \@$s ) } ) { $tuples .= sprintf "($fmt) ", @$a; } $tuples . "\n"; }   print product([[1, 2], [3, 4] ], '%1d %1d' ). product([[3, 4], [1, 2] ], '%1d %1d' ). product([[1, 2], [] ], '%1d %1d' ). product([[], [1, 2] ], '%1d %1d' ). product([[1,2,3], [30], [500,100] ], '%1d %1d %3d' ). product([[1,2,3], [], [500,100] ], '%1d %1d %3d' ). product([[1776,1789], [7,12], [4,14,23], [0,1]], '%4d %2d %2d %1d')
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#Erlang
Erlang
-module(catalan).   -export([test/0]).   cat(N) -> factorial(2 * N) div (factorial(N+1) * factorial(N)).   factorial(N) -> fac1(N,1).   fac1(0,Acc) -> Acc; fac1(N,Acc) -> fac1(N-1, N * Acc).   cat_r1(0) -> 1; cat_r1(N) -> lists:sum([cat_r1(I)*cat_r1(N-1-I) || I <- lists:seq(0,N-1)]).   cat_r2(0) -> 1; cat_r2(N) -> cat_r2(N - 1) * (2 * ((2 * N) - 1)) div (N + 1).   test() -> TestList = lists:seq(0,14), io:format("Directly:\n~p\n",[[cat(N) || N <- TestList]]), io:format("1st recusive method:\n~p\n",[[cat_r1(N) || N <- TestList]]), io:format("2nd recusive method:\n~p\n",[[cat_r2(N) || N <- TestList]]).