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/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
| #TypeScript | TypeScript |
// Catalan numbers
var c: number[] = [1];
console.log(`${0}\t${c[0]}`);
for (n = 0; n < 15; n++) {
c[n + 1] = 0;
for (i = 0; i <= n; i++)
c[n + 1] = c[n + 1] + c[i] * c[n - i];
console.log(`${n + 1}\t${c[n + 1]}`);
}
|
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task 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."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #uBasic.2F4tH | uBasic/4tH | Print " XXXX"
Print " X XX"
Print " X *** X XXXXX"
Print " X ***** X XXX XX"
Print " XXXX ******* XXX XXXX XX"
Print " XX X ****** XXXXXXXXX XX XXX"
Print " XX X **** X X** X"
Print " X XX XX X X***X"
Print " X //XXXX X XXXX"
Print " X // X XX"
Print " X // X XXXXXXXXXXXXXXXXXX/"
Print " X XXX// X X"
Print " X X X X X"
Print " X X X X X"
Print " X X X X X XX"
Print " X X X X X XXX XX"
Print " X XXX X X X X X X"
Print " X X X XX X XXXX"
Print " X X XXXXXXXX\\ XX XX X"
Print " XX XX X X X XX"
Print " XX XXXX XXXXXX/ X XXXX"
Print " XXX XX*** X X"
Print " XXXXXXXXXXXXX * * X X"
Print " *---* X X X"
Print " *-* * XXX X X"
Print " *- * XXX X"
Print " *- *X XXX"
Print " *- *X X XXX"
Print " *- *X X XX"
Print " *- *XX X X"
Print " * *X* X X X"
Print " * *X * X X X"
Print " * * X** X XXXX X"
Print " * * X** XX X X"
Print " * ** X** X XX X"
Print " * ** X* XXX X X"
Print " * ** XX XXXX XXX"
Print " * * * XXXX X X"
Print " * * * X X X"
Print " =======******* * * X X XXXXXXXX\\"
Print " * * * /XXXXX XXXXXXXX\\ )"
Print " =====********** * X ) \\ )"
Print " ====* * X \\ \\ )XXXXX"
Print " =========********** XXXXXXXXXXXXXXXXXXXXXX" |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Phix | Phix | --
-- demo\rosetta\BullsAndCows.exw
-- =============================
--
with javascript_semantics -- (DEV lots of resizing issues)
constant N = 4
function mask(integer ch)
return power(2,ch-'1')
end function
function score(string guess, goal)
integer bits = 0, bulls = 0, cows = 0, b
for i=1 to N do
b = goal[i]
if guess[i]=b then
bulls += 1
else
bits += mask(b)
end if
end for
for i=1 to N do
b = mask(guess[i])
if and_bits(bits,b)!=0 then
cows += 1
bits -= b
end if
end for
return {bulls, cows}
end function
include pGUI.e
Ihandle label, guess, res, dlg
string fmt = " Guess %-2d (%s) bulls:%d cows:%d\n",
tgt = shuffle("123456789")[1..N]
integer attempt = 1
function valuechanged_cb(Ihandle /*guess*/)
string g = IupGetAttribute(guess,"VALUE")
if length(g)=4 and length(unique(g))=4 then
integer {bulls, cows} = score(g,tgt)
string title = IupGetAttribute(res,"TITLE") &
sprintf(fmt,{attempt,g,bulls,cows})
if bulls=N then
title &= "\nWell done!"
IupSetInt(guess,"ACTIVE",false)
else
IupSetAttribute(guess,"VALUE","")
end if
IupSetStrAttribute(res,"TITLE",title)
attempt += 1
IupSetAttribute(dlg,"SIZE",NULL)
IupRefresh(dlg)
end if
return IUP_DEFAULT
end function
procedure main()
IupOpen()
label = IupLabel(sprintf("Enter %d digits 1 to 9 without duplication",{N}))
guess = IupText("VALUECHANGED_CB", Icallback("valuechanged_cb"))
res = IupLabel("")
dlg = IupDialog(IupVbox({IupHbox({label,guess},"GAP=10,NORMALIZESIZE=VERTICAL"),
IupHbox({res})},"MARGIN=5x5"),`TITLE="Bulls and Cows"`)
IupShow(dlg)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
end procedure
main()
|
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
| #Liberty_BASIC | Liberty BASIC | key = 7
Print "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
'Encrypt the text
Print CaesarCypher$("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", key)
'Decrypt the text by changing the key to (26 - key)
Print CaesarCypher$(CaesarCypher$("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", key), (26 - key))
Function CaesarCypher$(string$, key)
If (key < 0) Or (key > 25) Then _
CaesarCypher$ = "Key is Ouside of Bounds" : Exit Function
For i = 1 To Len(string$)
rotate = Asc(Mid$(string$, i, 1))
rotate = (rotate + key)
If Asc(Mid$(string$, i, 1)) > Asc("Z") Then
If rotate > Asc("z") Then rotate = (Asc("a") + (rotate - Asc("z")) - 1)
Else
If rotate > Asc("Z") Then rotate = (Asc("A") + (rotate - Asc("Z")) - 1)
End If
CaesarCypher$ = (CaesarCypher$ + Chr$(rotate))
Next i
End Function |
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.
| #Swift | Swift | // call a function with no args
noArgs()
// call a function with one arg with no external name
oneArgUnnamed(1)
// call a function with one arg with external name
oneArgNamed(arg: 1)
// call a function with two args with no external names
twoArgsUnnamed(1, 2)
// call a function with two args and external names
twoArgsNamed(arg1: 1, arg2: 2)
// call a function with an optional arg
// with arg
optionalArguments(arg: 1)
// without
optionalArguments() // defaults to 0
// function that takes another function as arg
funcArg(noArgs)
// variadic function
variadic(opts: "foo", "bar")
// getting a return value
let foo = returnString()
// getting a bunch of return values
let (foo, bar, baz) = returnSomeValues()
// getting a bunch of return values, discarding second returned value
let (foo, _, baz) = returnSomeValues() |
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.
| #Tcl | Tcl | aCallToACommandWithNoArguments
aCallToACommandWithOne argument
aCallToACommandWith arbitrarily many arguments
aCallToACommandWith {*}$manyArgumentsComingFromAListInAVariable
aCallToACommandWith -oneNamed argument -andAnother namedArgument
aCallToACommandWith theNameOfAnotherCommand
aCallToOneCommand [withTheResultOfAnother] |
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
| #Ursala | Ursala | #import std
#import nat
catalan = quotient^\successor choose^/double ~&
#cast %nL
t = catalan* iota 16 |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task 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."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #UNIX_Shell | UNIX Shell |
#!/bin/sh
echo "Snoopy goes here"
cal 1969
|
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #PHP | PHP | <?php
$size = 4;
$chosen = implode(array_rand(array_flip(range(1,9)), $size));
echo "I've chosen a number from $size unique digits from 1 to 9; you need
to input $size unique digits to guess my number\n";
for ($guesses = 1; ; $guesses++) {
while (true) {
echo "\nNext guess [$guesses]: ";
$guess = rtrim(fgets(STDIN));
if (!checkguess($guess))
echo "$size digits, no repetition, no 0... retry\n";
else
break;
}
if ($guess == $chosen) {
echo "You did it in $guesses attempts!\n";
break;
} else {
$bulls = 0;
$cows = 0;
foreach (range(0, $size-1) as $i) {
if ($guess[$i] == $chosen[$i])
$bulls++;
else if (strpos($chosen, $guess[$i]) !== FALSE)
$cows++;
}
echo "$cows cows, $bulls bulls\n";
}
}
function checkguess($g)
{
global $size;
return count(array_unique(str_split($g))) == $size &&
preg_match("/^[1-9]{{$size}}$/", $g);
}
?> |
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
| #LiveCode | LiveCode | function caesarCipher rot phrase
local rotPhrase, lowerLetters, upperLetters
put "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" into lowerLetters
put "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" into upperLetters
repeat for each char letter in phrase
get charTonum(letter)
if it >= 65 and it <= 90 then
put char ((it + rot) - 64) of upperLetters after rotPhrase
else if it >= 97 and it <= 122 then
put char ((it + rot) - 96) of lowerLetters after rotPhrase
else
put letter after rotPhrase
end if
end repeat
return rotPhrase
end caesarCipher |
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.
| #True_BASIC | True BASIC | FUNCTION Copialo$ (txt$, siNo, final$)
FOR cont = 1 TO ROUND(siNo)
LET nuevaCadena$ = nuevaCadena$ & txt$
NEXT cont
LET Copialo$ = LTRIM$(RTRIM$(nuevaCadena$)) & final$
END FUNCTION
SUB Saludo
PRINT "Hola mundo!"
END SUB
SUB testCadenas (txt$)
FOR cont = 1 TO ROUND(LEN(txt$))
PRINT (txt$)[cont:cont+1-1]; "";
NEXT cont
END SUB
SUB testNumeros (a, b, c)
PRINT a, b, c
END SUB
CALL Saludo
PRINT Copialo$("Saludos ", 6, "")
PRINT Copialo$("Saludos ", 3, "! !")
PRINT
CALL testNumeros(1, 2, 3)
CALL testNumeros(1, 2, 0)
PRINT
CALL testCadenas("1, 2, 3, 4, cadena, 6, 7, 8, \'incluye texto\'")
END |
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
| #Vala | Vala | namespace CatalanNumbers {
public class CatalanNumberGenerator {
private static double factorial(double n) {
if (n == 0)
return 1;
return n * factorial(n - 1);
}
public double first_method(double n) {
const double top_multiplier = 2;
return factorial(top_multiplier * n) / (factorial(n + 1) * factorial(n));
}
public double second_method(double n) {
if (n == 0) {
return 1;
}
double sum = 0;
double i = 0;
for (; i <= (n - 1); i++) {
sum += second_method(i) * second_method((n - 1) - i);
}
return sum;
}
public double third_method(double n) {
if (n == 0) {
return 1;
}
return ((2 * (2 * n - 1)) / (n + 1)) * third_method(n - 1);
}
}
void main() {
CatalanNumberGenerator generator = new CatalanNumberGenerator();
DateTime initial_time;
DateTime final_time;
TimeSpan ts;
stdout.printf("Direct Method\n");
stdout.printf(" n%9s\n", "C_n");
stdout.printf("............\n");
initial_time = new DateTime.now();
for (double i = 0; i <= 15; i++) {
stdout.printf("%2s %8s\n", i.to_string(), Math.ceil(generator.first_method(i)).to_string());
}
final_time = new DateTime.now();
ts = final_time.difference(initial_time);
stdout.printf("............\n");
stdout.printf("Time Elapsed: %s μs\n", ts.to_string());
stdout.printf("\nRecursive Method 1\n");
stdout.printf(" n%9s\n", "C_n");
stdout.printf("............\n");
initial_time = new DateTime.now();
for (double i = 0; i <= 15; i++) {
stdout.printf("%2s %8s\n", i.to_string(), Math.ceil(generator.second_method(i)).to_string());
}
final_time = new DateTime.now();
ts = final_time.difference(initial_time);
stdout.printf("............\n");
stdout.printf("Time Elapsed: %s μs\n", ts.to_string());
stdout.printf("\nRecursive Method 2\n");
stdout.printf(" n%9s\n", "C_n");
stdout.printf("............\n");
initial_time = new DateTime.now();
for (double i = 0; i <= 15; i++) {
stdout.printf("%2s %8s\n", i.to_string(), Math.ceil(generator.third_method(i)).to_string());
}
final_time = new DateTime.now();
ts = final_time.difference(initial_time);
stdout.printf("............\n");
stdout.printf("Time Elapsed: %s μs\n", ts.to_string());
}
} |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task 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."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Vedit_macro_language | Vedit macro language | Buf_Switch(Buf_Free)
Config_Tab(5,30,55)
#9 = 1 // first day of week: 0=Su, 1=Mo
#3 = 3 // number of months per line
#2 = 1969 // year
#1 = 1 // starting month
Repeat(12/#3) {
Repeat (#3) {
Buf_Switch(Buf_Free)
Call_File(122, "calendar.vdm", "DRAW_CALENDAR")
Reg_Copy_Block(10, 1, EOB_Pos, COLSET, 1, 21)
Buf_Quit(OK)
EOL Ins_Char(9)
#5 = Cur_Pos
Reg_Ins(10)
Goto_Pos(#5)
#1++
}
EOF
Ins_Newline(2)
} |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Picat | Picat | main =>
Digits = to_array("123456789"),
Size = 4,
random_sample(Size,Size,[],ChosenIndecies),
Chosen = {Digits[I] : I in ChosenIndecies},
printf("I have chosen a number from %d unique digits from 1 to 9 arranged in a random order.\n", Size),
printf("You need to input a %d digit, unique digit number as a guess at what I have chosen.\n", Size),
guess(Chosen,Size,1).
guess(Chosen,Size,NGuess) =>
Input = read_line(),
Guess = Input.to_array(),
if len(Guess) != Size || len(sort_remove_dups(Input)) != Size || (member(D, Input), (D @< '1' || D @> '9')) then
printf("Problem, try again. You need to enter %d unique digits from 1 to 9\n", Size),
guess(Chosen,Size,NGuess)
elseif Guess == Chosen then
printf("\nCongratulations you guessed correctly in %d attempts\n", NGuess)
else
Bulls = sum([cond(Chosen[I] == Guess[I], 1, 0) : I in 1..Size]),
Cows = sum([cond(member(Chosen[I], Input), 1, 0) : I in 1..Size]),
printf("%d Bulls\n%d Cows\n", Bulls, Cows),
guess(Chosen, Size, NGuess+1)
end.
random_sample(_N,0,Chosen0,Chosen) => Chosen = Chosen0.
random_sample(N,I,Chosen0,Chosen) =>
R = random() mod N + 1,
(not member(R, Chosen0) ->
random_sample(N,I-1,[R|Chosen0],Chosen)
;
random_sample(N,I,Chosen0,Chosen)
).
|
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
| #Logo | Logo | ; some useful constants
make "lower_a ascii "a
make "lower_z ascii "z
make "upper_a ascii "A
make "upper_z ascii "Z
; encipher a single character
to encipher_char :char :key
local "code make "code ascii :char
local "base make "base 0
ifelse [and (:code >= :lower_a) (:code <= :lower_z)] [make "base :lower_a] [
if [and (:code >= :upper_a) (:code <= :upper_z)] [make "base :upper_a] ]
ifelse [:base > 0] [
output char (:base + (modulo ( :code - :base + :key ) 26 ))
] [
output :char
]
end
; encipher a whole string
to caesar_cipher :string :key
output map [encipher_char ? :key] :string
end
; Demo
make "plaintext "|The five boxing wizards jump quickly|
make "key 3
make "ciphertext caesar_cipher :plaintext :key
make "recovered caesar_cipher :ciphertext -:key
print sentence "| Original:| :plaintext
print sentence "|Encrypted:| :ciphertext
print sentence "|Recovered:| :recovered
bye |
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.
| #UNIX_Shell | UNIX Shell | sayhello # Call a function in statement context with no arguments
multiply 3 4 # Call a function in statement context with two arguments |
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.
| #VBA | VBA | 'definitions/declarations
'Calling a function that requires no arguments
Function no_arguments() As String
no_arguments = "ok"
End Function
'Calling a function with a fixed number of arguments
Function fixed_number(argument1 As Integer, argument2 As Integer)
fixed_number = argument1 + argument2
End Function
'Calling a function with optional arguments
Function optional_parameter(Optional argument1 = 1) As Integer
'Optional parameters come at the end of the parameter list
optional_parameter = argument1
End Function
'Calling a function with a variable number of arguments
Function variable_number(arguments As Variant) As Integer
variable_number = UBound(arguments)
End Function
'Calling a function with named arguments
Function named_arguments(argument1 As Integer, argument2 As Integer) As Integer
named_arguments = argument1 + argument2
End Function
'Using a function in statement context
Function statement() As String
Debug.Print "function called as statement"
statement = "ok"
End Function
'Using a function in first-class context within an expression
'see call the functions
'Obtaining the return value of a function
Function return_value() As String
return_value = "ok"
End Function
'Distinguishing built-in functions and user-defined functions
'There is no way to distinguish built-in function and user-defined functions
'Distinguishing subroutines And functions
'subroutines are declared with the reserved word "sub" and have no return value
Sub foo()
Debug.Print "subroutine",
End Sub
'functions are declared with the reserved word "function" and can have a return value
Function bar() As String
bar = "function"
End Function
'Stating whether arguments are passed by value or by reference
Function passed_by_value(ByVal s As String) As String
s = "written over"
passed_by_value = "passed by value"
End Function
'By default, parameters in VBA are by reference
Function passed_by_reference(ByRef s As String) As String
s = "written over"
passed_by_reference = "passed by reference"
End Function
'Is partial application possible and how
'I don't know
'calling a subroutine with arguments does not require parentheses
Sub no_parentheses(myargument As String)
Debug.Print myargument,
End Sub
'call the functions
Public Sub calling_a_function()
'Calling a function that requires no arguments
Debug.Print "no arguments", , no_arguments
Debug.Print "no arguments", , no_arguments()
'Parentheses are not required
'Calling a function with a fixed number of arguments
Debug.Print "fixed_number", , fixed_number(1, 1)
'Calling a function with optional arguments
Debug.Print "optional parameter", optional_parameter
Debug.Print "optional parameter", optional_parameter(2)
'Calling a function with a variable number of arguments
Debug.Print "variable number", variable_number([{"hello", "there"}])
'The variable number of arguments have to be passed as an array
'Calling a function with named arguments
Debug.Print "named arguments", named_arguments(argument2:=1, argument1:=1)
'Using a function in statement context
statement
'Using a function in first-class context within an expression
s = "no_arguments"
Debug.Print "first-class context", Application.Run(s)
'A function name can be passed as argument in a string
'Obtaining the return value of a function
returnvalue = return_value
Debug.Print "obtained return value", returnvalue
'Distinguishing built-in functions and user-defined functions
'Distinguishing subroutines And functions
foo
Debug.Print , bar
'Stating whether arguments are passed by value or by reference
Dim t As String
t = "unaltered"
Debug.Print passed_by_value(t), t
Debug.Print passed_by_reference(t), t
'Is partial application possible and how
'I don 't know
'calling a subroutine with arguments does not require parentheses
no_parentheses "calling a subroutine"
Debug.Print "does not require parentheses"
Call no_parentheses("deprecated use")
Debug.Print "of parentheses"
End Sub
|
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
| #VBA | VBA | Public Sub Catalan1(n As Integer)
'Computes the first n Catalan numbers according to the first recursion given
Dim Cat() As Long
Dim sum As Long
ReDim Cat(n)
Cat(0) = 1
For i = 0 To n - 1
sum = 0
For j = 0 To i
sum = sum + Cat(j) * Cat(i - j)
Next j
Cat(i + 1) = sum
Next i
Debug.Print
For i = 0 To n
Debug.Print i, Cat(i)
Next
End Sub
Public Sub Catalan2(n As Integer)
'Computes the first n Catalan numbers according to the second recursion given
Dim Cat() As Long
ReDim Cat(n)
Cat(0) = 1
For i = 1 To n
Cat(i) = 2 * Cat(i - 1) * (2 * i - 1) / (i + 1)
Next i
Debug.Print
For i = 0 To n
Debug.Print i, Cat(i)
Next
End Sub |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task 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."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Visual_Basic_.NET | Visual Basic .NET | Option Compare Binary
Option Explicit On
Option Infer On
Option Strict On
Imports System.Globalization
Imports System.Text
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #PicoLisp | PicoLisp | (de ok? (N)
(let D (mapcar 'format (chop N))
(and (num? N)
(not (member 0 D))
(= 4 (length D))
(= D (uniq D))
D )) )
(de init-cows ()
(until (setq *Hidden (ok? (rand 1234 9876)))) )
(de guess (N)
(let D (ok? N)
(if D
(let Bulls (cnt '= D *Hidden)
(if (= 4 Bulls)
" You guessed it!"
(let Cows (- (cnt '((N) (member N *Hidden)) D) Bulls)
(pack Bulls " bulls, " Cows " cows") ) ) )
" Bad guess! (4 unique digits, 1-9)" ) ) )
|
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
| #Lua | Lua | local function encrypt(text, key)
return text:gsub("%a", function(t)
local base = (t:lower() == t and string.byte('a') or string.byte('A'))
local r = t:byte() - base
r = r + key
r = r%26 -- works correctly even if r is negative
r = r + base
return string.char(r)
end)
end
local function decrypt(text, key)
return encrypt(text, -key)
end
caesar = {
encrypt = encrypt,
decrypt = decrypt,
}
-- test
do
local text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"
local encrypted = caesar.encrypt(text, 7)
local decrypted = caesar.decrypt(encrypted, 7)
print("Original text: ", text)
print("Encrypted text: ", encrypted)
print("Decrypted text: ", decrypted)
end
|
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
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.
| #WDTE | WDTE | let noargs => + 2 5;
noargs -- print;
let fixedargs a b => + a b;
fixedargs 3 5 -- print;
let m => import 'math';
m.cos 3 -- print;
# WDTE only has expressions, not statements, so statement vs.
# first-class context doesn't make sense.
# Arguments in WDTE are technically passed by reference, in a way, but
# because it's a functional language and everything's immutable
# there's no real usability difference from that.
# Partial application is possible. For example, the following
# evaluates `+ 3` and then passes 7 to the resulting partially applied
# function.
(+ 3) 7 -- print; |
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.
| #WebAssembly | WebAssembly | (func $main (export "_start")
(local $result i32)
;;Call a function with no arguments
call $noargfunc
;;Multiply two numbers and store the result, flat syntax
i32.const 12
i32.const 3
call $multipy
set_local $result
;;Multiply two numbers and store the result, indented syntax
(set_local $result
(call $multipy
(i32.const 12)
(i32.const 3)
)
)
;;Add two numbers in linear memory (similar to using pointers)
(i32.store (i32.const 0) (i32.const 5))
(i32.store (i32.const 4) (i32.const 7))
(call $addinmemory
(i32.const 0)
(i32.const 4)
(i32.const 8)
)
) |
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
| #VBScript | VBScript |
Function catalan(n)
catalan = factorial(2*n)/(factorial(n+1)*factorial(n))
End Function
Function factorial(n)
If n = 0 Then
Factorial = 1
Else
For i = n To 1 Step -1
If i = n Then
factorial = n
Else
factorial = factorial * i
End If
Next
End If
End Function
'Find the first 15 Catalan numbers.
For j = 1 To 15
WScript.StdOut.Write j & " = " & catalan(j)
WScript.StdOut.WriteLine
Next
|
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task 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."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #VBScript | VBScript |
'call it with year, number of months per row (1,2,3,4,6) and locale ("" for default)
docal 1969,6,""
function center (s,n) x=n-len(s):center=space(x\2+(x and 1))& s & space(x\2):end function
sub print(x) wscript.stdout.writeline x : end sub
function iif(a,b,c) :if a then iif=b else iif =c end if : end function
sub docal (yr,nmonth,sloc)
dim ld(6)
dim d(6)
if nmonth=5 or nmonth>6 then wscript.stderr.writeline "Can't use width " & nmonth :exit sub
if sloc<>"" then Setlocale sloc
for i=1 to 7
wday=wday &" "&left(weekdayname(i,true,vbUseSystemDayOfWeek),2)
next
ncols=nmonth*21+(nmonth-1)*1
print center("[Snoopy]",ncols)
print center(yr,ncols)
print string(ncols,"=")
for i=1 to 12\nmonth
s="": s1="":esp=""
for j=1 to nmonth
s=s & esp & center(monthname(m+j),21)
s1=s1 & esp & wday
d(j)= -weekday(dateserial(yr,m+j,1),vbUseSystemDayOfWeek)+2
ld(j)=day(dateserial(yr,m+j+1,0))
esp=" "
next
print s: print s1
while(d(1)<ld(1)) or (d(2)<ld(2)) or (d(3)<ld(3)) or (d(4)<ld(4))
s=""
for j=1 to nmonth
for k=1 to 7
s=s& right(space(3)&iif(d(j)<1 or d(j)>ld(j),"",d(j)),3)
d(j)=d(j)+1
next
s=s&" "
next
print s
wend
m=m+nmonth
if i<>12\nmonth then print ""
next
print string(ncols,"=")
end sub
|
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #PowerShell | PowerShell |
[int]$guesses = $bulls = $cows = 0
[string]$guess = "none"
[string]$digits = ""
while ($digits.Length -lt 4)
{
$character = [char](49..57 | Get-Random)
if ($digits.IndexOf($character) -eq -1) {$digits += $character}
}
Write-Host "`nGuess four digits (1-9) using no digit twice.`n" -ForegroundColor Cyan
while ($bulls -lt 4)
{
do
{
$prompt = "Guesses={0:0#}, Last='{1,4}', Bulls={2}, Cows={3}; Enter your guess" -f $guesses, $guess, $bulls, $cows
$guess = Read-Host $prompt
if ($guess.Length -ne 4) {Write-Host "`nMust be a four-digit number`n" -ForegroundColor Red}
if ($guess -notmatch "[1-9][1-9][1-9][1-9]") {Write-Host "`nMust be numbers 1-9`n" -ForegroundColor Red}
}
until ($guess.Length -eq 4)
$guesses += 1
$bulls = $cows = 0
for ($i = 0; $i -lt 4; $i++)
{
$character = $digits.Substring($i,1)
if ($guess.Substring($i,1) -eq $character)
{
$bulls += 1
}
else
{
if ($guess.IndexOf($character) -ge 0)
{
$cows += 1
}
}
}
}
Write-Host "`nYou won after $($guesses - 1) guesses." -ForegroundColor Cyan
|
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
| #M2000_Interpreter | M2000 Interpreter |
a$="THIS IS MY TEXT TO ENCODE WITH CAESAR CIPHER"
Function Cipher$(a$, N) {
If Len(a$)=0 Then Exit
a$=Ucase$(a$)
N=N mod 25 +1
\\ Integer in Mem is unsigned number
Buffer Mem as Integer*Len(a$)
Return Mem, 0:=a$
For i=0 to Len(a$)-1 {
If Eval(mem, i)>=65 and Eval(mem, i)<=90 then Return Mem, i:=(Eval(mem, i)-65+N) mod 26+65
}
=Eval$(Mem)
}
B$=Cipher$(a$, 12)
Print B$
Print Cipher$(B$,12)
|
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.
| #Wren | Wren | var f1 = Fn.new { System.print("Function 'f1' with no arguments called.") }
var f2 = Fn.new { |a, b|
System.print("Function 'f2' with 2 arguments called and passed %(a) & %(b).")
}
var f3 = Fn.new { 42 } // function which returns a concrete value
f1.call() // statement context
f2.call(2, 3) // ditto
var v1 = 8 + f3.call() // calling function within an expression
var v2 = f3.call() // obtaining return value
System.print([v1, v2]) // print last two results as a list
class MyClass {
static m() { System.print("Static method 'm' called.") }
construct new(x) { _x = x } // stores 'x' in a field
x { _x } // gets the field
x=(y) { _x = y } // sets the field to 'y'
- { MyClass.new(-_x) } // prefix operator
+(o) { MyClass.new(_x + o.x) } // infix operator
toString { _x.toString } // instance method
}
MyClass.m() // call static method 'm'
var mc1 = MyClass.new(40) // construct 'mc1'
var mc2 = MyClass.new(8) // construct 'mc2'
System.print(mc1.x) // print mc1's field using getter
mc1.x = 42 // change mc1's field using setter
System.print(-mc1.x) // invoke prefix operator -
System.print(mc1 + mc2) // invoke infix operator + |
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
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function Factorial(n As Double) As Double
If n < 1 Then
Return 1
End If
Dim result = 1.0
For i = 1 To n
result = result * i
Next
Return result
End Function
Function FirstOption(n As Double) As Double
Return Factorial(2 * n) / (Factorial(n + 1) * Factorial(n))
End Function
Function SecondOption(n As Double) As Double
If n = 0 Then
Return 1
End If
Dim sum = 0
For i = 0 To n - 1
sum = sum + SecondOption(i) * SecondOption((n - 1) - i)
Next
Return sum
End Function
Function ThirdOption(n As Double) As Double
If n = 0 Then
Return 1
End If
Return ((2 * (2 * n - 1)) / (n + 1)) * ThirdOption(n - 1)
End Function
Sub Main()
Const MaxCatalanNumber = 15
Dim initial As DateTime
Dim final As DateTime
Dim ts As TimeSpan
initial = DateTime.Now
For i = 0 To MaxCatalanNumber
Console.WriteLine("CatalanNumber({0}:{1})", i, FirstOption(i))
Next
final = DateTime.Now
ts = final - initial
Console.WriteLine("It took {0}.{1} to execute", ts.Seconds, ts.Milliseconds)
Console.WriteLine()
initial = DateTime.Now
For i = 0 To MaxCatalanNumber
Console.WriteLine("CatalanNumber({0}:{1})", i, SecondOption(i))
Next
final = DateTime.Now
ts = final - initial
Console.WriteLine("It took {0}.{1} to execute", ts.Seconds, ts.Milliseconds)
Console.WriteLine()
initial = DateTime.Now
For i = 0 To MaxCatalanNumber
Console.WriteLine("CatalanNumber({0}:{1})", i, ThirdOption(i))
Next
final = DateTime.Now
ts = final - initial
Console.WriteLine("It took {0}.{1} to execute", ts.Seconds, ts.Milliseconds)
End Sub
End Module |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task 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."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #WYLBUR | WYLBUR | Any Year Calendar
--------------------
S M T W T F S
|
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Processing | Processing | IntDict score;
StringList choices;
StringList guess;
StringList secret;
int gamesWon = -1;
void setup() {
choices = new StringList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
newGame();
}
void newGame() {
gamesWon++;
choices.shuffle();
secret = new StringList();
for (int i=0; i<4; i++) { // selections
secret.append(choices.get(i));
}
newGuess();
println("\nsecret:", secret, "\n");
}
void newGuess() {
guess = new StringList();
score = null;
}
void draw() {
background(0);
text("Bulls & Cows " + gamesWon, 5, 20);
for (int i=0; i<guess.size(); i++) {
text(guess.get(i), 20*i+10, height/2);
}
if (score!=null) {
text("bulls:" + score.get("bulls") + " cows:" + score.get("cows"), 10, height-20);
}
}
void keyReleased() {
if (score!=null && score.get("bulls")==4) newGame();
if (guess.size()==secret.size()) newGuess();
if (guess.hasValue(str(key))) newGuess();
if (key>=48 && key<=57) guess.append(str(key));
if (guess.size()==secret.size()) {
score = checkScore(secret, guess);
println("guess: ", guess, "\n", score, "wins:", gamesWon);
}
}
IntDict checkScore(StringList secret, StringList guess) {
IntDict result = new IntDict();
result.set("bulls", 0);
result.set("cows", 0);
for (int i=0; i<guess.size(); i++) {
if (guess.get(i).equals(secret.get(i))) {
result.add("bulls", 1);
} else if (secret.hasValue(guess.get(i))) {
result.add("cows", 1);
}
}
return result;
} |
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
| #Maple | Maple |
> StringTools:-Encode( "The five boxing wizards jump quickly", encoding = alpharot[3] );
"Wkh ilyh eralqj zlcdugv mxps txlfnob"
> StringTools:-Encode( %, encoding = alpharot[ 23 ] );
"The five boxing wizards jump quickly"
|
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.
| #XLISP | XLISP | ; call a function (procedure) with no arguments:
(foo)
; call a function (procedure) with arguments:
(foo bar baz)
; the first symbol after "(" is the name of the function
; the other symbols are the arguments
; call a function on a list of arguments formed at run time:
(apply foo bar)
; In a REPL, the return value will be printed.
; In other contexts, it can be fed as argument into a further function:
(foo (bar baz))
; this calls bar on the argument baz and then calls foo on the return value
; or it can simply be discarded
(foo bar)
; nothing is done with the return value |
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
| #Vlang | Vlang | import math.big
fn main() {
mut b:= big.zero_int
for n := i64(0); n < 15; n++ {
b = big.integer_from_i64(n)
b = (b*big.two_int).factorial()/(b.factorial()*(b*big.two_int-b).factorial())
println(b/big.integer_from_i64(n+1))
}
} |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task 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."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Wren | Wren | import "/date" for Date
import "/fmt" for Fmt
import "/seq" for Lst
var calendar = Fn.new { |year|
var snoopy = "🐶"
var days = "Su Mo Tu We Th Fr Sa"
var months = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
]
Fmt.print("$70m", snoopy)
var yearStr = "--- %(year) ---"
Fmt.print("$70m\n", yearStr)
var first = List.filled(3, 0)
var mlen = List.filled(3, 0)
var c = 0
for (chunk in Lst.chunks(months, 3)) {
for (i in 0..2) Fmt.write("$20m ", chunk[i])
System.print()
for (i in 0..2) System.write("%(days) ")
System.print()
first[0] = Date.new(year, c*3 + 1, 1).dayOfWeek % 7
first[1] = Date.new(year, c*3 + 2, 1).dayOfWeek % 7
first[2] = Date.new(year, c*3 + 3, 1).dayOfWeek % 7
mlen[0] = Date.monthLength(year, c*3 + 1)
mlen[1] = Date.monthLength(year, c*3 + 2)
mlen[2] = Date.monthLength(year, c*3 + 3)
for (i in 0..5) {
for (j in 0..2) {
var start = 1 + 7 * i - first[j]
for (k in start..start+6) {
if (k >= 1 && k <= mlen[j]) {
Fmt.write("$2d ", k)
} else {
System.write(" ")
}
}
System.write(" ")
}
System.print()
}
System.print()
c = c + 1
}
}
calendar.call(1969) |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Prolog | Prolog | :- use_module(library(lambda)).
:- use_module(library(clpfd)).
% Parameters of the server
% length of the guess
proposition(4).
% Numbers of digits
% 0 -> 8
digits(8).
bulls_and_cows_server :-
proposition(LenGuess),
length(Solution, LenGuess),
choose(Solution),
repeat,
write('Your guess : '),
read(Guess),
( study(Solution, Guess, Bulls, Cows)
-> format('Bulls : ~w Cows : ~w~n', [Bulls, Cows]),
Bulls = LenGuess
; digits(Digits), Max is Digits + 1,
format('Guess must be of ~w digits between 1 and ~w~n',
[LenGuess, Max]),
fail).
choose(Solution) :-
digits(Digits),
Max is Digits + 1,
repeat,
maplist(\X^(X is random(Max) + 1), Solution),
all_distinct(Solution),
!.
study(Solution, Guess, Bulls, Cows) :-
proposition(LenGuess),
digits(Digits),
% compute the transformation 1234 => [1,2,3,4]
atom_chars(Guess, Chars),
maplist(\X^Y^(atom_number(X, Y)), Chars, Ms),
% check that the guess is well formed
length(Ms, LenGuess),
maplist(\X^(X > 0, X =< Digits+1), Ms),
% compute the digit in good place
foldl(\X^Y^V0^V1^((X = Y->V1 is V0+1; V1 = V0)),Solution, Ms, 0, Bulls),
% compute the digits in bad place
foldl(\Y1^V2^V3^(foldl(\X2^Z2^Z3^(X2 = Y1 -> Z3 is Z2+1; Z3 = Z2), Ms, 0, TT1),
V3 is V2+ TT1),
Solution, 0, TT),
Cows is TT - Bulls.
|
http://rosettacode.org/wiki/Caesar_cipher | Caesar cipher |
Task
Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.
This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | cypher[mesg_String,n_Integer]:=StringReplace[mesg,Flatten[Thread[Rule[#,RotateLeft[#,n]]]&/@CharacterRange@@@{{"a","z"},{"A","Z"}}]] |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
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.
| #XSLT | XSLT | <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">
<demo>
<!--
XSLT 1.0 actually defines two function-like constructs that
are used variously depending on the context.
-->
<xsl:call-template name="xpath-function-demos"/>
<xsl:call-template name="xslt-template-demos"/>
</demo>
</xsl:template>
<xsl:template name="xpath-function-demos">
<!--
A 'function' in XSLT 1.0 is a function that can be called from
an XPath 1.0 expression (such as from "select" or "test"
attribute of several XSLT elements). The following demos apply
to these functions.
-->
<!-- Calling function that requires no arguments -->
<!-- false() always returns a boolean false value -->
<line>This test is <xsl:if test="false()">NOT</xsl:if> OK.</line>
<!-- Calling a function with a fixed number of arguments -->
<!-- not() takes exactly 1 argument. starts-with() takes exactly 2 arguments. -->
<line>'haystack' does <xsl:if test="not(starts-with('haystack', 'hay'))">NOT</xsl:if> start with 'hay'.</line>
<!-- Calling a function with optional arguments -->
<!-- If the third argument of substring() is omitted, the length of the string is assumed. -->
<line>'<xsl:value-of select="substring('haystack', 1, 3)"/>' = 'hay'</line>
<line>'<xsl:value-of select="substring('haystack', 4)"/>' = 'stack'</line>
<!-- Calling a function with a variable number of arguments -->
<!-- concat() accepts two or more arguments. -->
<line>'<xsl:value-of select="concat('abcd', 'efgh')"/>' = 'abcdefgh'</line>
<line>'<xsl:value-of select="concat('ij', 'kl', 'mn', 'op')"/>' = 'ijklmnop'</line>
<!--
Aggregate functions such as sum() and count() accept nodesets.
This isn't quite the same as varargs but are probably worth
mentioning.
-->
<line>The number of root elements in the input document is <xsl:value-of select="count(/*)"/> (should be 1).</line>
<!-- Calling a function with named arguments -->
<!-- XPath 1.0 uses only positional parameters. -->
<!-- Using a function in statement context -->
<!--
In general, XPath 1.0 functions have no side effects, so calling
them as statements is useless. While implementations often allow
writing extensions in imperative languages, the semantics of
calling a function with side effects are, at the very least,
implementation-dependent.
-->
<!-- Using a function in first-class context within an expression -->
<!-- Functions are not natively first-class values in XPath 1.0. -->
<!-- Obtaining the return value of a function -->
<!--
The return value of the function is handled as specified by the
various contexts in which an XPath expression is used. The
return value can be stored in a "variable" (no destructive
assignment is allowed), passed as a parameter to a function or a
template, used as a conditional in an <xsl:if/> or <xsl:when/>,
interpolated into text using <xsl:value-of/> or into an
attribute value using brace syntax, and so forth.
-->
<!-- Here, concat() is interpolated into an attribute value using braces ({}). -->
<line foo="{concat('Hello, ', 'Hello, ', 'Hello')}!">See attribute.</line>
<!-- Distinguishing built-in functions and user-defined functions -->
<!--
Given that functions aren't first-class here, the origin of any
given function is known before run time. Incidentally, functions
defined by the standard are generally unprefixed while
implementation-specific extensions (and user extensions, if
available) must be defined within a separate namespace and
prefixed.
-->
<!-- Distinguishing subroutines and functions -->
<!--
There are no "subroutines" in this sense—everything that looks
like a subroutine has some sort of return or result value.
-->
<!-- Stating whether arguments are passed by value or by reference -->
<!-- There is no meaningful distinction since there is no mechanism by which to mutate values. -->
<!-- Is partial application possible and how -->
<!-- Not natively. -->
</xsl:template>
<xsl:template name="xslt-template-demos">
<!--
A 'template' in XSLT 1.0 is a subroutine-like construct. When
given a name (and, optionally, parameters), it can be called
from within another template using the <xsl:call-template/>
element. (An unnamed template is instead called according to its
match and mode attributes.) The following demos apply to named
templates.
-->
<!--
Unlike with functions, there are no built-in named templates to
speak of. The ones used here are defined later in this
transform.
-->
<!--
Answers for these prompts are the same as with XPath functions (above):
Using a function in statement context
Distinguishing subroutines and functions
Stating whether arguments are passed by value or by reference
Is partial application possible and how
-->
<!-- Calling function that requires no arguments -->
<xsl:call-template name="nullary-demo"/>
<!--
Note that even if a template has no parameters, it has access to
the current node (.) as of the time of the call. This
<xsl:apply-templates/> runs a matching template above that calls
the template "nullary-context-demo" with no parameters. Another
way to manipulate a template's idea of which node is current is
by calling from inside a <xsl:for-each/> loop.
-->
<xsl:apply-templates select="/*" mode="nullary-context-demo-mode"/>
<!--
A template parameter is made optional in the definition of the
template by supplying an expression as its select attribute,
which is evaluated and used as its value if the parameter is
omitted. Note, though, that all template parameters have an
implicit default value, the empty string, if the select
attribute is not specified. Therefore, all template parameters
are always optional, even when semantically they should not be.
-->
<!-- Calling a function with a fixed number of arguments -->
<working note="When all parameters are supplied">
<xsl:call-template name="ternary-demo">
<xsl:with-param name="a" select="4"/>
<xsl:with-param name="b">3</xsl:with-param>
<xsl:with-param name="c" select="2 + 3"/>
</xsl:call-template>
</working>
<broken note="When the third parameter 'c' is omitted">
<xsl:call-template name="ternary-demo">
<xsl:with-param name="a" select="4"/>
<xsl:with-param name="b">3</xsl:with-param>
</xsl:call-template>
</broken>
<!-- Calling a function with optional arguments -->
<!-- With the optional third parameter -->
<working name="When all parameters are supplied">
<xsl:call-template name="binary-or-ternary-demo">
<xsl:with-param name="a" select="4"/>
<xsl:with-param name="b" select="3"/>
<xsl:with-param name="c" select="5"/>
</xsl:call-template>
</working>
<!-- Without the optional third parameter (which defaults to 0) -->
<working name="When 'a' and 'b' are supplied but 'c' is defaulted to 0">
<xsl:call-template name="binary-or-ternary-demo">
<xsl:with-param name="a" select="4"/>
<xsl:with-param name="b" select="3"/>
</xsl:call-template>
</working>
<!-- Calling a function with a variable number of arguments -->
<!--
Templates are not varargs-capable. Variable numbers of arguments
usually appear in the form of a nodeset which is then bound to a
single parameter name.
-->
<!-- Calling a function with named arguments -->
<!--
Other than what comes with the current context, template
arguments are always named and can be supplied in any order.
Templates do not support positional arguments. Additionally,
even arguments not specified by the template may be passed; they
are silently ignored.
-->
<!-- Using a function in first-class context within an expression -->
<!-- Templates are not first-class values in XSLT 1.0. -->
<!-- Obtaining the return value of a function -->
<!--
The output of a template is interpolated into the place of the
call. Often, this is directly into the output of the transform,
as with most of the above examples. However, it is also possible
to bind the output as a variable or parameter. This is useful
for using templates to compute parameters for other templates or
for XPath functions.
-->
<!-- Which is the least of 34, 78, 12, 56? -->
<xsl:variable name="lesser-demo-result">
<!-- The variable is bound to the output of this call -->
<xsl:call-template name="lesser-value">
<xsl:with-param name="a">
<!-- A call as a parameter to another call -->
<xsl:call-template name="lesser-value">
<xsl:with-param name="a" select="34"/>
<xsl:with-param name="b" select="78"/>
</xsl:call-template>
</xsl:with-param>
<xsl:with-param name="b">
<!-- and again -->
<xsl:call-template name="lesser-value">
<xsl:with-param name="a" select="12"/>
<xsl:with-param name="b" select="56"/>
</xsl:call-template>
</xsl:with-param>
</xsl:call-template>
</xsl:variable>
<!-- The variable is used here in an XPath expression -->
<line>
<xsl:value-of select="concat('And the answer, which should be 12, is ', $lesser-demo-result, ', of course.')"/>
</line>
<!-- Distinguishing built-in functions and user-defined functions -->
<!-- Virtually all templates are user-defined. -->
</xsl:template>
<!-- Templates supporting template demos above -->
<xsl:template match="/*" mode="nullary-context-demo-mode">
<xsl:call-template name="nullary-context-demo"/>
</xsl:template>
<xsl:template name="nullary-demo">
<line>No parameters needed here!</line>
</xsl:template>
<xsl:template name="nullary-context-demo">
<!-- When a template is called it has access to the current node of the caller -->
<xsl:for-each select="self::*">
<line>The context element here is named "<xsl:value-of select="local-name()"/>"</line>
</xsl:for-each>
</xsl:template>
<xsl:template name="ternary-demo">
<!-- This demo requires, at least semantically, all three parameters. -->
<xsl:param name="a"/>
<xsl:param name="b"/>
<xsl:param name="c"/>
<line>(<xsl:value-of select="$a"/> * <xsl:value-of select="$b"/>) + <xsl:value-of select="$c"/> = <xsl:value-of select="($a * $b) + $c"/></line>
</xsl:template>
<xsl:template name="binary-or-ternary-demo">
<!-- This demo requires the first two parameters, but defaults the third to 0 if it is not supplied. -->
<xsl:param name="a"/>
<xsl:param name="b"/>
<xsl:param name="c" select="0"/>
<line>(<xsl:value-of select="$a"/> * <xsl:value-of select="$b"/>) + <xsl:value-of select="$c"/> = <xsl:value-of select="($a * $b) + $c"/></line>
</xsl:template>
<xsl:template name="lesser-value">
<xsl:param name="a"/>
<xsl:param name="b"/>
<xsl:choose>
<xsl:when test="number($a) < number($b)">
<xsl:value-of select="$a"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$b"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
|
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
| #Wortel | Wortel | ; the following number expression calculcates the nth Catalan number
#~ddiFSFmSoFSn
; which stands for: dup dup inc fac swap fac mult swap double fac swap divide
; to get the first 15 Catalan numbers we map this function over a list from 0 to 15
!*#~ddiFSFmSoFSn @til 15
; returns [1 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674439.9999999995] |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task 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."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #XLISP | XLISP | (defun calendar (year)
(define months-list '(("JANUARY" 31) ("FEBRUARY" 28) ("MARCH" 31) ("APRIL" 30) ("MAY" 31) ("JUNE" 30) ("JULY" 31) ("AUGUST" 31) ("SEPTEMBER" 30) ("OCTOBER" 31) ("NOVEMBER" 30) ("DECEMBER" 31)))
(define days #(" Sunday " "Monday " "Tuesday " "Wednesday " "Thursday " "Friday " "Saturday"))
(defun gauss-algorithm (a)
(rem (+ 1 (+ (* 5 (rem (- a 1) 4)) (* 4 (rem (- a 1) 100)) (* 6 (rem (- a 1) 400)))) 7))
(defun range (start end)
(if (<= start end)
(cons start (range (+ start 1) end))))
(defun string-repeat (s n)
(if (= n 0)
""
(string-append s (string-repeat s (- n 1)))))
(defun print-month (number-of-days start-day)
(defun print-days (day day-of-week end-day)
(if (= day-of-week 7)
(begin
(newline)
(define day-of-week 0)))
(display (string-repeat " " 8))
(if (= day-of-week 0)
(display (string-repeat " " 6)))
(if (< day 10)
(display " "))
(display day)
(display (string-repeat " " 8))
(if (= day end-day)
(begin
(fresh-line)
(+ day-of-week 1))
(print-days (+ day 1) (+ day-of-week 1) end-day)))
(mapcar (lambda (n) (display (vector-ref days n))) (range 0 6))
(newline)
(display (string-repeat (string-repeat " " 18) start-day))
(print-days 1 start-day number-of-days))
(defun leap-yearp (y)
(and (= (mod year 4) 0) (or (/= (mod year 100) 0) (= (mod year 400) 0))))
(define months (make-table))
(mapcar (lambda (month) (table-set! months (car month) (cadr month))) months-list)
(if (leap-yearp year)
(table-set! months "FEBRUARY" 29))
(defun print-calendar (calendar-months weekday)
(newline)
(newline)
(display (string-repeat " " 60))
(display (caar calendar-months))
(newline)
(define next-month-starts (print-month (table-ref months (caar calendar-months)) weekday))
(if (cdr calendar-months)
(print-calendar (cdr calendar-months) next-month-starts)))
(display (string-repeat " " 60))
(display "******** SNOOPY CALENDAR ")
(display year)
(display " ********")
(newline)
(newline)
(print-calendar months-list (gauss-algorithm year)))
(calendar 1969) |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #PureBasic | PureBasic | Define.s secret, guess, c
Define.i bulls, cows, guesses, i
If OpenConsole()
While Len(secret) < 4
c = Chr(Random(8) + 49)
If FindString(secret, c, 1) = 0
secret + c
EndIf
Wend
Repeat
Print("Guess a 4-digit number with no duplicate digits: ")
guess = Input()
If Len(guess) = 0
Break ;break from loop
EndIf
isMalformedGuess = #False
If Len(guess) <> 4
;guess is too short
isMalformedGuess = #True
Else
For i = 1 To 4
c = Mid(guess, i, 1)
If Not FindString("123456789", c, 1) Or CountString(guess, c) <> 1
;guess contains either non-digits or duplicate digits
isMalformedGuess = #True
Break ;break from For/Next loop
EndIf
Next
EndIf
If isMalformedGuess
PrintN("** You should enter 4 different numeric digits that are each from 1 to 9!")
Continue ;continue loop
EndIf
bulls = 0: cows = 0: guesses = guesses + 1
For i = 1 To 4
c = Mid(secret, i, 1)
If Mid(guess, i, 1) = c
bulls + 1
ElseIf FindString(guess, c, 1)
cows + 1
EndIf
Next
Print( Str(bulls) + " bull")
If bulls <> 1
Print( "s")
EndIf
Print( ", " + Str(cows) + " cow")
If cows <> 1
PrintN( "s")
Else
PrintN("")
EndIf
If guess = secret
PrintN("You won after " + Str(guesses) + " guesses!")
Break ;break from loop
EndIf
ForEver
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf |
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
| #MATLAB_.2F_Octave | MATLAB / Octave | function s = cipherCaesar(s, key)
s = char( mod(s - 'A' + key, 25 ) + 'A');
end;
function s = decipherCaesar(s, key)
s = char( mod(s - 'A' - key, 25 ) + 'A');
end; |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
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.
| #Yabasic | Yabasic |
sub test(a, b, c) : print a, b, c : end sub
test(1, 2, 3) // show 1 2 3
test(1, 2) // show 1 2 0
execute("test", 1, 2, 3) // show 1 2 3
sub test$(a$) // show all members of a "list"
local n, i, t$(1)
n = token(a$, t$(), ", ")
for i = 1 to n
print t$(i), " ";
next
end sub
test$("1, 2, 3, 4, text, 6, 7, 8, \"include text\"")
print |
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
| #Wren | Wren | import "/fmt" for Fmt
import "/math" for Int
var catalan = Fn.new { |n|
if (n < 0) Fiber.abort("Argument must be a non-negative integer")
var prod = 1
var i = n + 2
while (i <= n * 2) {
prod = prod * i
i = i + 1
}
return prod / Int.factorial(n)
}
var catalanRec
catalanRec = Fn.new { |n| (n != 0) ? 2 * (2 * n - 1) * catalanRec.call(n - 1) / (n + 1) : 1 }
System.print(" n Catalan number")
System.print("------------------")
for (i in 0..15) System.print("%(Fmt.d(2, i)) %(catalan.call(i))")
System.print("\nand again using a recursive function:\n")
for (i in 0..15) System.print("%(Fmt.d(2, i)) %(catalanRec.call(i))") |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task 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."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
func WeekDay(Year, Month, Day); \Return day of week (0=Sun 1=Mon..6=Sat)
int Year, Month, Day; \Works for years from 1583 onward
[if Month<=2 then [Month:= Month+12; Year:= Year-1];
return rem((Day-1 + (Month+1)*26/10 + Year + Year/4 + Year/100*6 + Year/400)/7);
];
proc Space(N); \Display N space characters
int N;
while N do [ChOut(0, ^ ); N:= N-1];
proc Calendar(Year); \Display calendar for specified year
int Year;
int Month, Col, C, Line, MoName, Days, DayMax, Day(3);
[MoName:= [
" January ", " February", " March ", " April ", " May ", " June ",
" July ", " August ", "September", " October", " November", " December"];
Space(35); Text(0, "[Snoopy]"); CrLf(0);
Space(37); IntOut(0, Year); CrLf(0);
CrLf(0);
for Month:= 1 to 12 do
[for Col:= 0 to 3-1 do
[Space(5); Text(0, MoName(Month+Col-1)); Space(7);
if Col<2 then Space(8);
];
CrLf(0);
for Col:= 0 to 3-1 do
[Text(0, "Su Mo Tu We Th Fr Sa");
if Col<2 then Space(9);
];
CrLf(0);
for Col:= 0 to 3-1 do \day of first Sunday of month (can be negative)
Day(Col):= 1 - WeekDay(Year, Month+Col, 1);
for Line:= 0 to 6-1 do
[for Col:= 0 to 3-1 do
[Days:= [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
DayMax:= Days(Month+Col);
if Month+Col=2 & (rem(Year/4)=0 & rem(Year/100)#0 ! rem(Year/400)=0) then
DayMax:= DayMax+1; \if February and leap year then add a day
for C:= 0 to 7-1 do
[if Day(Col)>=1 & Day(Col)<=DayMax then
[IntOut(0, Day(Col));
if Day(Col)<10 then Space(1); \left justify
]
else Space(2); \suppress out of range days
Space(1);
Day(Col):= Day(Col)+1;
];
if Col<2 then Space(8);
];
CrLf(0);
];
CrLf(0);
Month:= Month+2; \2+1 months per Col(umn)
];
];
Calendar(1969) |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Python | Python | '''
Bulls and cows. A game pre-dating, and similar to, Mastermind.
'''
import random
digits = '123456789'
size = 4
chosen = ''.join(random.sample(digits,size))
#print chosen # Debug
print '''I have chosen a number from %s unique digits from 1 to 9 arranged in a random order.
You need to input a %i digit, unique digit number as a guess at what I have chosen''' % (size, size)
guesses = 0
while True:
guesses += 1
while True:
# get a good guess
guess = raw_input('\nNext guess [%i]: ' % guesses).strip()
if len(guess) == size and \
all(char in digits for char in guess) \
and len(set(guess)) == size:
break
print "Problem, try again. You need to enter %i unique digits from 1 to 9" % size
if guess == chosen:
print '\nCongratulations you guessed correctly in',guesses,'attempts'
break
bulls = cows = 0
for i in range(size):
if guess[i] == chosen[i]:
bulls += 1
elif guess[i] in chosen:
cows += 1
print ' %i Bulls\n %i Cows' % (bulls, cows) |
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
| #Microsoft_Small_Basic | Microsoft Small Basic |
TextWindow.Write("Enter a 1-25 number key (-ve number to decode): ")
key = TextWindow.ReadNumber()
TextWindow.Write("Enter message: ")
message = text.ConvertToUpperCase(TextWindow.Read())
caeser = ""
For n = 1 To Text.GetLength(message)
letter = Text.GetSubText(message,n,1)
code = Text.GetCharacterCode(letter)
If code = 32 Then
newCode = 32
Else
newCode = code + key
If newCode > 90 Then
newCode = newCode - 26
ElseIf newCode < 65 then
newCode = newCode + 26
EndIf
EndIf
codeLetter = Text.GetCharacter(newCode)
caeser = Text.Append(caeser,codeLetter)
EndFor
TextWindow.WriteLine(message)
TextWindow.WriteLine(caeser)
|
http://rosettacode.org/wiki/Bitmap/PPM_conversion_through_a_pipe | Bitmap/PPM conversion through a pipe | Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page.
There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpeg (package "netpbm" on Linux), convert (from ImageMagick, multi-platform).
| #C | C | /* interface */
void print_jpg(image img, int qual); |
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.
| #zkl | zkl | f(); f(1,2,3,4);
fcn f(a=1){}() // define and call f, which gets a set to 1
fcn{vm.arglist}(1,2,3,4) // arglist is L(1,2,3,4)
fcn{a1:=vm.nthArg(1)}(1,2,3) // a1 == 2
(f() == True); (f() and 1 or 2)
if (f()) println()
f(f) // pass f to itself
s:=f()
fcn{}.isType(self.fcn) //True
fcn{}.len.isType(self.fcn) //False, len is a Method |
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
| #Yabasic | Yabasic | print " n First Second Third"
print " - ----- ------ -----"
print
for i = 0 to 15
print i using "###", catalan1(i) using "########", catalan2(i) using "########", catalan3(i) using "########"
next i
end
sub factorial(n)
if n = 0 return 1
return n * factorial(n - 1)
end sub
sub catalan1(n)
local proc, i
prod = 1
for i = n + 2 to 2 * n
prod = prod * i
next i
return int(prod / factorial(n))
end sub
sub catalan2(n)
local sum, i
if n = 0 return 1
sum = 0
for i = 0 to n - 1
sum = sum + catalan2(i) * catalan2(n - 1 - i)
next i
return sum
end sub
sub catalan3(n)
if n = 0 return 1
return ((2 * ((2 * n) - 1)) / (n + 1)) * catalan3(n - 1)
end sub |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task 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."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #Yabasic | Yabasic |
clear screen
sub snoopy()
local n, a$
n = open("snoopy.txt", "r")
while(not eof(#n))
line input #n a$
print " "; : print color("black", "white") a$
wend
close #n
end sub
sub floor(n)
return int(n + 0.5)
end sub
sub string.rep$(s$, n)
local i, r$
for i = 1 to n
r$ = r$ + s$
next i
return r$
end sub
sub center$(s$, width)
local fill1
fill1 = floor(width - len(s$)) / 2
return string.rep$(" ",fill1) + s$ + string.rep$(" ",fill1)
end sub
sub makeMonth(name, skip, days, cal$(), j)
local cal, curday, line$, i
curday = 1 - skip
cal = 3
cal$(j, 2) = " " + daysTitle$ + " "
//cal$(j, 1) = center$(months$(name),len(cal$(j, 2)))
cal$(j, 1) = left$(months$(name) + string.rep$(" ", 80), len(cal$(j, 2)))
while(cal < 9)
line$ = ""
for i = 1 to 7
if curday < 1 or curday > days then
line$ = line$ + " "
else
line$ = line$ + str$(curday, "###")
end if
curday = curday + 1
next
cal = cal + 1
cal$(j, cal) = line$ + " "
wend
end sub
dim months$(12)
n = token("JANUARY,FEBRUARY,MARCH,APRIL,MAY,JUNE,JULY,AUGUST,SEPTEMBER,OCTOBER,NOVEMBER,DECEMBER", months$(), ",")
daysTitle$ = "MO TU WE TH FR SA SU"
dim daysPerMonth(12)
for n = 1 to 12
read daysPerMonth(n)
next
data 31,28,31,30,31,30,31,31,30,31,30,31
sub print_cal(year)
local i, q, l, m, startday, sep, monthwidth, calwidth, dpm, calendar$(12, 9), line$(3)
startday=mod(((year-1)*365+floor((year-1)/4)-floor((year-1)/100)+floor((year-1)/400)),7)
if not mod(year,4) and mod(year,100) or not mod(year,400) then
daysPerMonth(2)=29
end if
sep = 5
monthwidth = len(daysTitle$)
calwidth = 3 * monthwidth + 2 * sep
for i = 1 to 12
dpm = daysPerMonth(i)
makeMonth(i, startday, dpm, calendar$(), i)
startday = mod(startday + dpm, 7)
next
snoopy()
print center$("--- " + str$(year) + " ---", calwidth), "\n"
print string.rep$(" ", sep + 1);
for q = 0 to 3
for l = 1 to 9
for m = 1 to 3
print calendar$(q * 3 + m, l);
next
print
print string.rep$(" ", sep);
next
print
print string.rep$(" ", sep + 1);
next
end sub
print_cal(2018)
|
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #R | R | target <- sample(1:9,4)
bulls <- 0
cows <- 0
attempts <- 0
while (bulls != 4)
{
input <- readline("Guess a 4-digit number with no duplicate digits or 0s: ")
if (nchar(input) == 4)
{
input <- as.integer(strsplit(input,"")[[1]])
if ((sum(is.na(input)+sum(input==0))>=1) | (length(table(input)) != 4)) {print("Malformed input!")} else {
bulls <- sum(input == target)
cows <- sum(input %in% target)-bulls
cat("\n",bulls," Bull(s) and ",cows, " Cow(s)\n")
attempts <- attempts + 1
}
} else {print("Malformed input!")}
}
print(paste("You won in",attempts,"attempt(s)!")) |
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
| #MiniScript | MiniScript | caesar = function(s, key)
chars = s.values
for i in chars.indexes
c = chars[i]
if c >= "a" and c <= "z" then chars[i] = char(97 + (code(c)-97+key)%26)
if c >= "A" and c <= "Z" then chars[i] = char(65 + (code(c)-65+key)%26)
end for
return chars.join("")
end function
print caesar("Hello world!", 7)
print caesar("Olssv dvysk!", 26-7) |
http://rosettacode.org/wiki/Bitmap/PPM_conversion_through_a_pipe | Bitmap/PPM conversion through a pipe | Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page.
There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpeg (package "netpbm" on Linux), convert (from ImageMagick, multi-platform).
| #Go | Go | package main
// Files required to build supporting package raster are found in:
// * Bitmap
// * Write a PPM file
import (
"fmt"
"math/rand"
"os/exec"
"raster"
)
func main() {
b := raster.NewBitmap(400, 300)
// a little extravagant, this draws a design of dots and lines
b.FillRgb(0xc08040)
for i := 0; i < 2000; i++ {
b.SetPxRgb(rand.Intn(400), rand.Intn(300), 0x804020)
}
for x := 0; x < 400; x++ {
for y := 240; y < 245; y++ {
b.SetPxRgb(x, y, 0x804020)
}
for y := 260; y < 265; y++ {
b.SetPxRgb(x, y, 0x804020)
}
}
for y := 0; y < 300; y++ {
for x := 80; x < 85; x++ {
b.SetPxRgb(x, y, 0x804020)
}
for x := 95; x < 100; x++ {
b.SetPxRgb(x, y, 0x804020)
}
}
// pipe logic
c := exec.Command("cjpeg", "-outfile", "pipeout.jpg")
pipe, err := c.StdinPipe()
if err != nil {
fmt.Println(err)
return
}
err = c.Start()
if err != nil {
fmt.Println(err)
return
}
err = b.WritePpmTo(pipe)
if err != nil {
fmt.Println(err)
return
}
err = pipe.Close()
if err != nil {
fmt.Println(err)
}
} |
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.
| #zonnon | zonnon |
module CallingProcs;
type
{public} Vector = array {math} * of integer;
var
nums: array {math} 4 of integer;
ints: Vector;
total: integer;
procedure Init(): boolean; (* private by default *)
begin
nums := [1,2,3,4];
ints := new Vector(5);
ints := [2,4,6,8,10];
return true;
end Init;
(* function *)
procedure Sum(v: Vector): integer;
var
i,s: integer;
begin
s := 0;
for i := 0 to len(v) - 1 do
(* inc is a predefined subroutine *)
inc(s,v[i])
end;
return s
end Sum;
(* subroutine
* @param v: by value
* @param t: by reference
*)
procedure Sum2(v: array {math} * of integer; var t: integer);
var
i: integer;
begin
t := 0;
for i := 0 to len(v) - 1 do
inc(t,v[i])
end
end Sum2;
begin
Init; (* calling a function without parameters *)
total := Sum(nums);
writeln(total);
(* optional arguments not supported *)
(* variable arguments through open arrays *)
writeln(Sum(ints));
(* named arguments not supported *)
ints := [1,3,5,7,9];
Sum2(ints,total);
writeln(total);
end CallingProcs.
|
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.
| #Z80_Assembly | Z80 Assembly | PackNibbles:
;input: B = top nibble, C = bottom nibble. Outputs to accumulator.
;usage: B = &0X, C = &0Y, => A = &XY
LD A,B
AND %00001111
RLCA
RLCA
RLCA
RLCA
OR C
RET |
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
| #XLISP | XLISP | (defun catalan (n)
(if (= n 0)
1
(* (/ (* 2 (- (* 2 n) 1)) (+ n 1)) (catalan (- n 1))) ) )
(defun range (x y)
(cons x
(if (< x y)
(range (+ x 1) y) ) ) )
(print (mapcar catalan (range 0 14))) |
http://rosettacode.org/wiki/Calendar | Calendar | Create a routine that will generate a text calendar for any year.
Test the calendar by generating a calendar for the year 1969, on a device of the time.
Choose one of the following devices:
A line printer with a width of 132 characters.
An IBM 3278 model 4 terminal (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43.
(Ideally, the program will generate well-formatted calendars for any page width from 20 characters up.)
Kudos (κῦδος) for routines that also transition from Julian to Gregorian calendar.
This task 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."
For further Kudos see task CALENDAR, where all code is to be in UPPERCASE.
For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder.
Related task
Five weekends
| #zkl | zkl | var [const] D=Time.Date, days="Su Mo Tu We Th Fr Sa";
fcn center(text,m) { String(" "*((m-text.len())/2),text) }
fcn oneMonth(year,month){
day1:=D.zeller(year,month,1); //1969-1-1 -->3 (Wed, ISO 8601)
dayz:=D.daysInMonth(year,month); //1969-1 -->31
List(center(D.monthNames[month],days.len()),days).extend(
(1).pump(dayz,(0).pump(day1,List,T(Void,""))).apply("%2s ".fmt)
.pump(List,T(Void.Read,days.len()/3,False),String.create));
}
const M=70; // mystery number
fcn oneYear(y=1969,title="3 Days of Peace & Music"){
println(center(title,M),"\n",center(y.toString(),M),"\n");
[1..12,3].pump(String,'wrap(m){ // 3 months per line
mmm:=(m).pump(3,List,oneMonth.fp(y)); //L(L(7-8 lines), L(...), L(...))
if(mmm.apply("len").sum() % 3) // months have diff # of lines, pad
mmm=mmm.apply("append","");
Utils.zipWith("%-25s%-25s%-25s\n".fmt,
mmm.xplode()).concat() + (if (m<D.October) "\n" else "")
})
}
if(vm.numArgs){ y:=vm.nthArg(0).toInt(); oneYear(y,"").println(); }
else oneYear().println(); |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Racket | Racket |
#lang racket
; secret : (listof exact-nonnegative-integer?)
(define secret
(foldr (λ (n result)
(cons n (map (λ (y) (if (>= y n) (add1 y) y))
result)))
'()
(map random '(10 9 8 7))))
; (count-bulls/cows guess) -> (values exact-nonnegative-integer?
; exact-nonnegative-integer?)
; guess : (listof exact-nonnegative-integer?)
(define (count-bulls/cows guess)
(let* ([bulls (map = guess secret)]
[cow-candidates (filter-map (λ (x y) (if (false? x) y #f))
bulls
secret)]
[cows (filter (curryr member cow-candidates) guess)])
(values (length (filter ((curry equal?) #t) bulls))
(length cows))))
; (valid-guess guess-str) -> (or/c (listof exact-nonnegative-integer?) #f)
; guess-str : string?
(define (valid-guess guess-str)
(define (char->digit c)
(- (char->integer c) (char->integer #\0)))
(if (regexp-match-exact? #px"[0-9]{4}" guess-str)
(let ([guess (map char->digit (string->list guess-str))])
(if (andmap (λ (x) (equal? (count ((curry equal?) x) guess) 1))
guess)
guess
#f))
#f))
; Game states
(define win #t)
(define game #f)
; (main-loop state step) -> void?
; state : boolean?
; step : exact-nonnegative-integer?
(define (main-loop state step)
(if (equal? state win)
(printf "You won after ~a guesses." step)
(begin
(let* ([guess-str (read-line)]
[guess (valid-guess guess-str)])
(if (false? guess)
(begin (displayln "Guess should include exactly four different digits")
(main-loop state step))
(let-values ([(bulls cows) (count-bulls/cows guess)])
(if (= bulls 4)
(main-loop win (add1 step))
(begin (printf "Bulls: ~a Cows: ~a\n" bulls cows)
(main-loop state (add1 step))))))))))
(main-loop game 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
| #ML | ML | fun readfile () = readfile []
| x = let val ln = readln ()
in if eof ln then
rev x
else
readfile ` ln :: x
end
local
val lower_a = ord #"a";
val lower_z = ord #"z";
val upper_a = ord #"A";
val upper_z = ord #"Z";
fun which
(c_upper c) = (upper_a, upper_z)
| _ = (lower_a, lower_z)
;
fun scale
(c, az) where (c > #1 az) = scale( (#0 az + (c - #1 az - 1)), az)
| (c, az) = c
in
fun encipher
([], offset, t) = implode ` rev t
| (x :: xs, offset, t) where (c_alphabetic x) = encipher (xs, offset, (chr ` scale (ord x + offset, which x)) :: t)
| (x :: xs, offset, t) = encipher (xs, offset, x :: t)
| (s, offset) = if (offset < 0) then
encipher (explode s, 26 + (offset rem 26), [])
else
encipher (explode s, offset rem 26, [])
end
fun default
(false, y) = y
| (x, _) = x
;
map println ` map (fn s = encipher (s,ston ` default (argv 0, "1"))) ` readfile ();
|
http://rosettacode.org/wiki/Bitmap/PPM_conversion_through_a_pipe | Bitmap/PPM conversion through a pipe | Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page.
There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpeg (package "netpbm" on Linux), convert (from ImageMagick, multi-platform).
| #Julia | Julia | using Images, FileIO
ppmimg = load("data/bitmapInputTest.ppm")
save("data/bitmapOutputTest.jpg", ppmimg) |
http://rosettacode.org/wiki/Bitmap/PPM_conversion_through_a_pipe | Bitmap/PPM conversion through a pipe | Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page.
There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpeg (package "netpbm" on Linux), convert (from ImageMagick, multi-platform).
| #Kotlin | Kotlin | // Version 1.2.40
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color) {
val g = image.graphics
g.color = c
g.fillRect(0, 0, image.width, image.height)
}
fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())
fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))
}
fun main(args: Array<String>) {
// create BasicBitmapStorage object
val width = 640
val height = 640
val bbs = BasicBitmapStorage(width, height)
for (y in 0 until height) {
for (x in 0 until width) {
val c = Color(x % 256, y % 256, (x * y) % 256)
bbs.setPixel(x, y, c)
}
}
// now write the object in PPM format to ImageMagick's STDIN via a pipe
// so it can be converted to a .jpg file and written to disk
val pb = ProcessBuilder("convert", "-", "output_piped.jpg")
pb.directory(null)
pb.redirectInput(ProcessBuilder.Redirect.PIPE)
val buffer = ByteArray(width * 3) // write one line at a time
val proc = pb.start()
val pStdIn = proc.outputStream
pStdIn.use {
val header = "P6\n$width $height\n255\n".toByteArray()
with (it) {
write(header)
for (y in 0 until height) {
for (x in 0 until width) {
val c = bbs.getPixel(x, y)
buffer[x * 3] = c.red.toByte()
buffer[x * 3 + 1] = c.green.toByte()
buffer[x * 3 + 2] = c.blue.toByte()
}
write(buffer)
}
}
}
} |
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.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 REM functions cannot be called in statement context
20 PRINT FN a(5): REM The function is used in first class context. Arguments are not named
30 PRINT FN b(): REM Here we call a function that has no arguments
40 REM subroutines cannot be passed parameters, however variables are global
50 LET n=1: REM This variable will be visible to the called subroutine
60 GO SUB 1000: REM subroutines are called by line number and do not have names
70 REM subroutines do not return a value, but we can see any variables it defined
80 REM subroutines cannot be used in first class context
90 REM builtin functions are used in first class context, and do not need the FN keyword prefix
100 PRINT SIN(50): REM here we pass a parameter to a builtin function
110 PRINT RND(): REM here we use a builtin function without parameters
120 RANDOMIZE: REM statements are not functions and cannot be used in first class context. |
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
| #XPL0 | XPL0 | code CrLf=9, IntOut=11;
int C, N;
[C:= 1;
IntOut(0, C); CrLf(0);
for N:= 1 to 14 do
[C:= C*2*(2*N-1)/(N+1);
IntOut(0, C); CrLf(0);
];
] |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Raku | Raku | my $size = 4;
my @secret = pick $size, '1' .. '9';
for 1..* -> $guesses {
my @guess;
loop {
@guess = (prompt("Guess $guesses: ") // exit).comb;
last if @guess == $size and
all(@guess) eq one(@guess) & any('1' .. '9');
say 'Malformed guess; try again.';
}
my ($bulls, $cows) = 0, 0;
for ^$size {
when @guess[$_] eq @secret[$_] { ++$bulls; }
when @guess[$_] eq any @secret { ++$cows; }
}
last if $bulls == $size;
say "$bulls bulls, $cows cows.";
}
say 'A winner is you!'; |
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
| #Modula-2 | Modula-2 | MODULE CaesarCipher;
FROM Conversions IMPORT IntToStr;
FROM Terminal IMPORT WriteString, WriteLn, ReadChar;
TYPE String = ARRAY[0..64] OF CHAR;
PROCEDURE Encrypt(p : String; key : CARDINAL) : String;
VAR e : String;
VAR i,t : CARDINAL;
VAR c : CHAR;
BEGIN
FOR i:=0 TO HIGH(p) DO
IF p[i]=0C THEN BREAK; END;
t := ORD(p[i]);
IF (p[i]>='A') AND (p[i]<='Z') THEN
t := t + key;
IF t>ORD('Z') THEN
t := t - 26;
END;
ELSIF (p[i]>='a') AND (p[i]<='z') THEN
t := t + key;
IF t>ORD('z') THEN
t := t - 26;
END;
END;
e[i] := CHR(t);
END;
RETURN e;
END Encrypt;
PROCEDURE Decrypt(p : String; key : CARDINAL) : String;
VAR e : String;
VAR i,t : CARDINAL;
VAR c : CHAR;
BEGIN
FOR i:=0 TO HIGH(p) DO
IF p[i]=0C THEN BREAK; END;
t := ORD(p[i]);
IF (p[i]>='A') AND (p[i]<='Z') THEN
t := t - key;
IF t<ORD('A') THEN
t := t + 26;
END;
ELSIF (p[i]>='a') AND (p[i]<='z') THEN
t := t - key;
IF t<ORD('a') THEN
t := t + 26;
END;
END;
e[i] := CHR(t);
END;
RETURN e;
END Decrypt;
VAR txt,enc : String;
VAR key : CARDINAL;
BEGIN
txt := "The five boxing wizards jump quickly";
key := 3;
WriteString("Original: ");
WriteString(txt);
WriteLn;
enc := Encrypt(txt, key);
WriteString("Encrypted: ");
WriteString(enc);
WriteLn;
WriteString("Decrypted: ");
WriteString(Decrypt(enc, key));
WriteLn;
ReadChar;
END CaesarCipher. |
http://rosettacode.org/wiki/Bitmap/PPM_conversion_through_a_pipe | Bitmap/PPM conversion through a pipe | Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page.
There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpeg (package "netpbm" on Linux), convert (from ImageMagick, multi-platform).
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | convert[image_,out_]:=Module[{process=StartProcess[{
"wolfram","-noinit","-noprompt","-run",
"Export[FromCharacterCode["~~ToString[ToCharacterCode[out]]~~"],ImportString[StringRiffle[Table[InputString[],{4}],FromCharacterCode[10]],FromCharacterCode[{80,80,77}]]]"
}]},
WriteLine[process,image];
WriteLine[process,"Quit[]"];
]; |
http://rosettacode.org/wiki/Bitmap/PPM_conversion_through_a_pipe | Bitmap/PPM conversion through a pipe | Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page.
There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpeg (package "netpbm" on Linux), convert (from ImageMagick, multi-platform).
| #Nim | Nim | import bitmap
import ppm_write
import osproc
# Build an image.
var image = newImage(100, 50)
image.fill(color(255, 0, 0))
for row in 10..20:
for col in 0..<image.w:
image[col, row] = color(0, 255, 0)
for row in 30..40:
for col in 0..<image.w:
image[col, row] = color(0, 0, 255)
# Launch ImageMagick "convert".
# Input is taken from stdin and result written in "output1.jpeg".
var p = startProcess("convert", args = ["ppm:-", "output1.jpeg"], options = {poUsePath})
var stream = p.inputStream()
image.writePPM(stream)
p.close()
# Launch Netpbm "pnmtojpeg".
# Input is taken from stdin and output sent to "output2.jpeg".
p = startProcess("pnmtojpeg >output2.jpeg", options = {poUsePath, poEvalCommand})
stream = p.inputStream()
image.writePPM(stream)
p.close() |
http://rosettacode.org/wiki/Bitmap/PPM_conversion_through_a_pipe | Bitmap/PPM conversion through a pipe | Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page.
There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpeg (package "netpbm" on Linux), convert (from ImageMagick, multi-platform).
| #OCaml | OCaml | let print_jpeg ~img ?(quality=96) () =
let cmd = Printf.sprintf "cjpeg -quality %d" quality in
(*
let cmd = Printf.sprintf "ppmtojpeg -quality %d" quality in
let cmd = Printf.sprintf "convert ppm:- -quality %d jpg:-" quality in
*)
let ic, oc = Unix.open_process cmd in
output_ppm ~img ~oc;
try
while true do
let c = input_char ic in
print_char c
done
with End_of_file -> ()
;; |
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
| #zkl | zkl | var BN=Import("zklBigNum");
fcn catalan(n){
BN(2*n).factorial() / BN(n+1).factorial() / BN(n).factorial();
}
foreach n in (16){
println("%2d --> %,d".fmt(n, catalan(n)));
}
println("%2d --> %,d".fmt(100, catalan(100))); |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Red | Red |
Red[]
a: "0123456789"
bulls: 0
random/seed now/time
number: copy/part random a 4
while [bulls <> 4] [
bulls: 0
cows: 0
guess: ask "make a guess: "
repeat i 4 [
if (pick guess i) = (pick number i) [bulls: bulls + 1]
]
cows: (length? intersect guess number) - bulls
print ["bulls: " bulls " cows: " cows]
]
print "You won!"
|
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
| #Modula-3 | Modula-3 | MODULE Caesar EXPORTS Main;
IMPORT IO, IntSeq, Text;
EXCEPTION BadCharacter;
(* Used whenever message contains a non-alphabetic character. *)
PROCEDURE Encode(READONLY message: TEXT; numbers: IntSeq.T) RAISES { BadCharacter } =
(*
Converts upper or lower case letter to 0..25.
Raises a "BadCharacter" exception for non-alphabetic characters.
*)
VAR
c: CHAR;
v: INTEGER;
BEGIN
FOR i := 0 TO Text.Length(message) - 1 DO
c := Text.GetChar(message, i);
CASE c OF
| 'A'..'Z' => v := ORD(c) - ORD('A');
| 'a'..'z' => v := ORD(c) - ORD('a');
ELSE
RAISE BadCharacter;
END;
numbers.addhi(v);
END;
END Encode;
PROCEDURE Decode(READONLY numbers: IntSeq.T; VAR message: TEXT) =
(* converts numbers in 0..26 to lower case characters *)
BEGIN
FOR i := 0 TO numbers.size() - 1 DO
message := message & Text.FromChar(VAL(numbers.get(i) + ORD('a'), CHAR));
END;
END Decode;
PROCEDURE Crypt(numbers: IntSeq.T; key: INTEGER) =
(*
In the Caesar cipher, encryption and decryption are really the same;
one adds the key, the other subtracts it. We can view this as adding a positive
or nevative integer; the common task is adding an integer. We call this "Crypt".
*)
BEGIN
FOR i := 0 TO numbers.size() - 1 DO
numbers.put(i, (numbers.get(i) + key) MOD 26);
END;
END Crypt;
PROCEDURE Encrypt(numbers: IntSeq.T; key := 4) =
(*
Encrypts a message of numbers using the designated key.
The result is also stored in "numbers".
*)
BEGIN
Crypt(numbers, key);
END Encrypt;
PROCEDURE Decrypt(numbers: IntSeq.T; key := 4) =
(*
Decrypts a message of numbers using the designated key.
The result is also stored in "numbers".
*)
BEGIN
Crypt(numbers, -key);
END Decrypt;
VAR
message := "";
buffer := NEW(IntSeq.T).init(22); (* sequence of 22 int's *)
BEGIN
TRY
Encode("WhenCaesarSetOffToGaul", buffer);
EXCEPT BadCharacter =>
(*
This should never occur.
Try adding spaces to the above to see what happens.
*)
IO.Put("Encountered a bad character in the input; completing partial task\n");
END;
Encrypt(buffer);
Decrypt(buffer);
Decode(buffer, message);
IO.Put(message); IO.PutChar('\n');
END Caesar. |
http://rosettacode.org/wiki/Bitmap/PPM_conversion_through_a_pipe | Bitmap/PPM conversion through a pipe | Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page.
There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpeg (package "netpbm" on Linux), convert (from ImageMagick, multi-platform).
| #Perl | Perl | # 20211224 Perl programming solution
use strict;
use warnings;
use Imager;
use Imager::Test 'test_image_raw';
my $img = test_image_raw();
my $IO = Imager::io_new_bufchain();
Imager::i_writeppm_wiol($img, $IO) or die;
my $raw = Imager::io_slurp($IO) or die;
open my $fh, '|-', '/usr/local/bin/convert - -compress none output.jpg' or die;
binmode $fh;
syswrite $fh, $raw or die;
close $fh; |
http://rosettacode.org/wiki/Bitmap/PPM_conversion_through_a_pipe | Bitmap/PPM conversion through a pipe | Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page.
There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpeg (package "netpbm" on Linux), convert (from ImageMagick, multi-platform).
| #Phix | Phix | -- demo\rosetta\Bitmap_PPM_conversion_through_a_pipe.exw
without js -- file i/o, system_exec(), pipes[!!]
include builtins\pipeio.e
include builtins\serialize.e
include ppm.e -- read_ppm()
sequence pipes = repeat(0,3)
pipes[PIPEIN] = create_pipe(INHERIT_WRITE)
-- Create the child process, with replacement stdin.
string cmd = sprintf("%s viewppm -save test.jpg",{get_interpreter(true)})
atom hProc = system_exec(cmd, 12, pipes),
hPipe = pipes[PIPEIN][WRITE_PIPE]
sequence img = serialize(read_ppm("Lena.ppm",bFlat:=true))
if not write_to_pipe(hPipe,img) then crash("error") end if
-- Close the pipe handle so the child process stops reading.
--hPipe = close_handles(hPipe)
pipes = close_handles(pipes) -- (may as well do the lot)
?"done"
{} = wait_key()
|
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
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 FOR i=0 TO 15
20 LET n=i: LET m=2*n
30 LET r=1: LET d=m-n
40 IF d>n THEN LET n=d: LET d=m-n
50 IF m<=n THEN GO TO 90
60 LET r=r*m: LET m=m-1
70 IF (d>1) AND NOT FN m(r,d) THEN LET r=r/d: LET d=d-1: GO TO 70
80 GO TO 50
90 PRINT i;TAB 4;r/(1+n)
100 NEXT i
110 STOP
120 DEF FN m(a,b)=a-INT (a/b)*b: REM Modulus function
|
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #REXX | REXX | /*REXX program scores the Bulls & Cows game with CBLFs (Carbon Based Life Forms). */
?=; do until length(?)==4; r= random(1, 9) /*generate a unique four-digit number. */
if pos(r,?)\==0 then iterate; ?= ? || r /*don't allow a repeated digit/numeral. */
end /*until length*/ /* [↑] builds a unique four-digit number*/
$= '──────── [Bulls & Cows] ' /*a literal that is part of the prompt. */
do until bulls==4; say /*play until guessed or enters "Quit".*/
say $ 'Please enter a 4-digit guess (with no zeroes) [or Quit]:'
pull n; n=space(n, 0); if abbrev('QUIT', n, 1) then exit /*user wants to quit?*/
q=?; L= length(n); bulls= 0; cows= 0 /*initialize some REXX variables. */
do j=1 for L; if substr(n, j, 1)\==substr(q, j, 1) then iterate /*is bull?*/
bulls= bulls +1; q= overlay(., q, j) /*bump the bull count; disallow for cow.*/
end /*j*/ /* [↑] bull count───────────────────────*/
/*is cow? */
do k=1 for L; _= substr(n, k, 1); if pos(_, q)==0 then iterate
cows=cows + 1; q= translate(q, , _) /*bump the cow count; allow mult digits.*/
end /*k*/ /* [↑] cow count───────────────────────*/
say; @= 'You got' bulls
if L\==0 & bulls\==4 then say $ @ 'bull's(bulls) "and" cows 'cow's(cows).
end /*until bulls*/
say " ┌─────────────────────────────────────────┐"
say " │ │"
say " │ Congratulations, you've guessed it !! │"
say " │ │"
say " └─────────────────────────────────────────┘"
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
s: if arg(1)==1 then return ''; return "s" /*this function handles pluralization. */ |
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
| #Nanoquery | Nanoquery | def caesar_encode(plaintext, shift)
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lowercase = "abcdefghijklmnopqrstuvwxyz"
cipher = ""
for char in plaintext
if char in uppercase
cipher += uppercase[uppercase[char] - (26 - shift)]
else if char in lowercase
cipher += lowercase[lowercase[char] - (26 - shift)]
else
cipher += char
end
end
return cipher
end
def caesar_decode(cipher, shift)
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lowercase = "abcdefghijklmnopqrstuvwxyz"
plaintext = ""
for char in cipher
if char in uppercase
plaintext += uppercase[uppercase[char] - shift]
else if char in lowercase
plaintext += lowercase[lowercase[char] - shift]
else
plaintext += char
end
end
return plaintext
end |
http://rosettacode.org/wiki/Bitmap/PPM_conversion_through_a_pipe | Bitmap/PPM conversion through a pipe | Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page.
There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpeg (package "netpbm" on Linux), convert (from ImageMagick, multi-platform).
| #PicoLisp | PicoLisp | # Create an empty image of 120 x 90 pixels
(setq *Ppm (make (do 90 (link (need 120)))))
# Fill background with green color
(ppmFill *Ppm 0 255 0)
# Draw a diagonal line
(for I 80 (ppmSetPixel *Ppm I I 0 0 0))
# Write to "img.jpg" through a pipe
(ppmWrite *Ppm '("convert" "-" "img.jpg")) |
http://rosettacode.org/wiki/Bitmap/PPM_conversion_through_a_pipe | Bitmap/PPM conversion through a pipe | Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page.
There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpeg (package "netpbm" on Linux), convert (from ImageMagick, multi-platform).
| #Python | Python |
"""
Adapted from https://stackoverflow.com/questions/26937143/ppm-to-jpeg-jpg-conversion-for-python-3-4-1
Requires pillow-5.3.0 with Python 3.7.1 32-bit on Windows.
Sample ppm graphics files from http://www.cs.cornell.edu/courses/cs664/2003fa/images/
"""
from PIL import Image
im = Image.open("boxes_1.ppm")
im.save("boxes_1.jpg")
|
http://rosettacode.org/wiki/Bitmap/PPM_conversion_through_a_pipe | Bitmap/PPM conversion through a pipe | Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page.
There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpeg (package "netpbm" on Linux), convert (from ImageMagick, multi-platform).
| #Racket | Racket |
(define (ppm->jpeg bitmap [jpg-file "output"] [quality 75])
(define command (format "convert ppm:- -quality ~a jpg:~a.jpg" quality jpg-file))
(match-define (list in out pid err ctrl) (process command))
(bitmap->ppm bitmap out)
(close-input-port in)
(close-output-port out))
(ppm->jpeg bm) |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Ring | Ring |
# Project : Bulls and cows
secret = ""
while len(secret) != 4
c = char(48 + random(9))
if substr(secret, c) = 0
secret = secret + c
ok
end
see "guess a four-digit number with no digit used twice."
guesses = 0
guess = ""
while true
guess = ""
while len(guess) != 4
see "enter your guess: "
give guess
if len(guess) != 4
see "must be a four-digit number" + nl
ok
end
guesses = guesses + 1
if guess = secret
see "you won after " + guesses + " guesses!"
exit
ok
bulls = 0
cows = 0
for i = 1 to 4
c = secret[i]
if guess[i] = c
bulls = bulls + 1
but substr(guess, c) > 0
cows = cows + 1
ok
next
see "you got " + bulls + " bull(s) and " + cows + " cow(s)." + nl
end
|
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe | Bitmap/Read an image through a pipe | This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PPM format like a (natural) bridge between the foreign image format and our simple data storage.
| #AutoHotkey | AutoHotkey | ppm := Run("cmd.exe /c convert lena50.jpg ppm:-")
; pipe in from imagemagick
img := ppm_read("", ppm) ;
x := img[4,4] ; get pixel(4,4)
y := img[24,24] ; get pixel(24,24)
msgbox % x.rgb() " " y.rgb()
img.write("lena50copy.ppm")
return
ppm_read(filename, ppmo=0) ; only ppm6 files supported
{
if !ppmo ; if image not already in memory, read from filename
fileread, ppmo, % filename
index := 1
pos := 1
loop, parse, ppmo, `n, `r
{
if (substr(A_LoopField, 1, 1) == "#")
continue
loop,
{
if !pos := regexmatch(ppmo, "\d+", pixel, pos)
break
bitmap%A_Index% := pixel
if (index == 4)
Break
pos := regexmatch(ppmo, "\s", x, pos)
index ++
}
}
type := bitmap1
width := bitmap2
height := bitmap3
maxcolor := bitmap4
bitmap := Bitmap(width, height, color(0,0,0))
index := 1
i := 1
j := 1
bits := pos
loop % width * height
{
bitmap[i, j, "r"] := numget(ppmo, 3 * A_Index + bits, "uchar")
bitmap[i, j, "g"] := numget(ppmo, 3 * A_Index + bits + 1, "uchar")
bitmap[i, j, "b"] := numget(ppmo, 3 * A_Index + bits + 2, "uchar")
if (j == width)
{
j := 1
i += 1
}
else
j++
}
return bitmap
}
#include bitmap_storage.ahk ; from http://rosettacode.org/wiki/Basic_bitmap_storage/AutoHotkey
#include run.ahk ; http://www.autohotkey.com/forum/viewtopic.php?t=16823
|
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols nobinary
messages = [ -
'The five boxing wizards jump quickly', -
'Attack at dawn!', -
'HI']
keys = [1, 2, 20, 25, 13]
loop m_ = 0 to messages.length - 1
in = messages[m_]
loop k_ = 0 to keys.length - 1
say 'Caesar cipher, key:' keys[k_].right(3)
ec = caesar_encipher(in, keys[k_])
dc = caesar_decipher(ec, keys[k_])
say in
say ec
say dc
say
end k_
say 'Rot-13:'
ec = rot13(in)
dc = rot13(ec)
say in
say ec
say dc
say
end m_
return
method rot13(input) public static signals IllegalArgumentException
return caesar(input, 13, isFalse)
method caesar(input = Rexx, idx = int, caps = boolean) public static signals IllegalArgumentException
if idx < 1 | idx > 25 then signal IllegalArgumentException()
-- 12345678901234567890123456
itab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
shift = itab.length - idx
parse itab tl +(shift) tr
otab = tr || tl
if caps then input = input.upper
cipher = input.translate(itab || itab.lower, otab || otab.lower)
return cipher
method caesar_encipher(input = Rexx, idx = int, caps = boolean) public static signals IllegalArgumentException
return caesar(input, idx, caps)
method caesar_decipher(input = Rexx, idx = int, caps = boolean) public static signals IllegalArgumentException
return caesar(input, int(26) - idx, isFalse)
method caesar_encipher(input = Rexx, idx = int) public static signals IllegalArgumentException
return caesar(input, idx, isFalse)
method caesar_decipher(input = Rexx, idx = int) public static signals IllegalArgumentException
return caesar(input, int(26) - idx, isFalse)
method caesar_encipher(input = Rexx, idx = int, opt = Rexx) public static signals IllegalArgumentException
return caesar(input, idx, opt)
method caesar_decipher(input = Rexx, idx = int, opt = Rexx) public static signals IllegalArgumentException
return caesar(input, int(26) - idx, opt)
method caesar(input = Rexx, idx = int, opt = Rexx) public static signals IllegalArgumentException
if opt.upper.abbrev('U') >= 1 then caps = isTrue
else caps = isFalse
return caesar(input, idx, caps)
method caesar(input = Rexx, idx = int) public static signals IllegalArgumentException
return caesar(input, idx, isFalse)
method isTrue public static returns boolean
return (1 == 1)
method isFalse public static returns boolean
return \isTrue |
http://rosettacode.org/wiki/Bitmap/PPM_conversion_through_a_pipe | Bitmap/PPM conversion through a pipe | Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page.
There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpeg (package "netpbm" on Linux), convert (from ImageMagick, multi-platform).
| #Raku | Raku | # Reference:
# https://rosettacode.org/wiki/Bitmap/Write_a_PPM_file#Raku
use v6;
class Pixel { has uint8 ($.R, $.G, $.B) }
class Bitmap {
has UInt ($.width, $.height);
has Pixel @!data;
method fill(Pixel $p) {
@!data = $p.clone xx ($!width*$!height)
}
method pixel(
$i where ^$!width,
$j where ^$!height
--> Pixel
) is rw { @!data[$i*$!height + $j] }
method data { @!data }
}
role PPM {
method P6 returns Blob {
"P6\n{self.width} {self.height}\n255\n".encode('ascii')
~ Blob.new: flat map { .R, .G, .B }, self.data
}
}
my Bitmap $b = Bitmap.new(width => 125, height => 125) but PPM;
for flat ^$b.height X ^$b.width -> $i, $j {
$b.pixel($i, $j) = Pixel.new: :R($i*2), :G($j*2), :B(255-$i*2);
}
my $proc = run '/usr/bin/convert','-','output_piped.jpg', :in;
$proc.in.write: $b.P6;
$proc.in.close; |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Ruby | Ruby | def generate_word(len)
[*"1".."9"].shuffle.first(len) # [*"1".."9"].sample(len) ver 1.9+
end
def get_guess(len)
loop do
print "Enter a guess: "
guess = gets.strip
err = case
when guess.match(/[^1-9]/) ; "digits only"
when guess.length != len ; "exactly #{len} digits"
when guess.split("").uniq.length != len; "digits must be unique"
else return guess.split("")
end
puts "the word must be #{len} unique digits between 1 and 9 (#{err}). Try again."
end
end
def score(word, guess)
bulls = cows = 0
guess.each_with_index do |num, idx|
if word[idx] == num
bulls += 1
elsif word.include? num
cows += 1
end
end
[bulls, cows]
end
word_length = 4
puts "I have chosen a number with #{word_length} unique digits from 1 to 9."
word = generate_word(word_length)
count = 0
loop do
guess = get_guess(word_length)
count += 1
break if word == guess
puts "that guess has %d bulls and %d cows" % score(word, guess)
end
puts "you guessed correctly in #{count} tries." |
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe | Bitmap/Read an image through a pipe | This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PPM format like a (natural) bridge between the foreign image format and our simple data storage.
| #C | C | image read_image(const char *name); |
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe | Bitmap/Read an image through a pipe | This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PPM format like a (natural) bridge between the foreign image format and our simple data storage.
| #Go | Go | package main
// Files required to build supporting package raster are found in:
// * Bitmap
// * Read a PPM file
// * Write a PPM file
import (
"log"
"os/exec"
"raster"
)
func main() {
c := exec.Command("convert", "Unfilledcirc.png", "-depth", "1", "ppm:-")
pipe, err := c.StdoutPipe()
if err != nil {
log.Fatal(err)
}
if err = c.Start(); err != nil {
log.Fatal(err)
}
b, err := raster.ReadPpmFrom(pipe)
if err != nil {
log.Fatal(err)
}
if err = b.WritePpmFile("Unfilledcirc.ppm"); err != nil {
log.Fatal(err)
}
} |
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe | Bitmap/Read an image through a pipe | This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PPM format like a (natural) bridge between the foreign image format and our simple data storage.
| #Julia | Julia | using Images, FileIO
img = load("data/bitmapOutputTest.jpg")
save("data/bitmapOutputTest.ppm", img) |
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
| #Nim | Nim | import strutils
proc caesar(s: string, k: int, decode = false): string =
var k = if decode: 26 - k else: k
result = ""
for i in toUpper(s):
if ord(i) >= 65 and ord(i) <= 90:
result.add(chr((ord(i) - 65 + k) mod 26 + 65))
let msg = "The quick brown fox jumped over the lazy dogs"
echo msg
let enc = caesar(msg, 11)
echo enc
echo caesar(enc, 11, decode = true) |
http://rosettacode.org/wiki/Bitmap/PPM_conversion_through_a_pipe | Bitmap/PPM conversion through a pipe | Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page.
There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpeg (package "netpbm" on Linux), convert (from ImageMagick, multi-platform).
| #Ruby | Ruby | class Pixmap
PIXMAP_FORMATS = ["P3", "P6"] # implemented output formats
PIXMAP_BINARY_FORMATS = ["P6"] # implemented output formats which are binary
def write_ppm(ios, format="P6")
if not PIXMAP_FORMATS.include?(format)
raise NotImplementedError, "pixmap format #{format} has not been implemented"
end
ios.puts format, "#{@width} #{@height}", "255"
ios.binmode if PIXMAP_BINARY_FORMATS.include?(format)
@height.times do |y|
@width.times do |x|
case format
when "P3" then ios.print @data[x][y].values.join(" "),"\n"
when "P6" then ios.print @data[x][y].values.pack('C3')
end
end
end
end
def save(filename, opts={:format=>"P6"})
File.open(filename, 'w') do |f|
write_ppm(f, opts[:format])
end
end
def print(opts={:format=>"P6"})
write_ppm($stdout, opts[:format])
end
def save_as_jpeg(filename, quality=75)
pipe = IO.popen("convert ppm:- -quality #{quality} jpg:#{filename}", 'w')
write_ppm(pipe)
pipe.close
end
end
image = Pixmap.open('file.ppm')
image.save_as_jpeg('file.jpg') |
http://rosettacode.org/wiki/Bitmap/PPM_conversion_through_a_pipe | Bitmap/PPM conversion through a pipe | Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page.
There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpeg (package "netpbm" on Linux), convert (from ImageMagick, multi-platform).
| #Standard_ML | Standard ML |
val useOSConvert = fn ppm =>
let
val img = String.translate (fn #"\"" => "\\\""|n=>str n ) ppm ;
val app = " convert - jpeg:- "
val fname = "/tmp/fConv" ^ (String.extract (Time.toString (Posix.ProcEnv.time()),7,NONE) );
val shellCommand = " echo \"" ^ img ^ "\" | " ^ app ;
val me = ( Posix.FileSys.mkfifo
(fname,
Posix.FileSys.S.flags [ Posix.FileSys.S.irusr,Posix.FileSys.S.iwusr ]
) ;
Posix.Process.fork ()
) ;
in
if (Option.isSome me) then
let
val fin =BinIO.openIn fname
in
( Posix.Process.sleep (Time.fromReal 0.1) ;
BinIO.inputAll fin before
(BinIO.closeIn fin ; OS.FileSys.remove fname )
)
end
else
( OS.Process.system ( shellCommand ^ " > " ^ fname ^ " 2>&1 " ) ;
Word8Vector.fromList [] before OS.Process.exit OS.Process.success
)
end;
|
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Rust | Rust | use std::io;
use rand::{Rng,thread_rng};
extern crate rand;
const NUMBER_OF_DIGITS: usize = 4;
static DIGITS: [char; 9] = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];
fn generate_digits() -> Vec<char> {
let mut temp_digits: Vec<_> = (&DIGITS[..]).into();
thread_rng().shuffle(&mut temp_digits);
return temp_digits.iter().take(NUMBER_OF_DIGITS).map(|&a| a).collect();
}
fn parse_guess_string(guess: &str) -> Result<Vec<char>, String> {
let chars: Vec<char> = (&guess).chars().collect();
if !chars.iter().all(|c| DIGITS.contains(c)) {
return Err("only digits, please".to_string());
}
if chars.len() != NUMBER_OF_DIGITS {
return Err(format!("you need to guess with {} digits", NUMBER_OF_DIGITS));
}
let mut uniques: Vec<char> = chars.clone();
uniques.dedup();
if uniques.len() != chars.len() {
return Err("no duplicates, please".to_string());
}
return Ok(chars);
}
fn calculate_score(given_digits: &[char], guessed_digits: &[char]) -> (usize, usize) {
let mut bulls = 0;
let mut cows = 0;
for i in 0..NUMBER_OF_DIGITS {
let pos: Option<usize> = guessed_digits.iter().position(|&a| -> bool {a == given_digits[i]});
match pos {
None => (),
Some(p) if p == i => bulls += 1,
Some(_) => cows += 1
}
}
return (bulls, cows);
}
fn main() {
let reader = io::stdin();
loop {
let given_digits = generate_digits();
println!("I have chosen my {} digits. Please guess what they are", NUMBER_OF_DIGITS);
loop {
let guess_string: String = {
let mut buf = String::new();
reader.read_line(&mut buf).unwrap();
buf.trim().into()
};
let digits_maybe = parse_guess_string(&guess_string);
match digits_maybe {
Err(msg) => {
println!("{}", msg);
continue;
},
Ok(guess_digits) => {
match calculate_score(&given_digits, &guess_digits) {
(NUMBER_OF_DIGITS, _) => {
println!("you win!");
break;
},
(bulls, cows) => println!("bulls: {}, cows: {}", bulls, cows)
}
}
}
}
}
} |
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe | Bitmap/Read an image through a pipe | This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PPM format like a (natural) bridge between the foreign image format and our simple data storage.
| #Kotlin | Kotlin | // Version 1.2.40
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import java.io.PushbackInputStream
import java.io.File
import javax.imageio.ImageIO
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color) {
val g = image.graphics
g.color = c
g.fillRect(0, 0, image.width, image.height)
}
fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())
fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))
fun toGrayScale() {
for (x in 0 until image.width) {
for (y in 0 until image.height) {
var rgb = image.getRGB(x, y)
val red = (rgb shr 16) and 0xFF
val green = (rgb shr 8) and 0xFF
val blue = rgb and 0xFF
val lumin = (0.2126 * red + 0.7152 * green + 0.0722 * blue).toInt()
rgb = (lumin shl 16) or (lumin shl 8) or lumin
image.setRGB(x, y, rgb)
}
}
}
}
fun PushbackInputStream.skipComment() {
while (read().toChar() != '\n') {}
}
fun PushbackInputStream.skipComment(buffer: ByteArray) {
var nl: Int
while (true) {
nl = buffer.indexOf(10) // look for newline at end of comment
if (nl != -1) break
read(buffer) // read another buffer full if newline not yet found
}
val len = buffer.size
if (nl < len - 1) unread(buffer, nl + 1, len - nl - 1)
}
fun Byte.toUInt() = if (this < 0) 256 + this else this.toInt()
fun main(args: Array<String>) {
// use file, output_piped.jpg, created in the
// Bitmap/PPM conversion through a pipe task
val pb = ProcessBuilder("convert", "output_piped.jpg", "ppm:-")
pb.directory(null)
pb.redirectOutput(ProcessBuilder.Redirect.PIPE)
val proc = pb.start()
val pStdOut = proc.inputStream
val pbis = PushbackInputStream(pStdOut, 80)
pbis.use {
with (it) {
val h1 = read().toChar()
val h2 = read().toChar()
val h3 = read().toChar()
if (h1 != 'P' || h2 != '6' || h3 != '\n') {
println("Not a P6 PPM file")
System.exit(1)
}
val sb = StringBuilder()
while (true) {
val r = read().toChar()
if (r == '#') { skipComment(); continue }
if (r == ' ') break // read until space reached
sb.append(r.toChar())
}
val width = sb.toString().toInt()
sb.setLength(0)
while (true) {
val r = read().toChar()
if (r == '#') { skipComment(); continue }
if (r == '\n') break // read until new line reached
sb.append(r.toChar())
}
val height = sb.toString().toInt()
sb.setLength(0)
while (true) {
val r = read().toChar()
if (r == '#') { skipComment(); continue }
if (r == '\n') break // read until new line reached
sb.append(r.toChar())
}
val maxCol = sb.toString().toInt()
if (maxCol !in 0..255) {
println("Maximum color value is outside the range 0..255")
System.exit(1)
}
var buffer = ByteArray(80)
// get rid of any more opening comments before reading data
while (true) {
read(buffer)
if (buffer[0].toChar() == '#') {
skipComment(buffer)
}
else {
unread(buffer)
break
}
}
// read data
val bbs = BasicBitmapStorage(width, height)
buffer = ByteArray(width * 3)
var y = 0
while (y < height) {
read(buffer)
for (x in 0 until width) {
val c = Color(
buffer[x * 3].toUInt(),
buffer[x * 3 + 1].toUInt(),
buffer[x * 3 + 2].toUInt()
)
bbs.setPixel(x, y, c)
}
y++
}
// convert to grayscale and save to a file
bbs.toGrayScale()
val grayFile = File("output_piped_gray.jpg")
ImageIO.write(bbs.image, "jpg", grayFile)
}
}
} |
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
| #Oberon-2 | Oberon-2 |
MODULE Caesar;
IMPORT
Out;
CONST
encode* = 1;
decode* = -1;
VAR
text,cipher: POINTER TO ARRAY OF CHAR;
PROCEDURE Cipher*(txt: ARRAY OF CHAR; key: INTEGER; op: INTEGER; VAR cipher: ARRAY OF CHAR);
VAR
i: LONGINT;
BEGIN
i := 0;
WHILE i < LEN(txt) - 1 DO
IF (txt[i] >= 'A') & (txt[i] <= 'Z') THEN
cipher[i] := CHR(ORD('A') + ((ORD(txt[i]) - ORD('A') + (key * op))) MOD 26)
ELSIF (txt[i] >= 'a') & (txt[i] <= 'z') THEN
cipher[i] := CHR(ORD('a') + ((ORD(txt[i]) - ORD('a') + (key * op))) MOD 26)
ELSE
cipher[i] := txt[i]
END;
INC(i)
END;
cipher[i] := 0X
END Cipher;
BEGIN
NEW(text,3);NEW(cipher,3);
COPY("HI",text^);
Out.String(text^);Out.String(" =e=> ");
Cipher(text^,2,encode,cipher^);
Out.String(cipher^);
COPY(cipher^,text^);
Cipher(text^,2,decode,cipher^);
Out.String(" =d=> ");Out.String(cipher^);Out.Ln;
COPY("ZA",text^);
Out.String(text^);Out.String(" =e=> ");
Cipher(text^,2,encode,cipher^);
Out.String(cipher^);
COPY(cipher^,text^);
Cipher(text^,2,decode,cipher^);
Out.String(" =d=> ");Out.String(cipher^);Out.Ln;
NEW(text,37);NEW(cipher,37);
COPY("The five boxing wizards jump quickly",text^);
Out.String(text^);Out.String(" =e=> ");
Cipher(text^,3,encode,cipher^);
Out.String(cipher^);
COPY(cipher^,text^);
Cipher(text^,3,decode,cipher^);
Out.String(" =d=> ");Out.String(cipher^);Out.Ln;
END Caesar.
|
http://rosettacode.org/wiki/Bitmap/PPM_conversion_through_a_pipe | Bitmap/PPM conversion through a pipe | Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page.
There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpeg (package "netpbm" on Linux), convert (from ImageMagick, multi-platform).
| #Tcl | Tcl | package require Tk
proc output_jpeg {image filename {quality 75}} {
set f [open |[list convert ppm:- -quality $quality jpg:- > $filename] w]
fconfigure $f -translation binary
puts -nonewline $f [$image data -format ppm]
close $f
} |
http://rosettacode.org/wiki/Bitmap/PPM_conversion_through_a_pipe | Bitmap/PPM conversion through a pipe | Using the data storage type defined on this page for raster images, delegate writing a JPEG file through a pipe using the output_ppm function defined on this other page.
There are various utilities that can be used for this task, for example: cjpeg (package "jpeg-progs" on Linux), ppmtojpeg (package "netpbm" on Linux), convert (from ImageMagick, multi-platform).
| #Wren | Wren | /* gcc -O3 -std=c11 -shared -o pipeconv.so -fPIC -I./include pipeconv.c */
#include <stdlib.h>
#include <string.h>
#include "dome.h"
static DOME_API_v0* core;
static WREN_API_v0* wren;
static const char* source = ""
"class PipeConv {\n"
"foreign static convert(from, to) \n"
"} \n";
void C_convert(WrenVM* vm) {
const char *from = wren->getSlotString(vm, 1);
const char *to = wren->getSlotString(vm, 2);
char command[strlen(from) + strlen(to) + 10];
strcpy(command, "convert ");
strcat(command, from);
strcat(command, " ");
strcat(command, to);
int res = system(command);
}
DOME_EXPORT DOME_Result PLUGIN_onInit(DOME_getAPIFunction DOME_getAPI, DOME_Context ctx) {
core = DOME_getAPI(API_DOME, DOME_API_VERSION);
wren = DOME_getAPI(API_WREN, WREN_API_VERSION);
core->registerModule(ctx, "pipeconv", source);
core->registerClass(ctx, "pipeconv", "PipeConv", NULL, NULL);
core->registerFn(ctx, "pipeconv", "static PipeConv.convert(_,_)", C_convert);
return DOME_RESULT_SUCCESS;
}
DOME_EXPORT DOME_Result PLUGIN_preUpdate(DOME_Context ctx) {
return DOME_RESULT_SUCCESS;
}
DOME_EXPORT DOME_Result PLUGIN_postUpdate(DOME_Context ctx) {
return DOME_RESULT_SUCCESS;
}
DOME_EXPORT DOME_Result PLUGIN_preDraw(DOME_Context ctx) {
return DOME_RESULT_SUCCESS;
}
DOME_EXPORT DOME_Result PLUGIN_postDraw(DOME_Context ctx) {
return DOME_RESULT_SUCCESS;
}
DOME_EXPORT DOME_Result PLUGIN_onShutdown(DOME_Context ctx) {
return DOME_RESULT_SUCCESS;
} |
http://rosettacode.org/wiki/Bulls_and_cows | Bulls and cows | Bulls and Cows
Task
Create a four digit random number from the digits 1 to 9, without duplication.
The program should:
ask for guesses to this number
reject guesses that are malformed
print the score for the guess
The score is computed as:
The player wins if the guess is the same as the randomly chosen number, and the program ends.
A score of one bull is accumulated for each digit in the guess that equals the corresponding digit in the randomly chosen initial number.
A score of one cow is accumulated for each digit in the guess that also appears in the randomly chosen number, but in the wrong position.
Related tasks
Bulls and cows/Player
Guess the number
Guess the number/With Feedback
Mastermind
| #Scala | Scala | import scala.util.Random
object BullCow {
def main(args: Array[String]): Unit = {
val number=chooseNumber
var guessed=false
var guesses=0
while(!guessed){
Console.print("Guess a 4-digit number with no duplicate digits: ")
val input=Console.readInt
val digits=input.toString.map(_.asDigit).toList
if(input>=1111 && input<=9999 && !hasDups(digits)){
guesses+=1
var bulls, cows=0
for(i <- 0 to 3)
if(number(i)==digits(i))
bulls+=1
else if(number.contains(digits(i)))
cows+=1
if(bulls==4)
guessed=true
else
println("%d Cows and %d Bulls.".format(cows, bulls))
}
}
println("You won after "+guesses+" guesses!");
}
def chooseNumber={
var digits=List[Int]()
while(digits.size<4){
val d=Random.nextInt(9)+1
if (!digits.contains(d))
digits=digits:+d
}
digits
}
def hasDups(input:List[Int])=input.size!=input.distinct.size
} |
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe | Bitmap/Read an image through a pipe | This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PPM format like a (natural) bridge between the foreign image format and our simple data storage.
| #Lua | Lua | function Bitmap:loadPPM(filename, fp)
if not fp then fp = io.open(filename, "rb") end
if not fp then return end
local head, width, height, depth, tail = fp:read("*line", "*number", "*number", "*number", "*line")
self.width, self.height = width, height
self:alloc()
for y = 1, self.height do
for x = 1, self.width do
self.pixels[y][x] = { string.byte(fp:read(1)), string.byte(fp:read(1)), string.byte(fp:read(1)) }
end
end
fp:close()
end |
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe | Bitmap/Read an image through a pipe | This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PPM format like a (natural) bridge between the foreign image format and our simple data storage.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Export["data/bitmapOutputTest.ppm",Import["data/bitmapOutputTest.jpg"]]; |
http://rosettacode.org/wiki/Bitmap/Read_an_image_through_a_pipe | Bitmap/Read an image through a pipe | This task is the opposite of the PPM conversion through a pipe. In this task, using a delegate tool (like cjpeg, one of the netpbm package, or convert of the ImageMagick package) we read an image file and load it into the data storage type defined here. We can also use the code from Read ppm file, so that we can use PPM format like a (natural) bridge between the foreign image format and our simple data storage.
| #Nim | Nim | import bitmap
import osproc
import ppm_read
import streams
# Launch Netpbm "jpegtopnm".
# Input is taken from "input.jpeg" and result sent to stdout.
let p = startProcess("jpegtopnm", args = ["input.jpeg"], options = {poUsePath})
let stream = FileStream(p.outputStream())
let image = stream.readPPM()
echo image.w, " ", image.h
p.close() |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.