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/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #SPL | SPL | x = #.array("a")
#.output("a -> ",x[1]," ",x[2])
x = [98,0]
#.output("98 0 -> ",#.str(x)) |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Standard_ML | Standard ML | print (Int.toString (ord #"a") ^ "\n"); (* prints "97" *)
print (Char.toString (chr 97) ^ "\n"); (* prints "a" *) |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Stata | Stata | : ascii("α")
1 2
+-------------+
1 | 206 177 |
+-------------+ |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Swift | Swift | let c1: UnicodeScalar = "a"
println(c1.value) // prints "97"
let c2: UnicodeScalar = "π"
println(c2.value) // prints "960" |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Tailspin | Tailspin |
'abc' -> $::asCodePoints -> !OUT::write
'$#10;' -> !OUT::write
'$#97;' -> !OUT::write
|
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Tcl | Tcl | # ASCII
puts [scan "a" %c] ;# ==> 97
puts [format %c 97] ;# ==> a
# Unicode is the same
puts [scan "π" %c] ;# ==> 960
puts [format %c 960] ;# ==> π |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #TI-83_BASIC | TI-83 BASIC | "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789→Str1
Disp inString(Str1,"A
Input "CODE? ",A
Disp sub(Str1,A,1 |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #TI-89_BASIC | TI-89 BASIC | Prgm
Local k, s
ClrIO
Loop
Disp "Press a key, or ON to exit."
getKey() © clear buffer
0 → k : While k = 0 : getKey() → k : EndWhile
ClrIO
If k ≥ 256 Then
Disp "Not a character."
Disp "Code: " & string(k)
Else
char(k) → s ©
© char() and ord() are inverses. ©
Disp "Character: " & s ©
Disp "Code: " & string(ord(s)) ©
EndIf
EndLoop
EndPrgm |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Trith | Trith | "a" ord print
97 chr print |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #TUSCRIPT | TUSCRIPT | $$ MODE TUSCRIPT
SET character ="a", code=DECODE (character,byte)
PRINT character,"=",code |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #uBasic.2F4tH | uBasic/4tH | z = ORD("a") : PRINT CHR(z) ' Prints "a" |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Ursa | Ursa | # outputs the character value for 'a'
out (ord "a") endl console
# outputs the character 'a' given its value
out (chr 97) endl console |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Ursala | Ursala | #import std
#import nat
chr = -: num characters
asc = -:@rlXS num characters
#cast %cnX
test = (chr97,asc`a) |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #VBA | VBA | Debug.Print Chr(97) 'Prints a
Debug.Print [Code("a")] ' Prints 97 |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #VBScript | VBScript |
'prints a
WScript.StdOut.WriteLine Chr(97)
'prints 97
WScript.StdOut.WriteLine Asc("a")
|
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Vim_Script | Vim Script | "encoding is set to utf-8
echo char2nr("a")
"Prints 97
echo nr2char(97)
"Prints a |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Visual_Basic_.NET | Visual Basic .NET | Console.WriteLine(Chr(97)) 'Prints a
Console.WriteLine(Asc("a")) 'Prints 97 |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Vlang | Vlang | fn main() {
println('a'[0]) // prints "97"
println('π'[0]) // prints "207"
s := 'aπ'
println('string cast to bytes: ${s.bytes()}')
for c in s {
print('0x${c:x} ')
}
} |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Wren | Wren | var cps = []
for (c in ["a", "π", "字", "🐘"]) {
var cp = c.codePoints[0]
cps.add(cp)
System.print("%(c) = %(cp)")
}
System.print()
for (i in cps) {
var c = String.fromCodePoint(i)
System.print("%(i) = %(c)")
} |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #XLISP | XLISP | [1] (INTEGER->CHAR 97)
#\a
[2] (CHAR->INTEGER #\a)
97 |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #XPL0 | XPL0 | IntOut(0, ^a); \(Integer Out) displays "97" on the console (device 0)
ChOut(0, 97); \(Character Out) displays "a" on the console (device 0) |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Z80_Assembly | Z80 Assembly | LD A,'a'
call &BB5a |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Zig | Zig | const std = @import("std");
const debug = std.debug;
const unicode = std.unicode;
test "character codes" {
debug.warn("\n", .{});
// Zig's string is just an array of bytes (u8).
const message = "ABCabc";
for (message) |val| {
debug.warn(" '{c}' code: {} [hexa: 0x{x}]\n", .{ val, val, val });
}
}
test "character (uni)codes" {
debug.warn("\n", .{});
const message = "あいうえお";
const utf8_view = unicode.Utf8View.initUnchecked(message);
var iter = utf8_view.iterator();
while (iter.nextCodepoint()) |val| {
var array: [4]u8 = undefined;
var slice = array[0..try unicode.utf8Encode(val, &array)];
debug.warn(" '{}' code: {} [hexa: U+{x}]\n", .{ slice, val, val });
}
} |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #zkl | zkl | "a".toAsc() //-->97
(97).toChar() //-->"a" |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Zoea | Zoea |
program: character_codes
input: a
output: 97
|
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #Zoea_Visual | Zoea Visual | 10 PRINT CHR$ 97: REM prints a
20 PRINT CODE "a": REM prints 97 |
http://rosettacode.org/wiki/Character_codes | Character codes |
Task
Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses).
Example
The character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode).
Conversely, given a code, print out the corresponding character.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 PRINT CHR$ 97: REM prints a
20 PRINT CODE "a": REM prints 97 |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #11l | 11l | F correct_case(string)
R string.filter(s -> s.is_alpha()).map(s -> s.uppercase()).join(‘’)
F permu(String alp; num)
R alp[num..]‘’alp[0 .< num]
F rotate_wheels(lalph, ralph, key)
V newin = ralph.index(key)
R (permu(lalph, newin), permu(ralph, newin))
F scramble_wheels(String =lalph, String =ralph)
lalph = lalph[0]‘’lalph[2.<14]‘’lalph[1]‘’lalph[14..]
ralph = ralph[1.<3]‘’ralph[4.<15]‘’ralph[3]‘’ralph[15..]‘’ralph[0]
R (lalph, ralph)
F do_chao(=msg, =lalpha, =ralpha, en = 1B, show = 0B)
msg = correct_case(msg)
V out = ‘’
I show
print(‘=’ * 54)
print((10 * ‘ ’)‘left:’(21 * ‘ ’)‘right: ’)
print(‘=’ * 54)
print(lalpha‘ ’ralpha" \n")
L(l) msg
I en
(lalpha, ralpha) = rotate_wheels(lalpha, ralpha, l)
out ‘’= lalpha[0]
E
(ralpha, lalpha) = rotate_wheels(ralpha, lalpha, l)
out ‘’= ralpha[0]
(lalpha, ralpha) = scramble_wheels(lalpha, ralpha)
I show
print(lalpha‘ ’ralpha)
R out
V lalpha = ‘HXUCZVAMDSLKPEFJRIGTWOBNYQ’
V ralpha = ‘PTLNBQDEOYSFAVZKGJRIHWXUMC’
V msg = ‘WELLDONEISBETTERTHANWELLSAID’
print(‘L: ’lalpha)
print(‘R: ’ralpha)
print(‘I: ’msg)
V o = do_chao(msg, lalpha, ralpha, 1B, 0B)
print(‘O: ’o)
print(‘D: ’do_chao(o, lalpha, ralpha, 0B, 0B))
print()
do_chao(msg, lalpha, ralpha, 1B, 1B) |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #Ada | Ada |
with Ada.Text_IO; use Ada.Text_IO;
procedure chao_slices is
type iMode is (Encrypt, Decrypt);
L_Alphabet : String := "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
R_Alphabet : String := "PTLNBQDEOYSFAVZKGJRIHWXUMC";
plaintext : String := "WELLDONEISBETTERTHANWELLSAID";
ciphertext : String (1 .. plaintext'length);
plaintext2 : String (1 .. plaintext'length);
offset : Natural;
function IndexOf (Source : String; Value : Character) return Positive is
Result : Positive;
begin
for I in Source'Range loop
if Source (I) = Value then
Result := I;
exit;
end if;
end loop;
return Result;
end IndexOf;
function Exec
(Text : String; mode : iMode; showsteps : Boolean := False) return String
is
etext : String (Text'First .. Text'Last);
temp : String (1 .. 26);
index : Positive;
store : Character;
left : String := L_Alphabet;
right : String := R_Alphabet;
begin
for I in Text'Range loop
if showsteps then
Put_Line (left & " " & right);
end if;
if mode = Encrypt then
index := IndexOf (Source => right, Value => Text (I));
etext (I) := left (index);
else
index := IndexOf (Source => left, Value => Text (I));
etext (I) := right (index);
end if;
exit when I = Text'Last;
-- permute left
-- The array value permutations are performed using array slices
-- rather than explicit loops
if index > 1 then
offset := 26 - index;
temp (1 .. offset + 1) := left (index .. index + offset);
temp (offset + 2 .. 26) := left (1 .. index - 1);
store := temp (2);
temp (2 .. 13) := temp (3 .. 14);
temp (14) := store;
left := temp;
-- permute right
-- The array value permutations are performed using array slices
-- rather than explicit loops
temp (1 .. offset + 1) := right (index .. index + offset);
temp (offset + 2 .. 26) := right (1 .. index - 1);
store := temp (1);
temp (1 .. 25) := temp (2 .. 26);
temp (26) := store;
store := temp (3);
temp (3 .. 13) := temp (4 .. 14);
temp (14) := store;
right := temp;
end if;
end loop;
return etext;
end Exec;
begin
Put_Line ("The original text is : " & plaintext);
New_Line;
Put_Line
("The left and right alphabets after each permutation during encryption are:");
New_Line;
ciphertext := Exec (plaintext, Encrypt, True);
New_Line;
Put_Line ("The ciphertext is : " & ciphertext);
plaintext2 := Exec (ciphertext, Decrypt);
New_Line;
Put_Line ("The recovered plaintext is : " & plaintext2);
end chao_slices;
|
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #11l | 11l | V n = 15
V t = [0] * (n + 2)
t[1] = 1
L(i) 1 .. n
L(j) (i .< 1).step(-1)
t[j] += t[j - 1]
t[i + 1] = t[i]
L(j) (i + 1 .< 1).step(-1)
t[j] += t[j - 1]
print(t[i + 1] - t[i], end' ‘ ’) |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #AppleScript | AppleScript | -- Chaocipher algorithm by J.F.Byrne 1918.
on chaocipher(input, |key|, mode)
-- input: text to be enciphered or deciphered.
-- |key|: script object or record with leftAlpha and rightAlpha properties, each of whose values is a shuffled alphabet text.
-- mode: the text "encipher" or "decipher".
script o
property inputChars : input's characters
property leftAlpha : |key|'s leftAlpha's characters
property rightAlpha : |key|'s rightAlpha's characters
property inAlpha : leftAlpha
property outAlpha : rightAlpha
property output : {}
end script
set alphaLen to (count o's leftAlpha)
if ((count o's rightAlpha) ≠ alphaLen) then error
if (mode is "encipher") then
set {o's inAlpha, o's outAlpha} to {o's rightAlpha, o's leftAlpha}
else if (mode is not "decipher") then
error
end if
set zenith to 1
set nadir to alphaLen div 2 + 1
repeat with char in o's inputChars
set char to char's contents
set found to false
repeat with i from 1 to alphaLen
if (o's inAlpha's item i = char) then
set end of o's output to o's outAlpha's item i
set found to true
exit repeat
end if
end repeat
if (found) then
rotate(o's leftAlpha, zenith, alphaLen, -(i - zenith))
rotate(o's leftAlpha, zenith + 1, nadir, -1)
rotate(o's rightAlpha, zenith, alphaLen, -i)
rotate(o's rightAlpha, zenith + 2, nadir, -1)
end if
end repeat
return join(o's output, "")
end chaocipher
on rotate(theList, l, r, amount)
set listLength to (count theList)
if (listLength < 2) then return
if (l < 0) then set l to listLength + l + 1
if (r < 0) then set r to listLength + r + 1
if (l > r) then set {l, r} to {r, l}
script o
property lst : theList
property storage : missing value
end script
set rangeLength to r - l + 1
set amount to (rangeLength + rangeLength - amount) mod rangeLength
if (amount is 0) then return
set o's storage to o's lst's items l thru (l + amount - 1)
repeat with i from (l + amount) to r
set o's lst's item (i - amount) to o's lst's item i
end repeat
set j to r - amount
repeat with i from 1 to amount
set o's lst's item (j + i) to o's storage's item i
end repeat
end rotate
on join(lst, delim)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set txt to lst as text
set AppleScript's text item delimiters to astid
return txt
end join
-- Return a script object containing a couple of randomised alphabets to use as a choacipher key.
on makeKey()
set lAlpha to "ABCDEFGHIJKLMNOPQRSTUVWXYZ"'s characters
copy lAlpha to rAlpha
script |key|
property leftAlpha : join(shuffle(lAlpha, 1, -1), "")
property rightAlpha : join(shuffle(rAlpha, 1, -1), "")
end script
return |key|
end makeKey
-- Fisher-Yates (aka Durstenfeld, aka Knuth) shuffle.
on shuffle(theList, l, r)
set listLength to (count theList)
if (listLength < 2) then return array
if (l < 0) then set l to listLength + l + 1
if (r < 0) then set r to listLength + r + 1
if (l > r) then set {l, r} to {r, l}
script o
property lst : theList
end script
repeat with i from l to (r - 1)
set j to (random number from i to r)
set v to o's lst's item i
set o's lst's item i to o's lst's item j
set o's lst's item j to v
end repeat
return theList
end shuffle
-- Demo using the two-alphabet key from the Rubin paper and another generated at random.
-- Decription must be with the key that was used for the encription.
on demo(originalText)
set key1 to {leftAlpha:"HXUCZVAMDSLKPEFJRIGTWOBNYQ", rightAlpha:"PTLNBQDEOYSFAVZKGJRIHWXUMC"}
set key2 to makeKey()
set enciphered to chaocipher(originalText, key1, "encipher")
set doubleEnciphered to chaocipher(enciphered, key2, "encipher")
set deDoubleEnciphered to chaocipher(doubleEnciphered, key2, "decipher")
set deciphered to chaocipher(deDoubleEnciphered, key1, "decipher")
return join({"Original text = " & originalText, ¬
"Enciphered = " & enciphered, "Double enciphered = " & doubleEnciphered, ¬
"De-double enciphered = " & deDoubleEnciphered, "Deciphered = " & deciphered}, linefeed)
end demo
demo("WELLDONEISBETTERTHANWELLSAID") |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #360_Assembly | 360 Assembly | CATALAN CSECT
USING CATALAN,R13,R12
SAVEAREA B STM-SAVEAREA(R15)
DC 17F'0'
DC CL8'CATALAN'
STM STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15
LA R12,4095(R13)
LA R12,1(R12)
* ---- CODE
LA R0,1
ST R0,T t(1)=1
LA R4,0 ix:i=1
LA R6,1 by 1
LH R7,N to n
LOOPI BXH R4,R6,ENDLOOPI loop i
LR R5,R4 ix:j=i+1
LA R5,2(R5) i+2
LA R8,0
BCTR R8,0 by -1
LA R9,1 to 2
LOOP1J BXLE R5,R8,ENLOOP1J loop j
LR R10,R5 j
BCTR R10,0
SLA R10,2
L R2,T(R10) r2=t(j)
LR R1,R10 j
SH R1,=H'4'
L R3,T(R1) r3=t(j-1)
AR R2,R3 r2=r2+r3
ST R2,T(R10) t(j)=t(j)+t(j-1)
B LOOP1J
ENLOOP1J EQU *
LR R1,R4 i
BCTR R1,0
SLA R1,2
L R3,T(R1) t(i)
LA R1,4(R1)
ST R3,T(R1) t(i+1)
LR R5,R4 ix:j=i+2
LA R5,3(R5) i+3
LA R8,0
BCTR R8,0 by -1
LA R9,1 to 2
LOOP2J BXLE R5,R8,ENLOOP2J loop j
LR R10,R5 j
BCTR R10,0
SLA R10,2
L R2,T(R10) r2=t(j)
LR R1,R10 j
SH R1,=H'4'
L R3,T(R1) r3=t(j-1)
AR R2,R3 r2=r2+r3
ST R2,T(R10) t(j)=t(j)+t(j-1)
B LOOP2J
ENLOOP2J EQU *
LR R1,R4 i
BCTR R1,0
SLA R1,2
L R2,T(R1) t(i)
LA R1,4(R1)
L R3,T(R1) t(i+1)
SR R3,R2
CVD R3,P
UNPK Z,P
MVC C,Z
OI C+L'C-1,X'F0'
MVC WTOBUF(8),C+8
WTO MF=(E,WTOMSG)
B LOOPI
ENDLOOPI EQU *
* ---- END CODE
CNOP 0,4
L R13,4(0,R13)
LM R14,R12,12(R13)
XR R15,R15
BR R14
* ---- DATA
N DC H'15'
T DC 17F'0'
P DS PL8
Z DS ZL16
C DS CL16
WTOMSG DS 0F
DC H'80'
DC H'0'
WTOBUF DC CL80' '
YREGS
END |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Ki
DEFINE PTR="CARD"
DEFINE REALSIZE="6"
PTR FUNC GetItemAddr(PTR buf BYTE i)
RETURN (buf+REALSIZE*i)
PROC Main()
DEFINE COUNT="15"
BYTE ARRAY buf(102) ;(COUNT+2)*REALSIZE
REAL POINTER r1,r2
REAL c
BYTE i,j
Put(125) PutE() ;clear the screen
r1=GetItemAddr(buf,1)
IntToReal(1,r1)
FOR i=1 TO COUNT
DO
j=i+1
WHILE j>=2
DO
r1=GetItemAddr(buf,j)
r2=GetItemAddr(buf,j-1)
RealAdd(r1,r2,r1) ;t(j)==+t(j-1)
j==-1
OD
r1=GetItemAddr(buf,i)
r2=GetItemAddr(buf,i+1)
RealAssign(r1,r2) ;t(i+1)=t(i)
j=i+2
WHILE j>=2
DO
r1=GetItemAddr(buf,j)
r2=GetItemAddr(buf,j-1)
RealAdd(r1,r2,r1) ;t(j)==+t(j-1)
j==-1
OD
r1=GetItemAddr(buf,i)
r2=GetItemAddr(buf,i+1)
RealSub(r2,r1,c) ;c=t(i+1)-t(i)
PrintF("C(%B)=",i) PrintRE(c)
OD
RETURN |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #Arc | Arc | (= lshift '((0 1) (2 14) (1 2) (14 26)))
(= rshift '((1 3) (4 15) (3 4) (15 26) (0 1)))
(= rot (fn (alpha shift)
(let shift (mod shift 26)
(string (cut alpha shift) (cut alpha 0 shift)))))
(= scramble-wheel (fn (alpha moves)
(= oput '())
(up i 0 (- (len moves) 1)
(push (cut alpha ((moves i) 0) ((moves i) 1)) oput))
(= oput (string (rev oput)))))
(= chaocipher (fn (left right msg (o crypted) (o dec?))
(unless crypted
(prn "Encoding " msg " with chaocipher")
(prn left " " right))
(when dec? (swap left right))
(= offset ((positions (msg 0) right) 0))
(= left (rot left offset))
(= right (rot right offset))
(push (cut left 0 1) crypted)
(when dec? (swap left right))
(prn (scramble-wheel left lshift)
" " (scramble-wheel right rshift))
(if (> (len msg) 1)
(chaocipher (scramble-wheel left lshift)
(scramble-wheel right rshift)
(cut msg 1) crypted dec?)
(string (rev crypted)))))
(chaocipher "HXUCZVAMDSLKPEFJRIGTWOBNYQ" "PTLNBQDEOYSFAVZKGJRIHWXUMC"
"WELLDONEISBETTERTHANWELLSAID")
(chaocipher "HXUCZVAMDSLKPEFJRIGTWOBNYQ" "PTLNBQDEOYSFAVZKGJRIHWXUMC"
"OAHQHCNYNXTSZJRRHJBYHQKSOUJY" nil 1)
|
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #Ada | Ada | with Ada.Text_IO, Pascal;
procedure Catalan is
Last: Positive := 15;
Row: Pascal.Row := Pascal.First_Row(2*Last+1);
begin
for I in 1 .. Last loop
Row := Pascal.Next_Row(Row);
Row := Pascal.Next_Row(Row);
Ada.Text_IO.Put(Integer'Image(Row(I+1)-Row(I+2)));
end loop;
end Catalan; |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #ALGOL_68 | ALGOL 68 | INT n = 15;
[ 0 : n + 1 ]INT t;
t[0] := 0;
t[1] := 1;
FOR i TO n DO
FOR j FROM i BY -1 TO 2 DO t[j] := t[j] + t[j-1] OD;
t[i+1] := t[i];
FOR j FROM i+1 BY -1 TO 2 DO t[j] := t[j] + t[j-1] OD;
print( ( whole( t[i+1] - t[i], 0 ), " " ) )
OD |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #11l | 11l | V dog = ‘Benjamin’
V Dog = ‘Samba’
V DOG = ‘Bernie’
print(‘The three dogs are named ’dog‘, ’Dog‘ and ’DOG‘.’) |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #AutoHotkey | AutoHotkey | LeftW := "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
RghtW := "PTLNBQDEOYSFAVZKGJRIHWXUMC"
PlainText := "WELLDONEISBETTERTHANWELLSAID"
CipherText := Chao_Cipher(PlainText, LeftW, RghtW) ; "OAHQHCNYNXTSZJRRHJBYHQKSOUJY"
DecipherText:= Chao_Decipher(CipherText, LeftW, RghtW) ; "WELLDONEISBETTERTHANWELLSAID"
MsgBox % Result := "Original text:`t" PlainText "`nCipher text:`t" CipherText "`nDecipher text:`t" DecipherText
return
;-------------------------------------------
Chao_Cipher(PT, LeftW, RghtW){
oRght:=StrSplit(RghtW), oLeft:=StrSplit(LeftW)
for i, p in StrSplit(PT){
result .= (c := Key2Val(oRght, oLeft, p))
oLeft:=Permute(oLeft, c, 1)
oRght:=Permute(oRght, p)
}
return result
}
;-------------------------------------------
Chao_Decipher(CT, LeftW, RghtW){
oRght:=StrSplit(RghtW), oLeft:=StrSplit(LeftW)
for i, c in StrSplit(CT){
result .= (p := Key2Val(oLeft, oRght, c))
oLeft:=Permute(oLeft, c, 1)
oRght:=Permute(oRght, p)
}
return result
}
;-------------------------------------------
Key2Val(Key, Val, char){
for i, ch in Key
if (ch = char)
return Val[i]
}
;-------------------------------------------
Permute(Arr, ch, dt:=0){
for i, c in Arr
if (c=ch)
break
loop % i-dt
Arr.Push(Arr.RemoveAt(1)) ; shift left
ch := Arr[3-dt] ; save 2nd/3rd chr
loop % 11+dt
Arr[A_Index+2-dt]:=Arr[A_Index+3-dt] ; shift pos 3/4-14 left
Arr[14] := ch ; place 2nd/3rd chr in pos 14
return Arr
} |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #ALGOL_W | ALGOL W | begin
% print the first 15 Catalan numbers from Pascal's triangle %
integer n;
n := 15;
begin
integer array pascalLine ( 1 :: n + 1 );
% the Catalan numbers are the differences between the middle and middle - 1 numbers of the odd %
% lines of Pascal's triangle (lines with 3 or more numbers) %
% note - we only need to calculate the left side of the triangle %
pascalLine( 1 ) := 1;
for c := 2 until n + 1 do begin
% even line %
for i := c - 1 step -1 until 2 do pascalLine( i ) := pascalLine( i - 1 ) + pascalLine( i );
pascalLine( c ) := pascalLine( c - 1 );
% odd line %
for i := c step -1 until 2 do pascalLine( i ) := pascalLine( i - 1 ) + pascalLine( i );
writeon( i_w := 1, s_w := 0, " ", pascalLine( c ) - pascalLine( c - 1 ) )
end for_c
end
end. |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #APL | APL |
⍝ Based heavily on the J solution
CATALAN←{¯1↓↑-/1 ¯1↓¨(⊂⎕IO+0 0)⍉¨0 2⌽¨⊂(⎕IO-⍨⍳N){+\⍣⍺⊢⍵}⍤0 1⊢1⍴⍨N←⍵+2}
|
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Action.21 | Action! | PROC Main()
CHAR ARRAY dog="Bernie"
PrintF("There is just one dog named %S.",dog)
RETURN |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Ada | Ada | with Ada.Text_IO;
procedure Dogs is
Dog : String := "Bernie";
begin
Ada.Text_IO.Put_Line ("There is just one dog named " & DOG);
end Dogs; |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #C | C | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
typedef int bool;
typedef enum { ENCRYPT, DECRYPT } cmode;
const char *l_alphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
const char *r_alphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC";
void chao(const char *in, char *out, cmode mode, bool show_steps) {
int i, j, index;
char store;
size_t len = strlen(in);
char left[27], right[27], temp[27];
strcpy(left, l_alphabet);
strcpy(right, r_alphabet);
temp[26] = '\0';
for (i = 0; i < len; ++i ) {
if (show_steps) printf("%s %s\n", left, right);
if (mode == ENCRYPT) {
index = strchr(right, in[i]) - right;
out[i] = left[index];
}
else {
index = strchr(left, in[i]) - left;
out[i] = right[index];
}
if (i == len - 1) break;
/* permute left */
for (j = index; j < 26; ++j) temp[j - index] = left[j];
for (j = 0; j < index; ++j) temp[26 - index + j] = left[j];
store = temp[1];
for (j = 2; j < 14; ++j) temp[j - 1] = temp[j];
temp[13] = store;
strcpy(left, temp);
/* permute right */
for (j = index; j < 26; ++j) temp[j - index] = right[j];
for (j = 0; j < index; ++j) temp[26 - index + j] = right[j];
store = temp[0];
for (j = 1; j < 26; ++j) temp[j - 1] = temp[j];
temp[25] = store;
store = temp[2];
for (j = 3; j < 14; ++j) temp[j - 1] = temp[j];
temp[13] = store;
strcpy(right, temp);
}
}
int main() {
const char *plain_text = "WELLDONEISBETTERTHANWELLSAID";
char *cipher_text = malloc(strlen(plain_text) + 1);
char *plain_text2 = malloc(strlen(plain_text) + 1);
printf("The original plaintext is : %s\n", plain_text);
printf("\nThe left and right alphabets after each permutation"
" during encryption are :\n\n");
chao(plain_text, cipher_text, ENCRYPT, TRUE);
printf("\nThe ciphertext is : %s\n", cipher_text);
chao(cipher_text, plain_text2, DECRYPT, FALSE);
printf("\nThe recovered plaintext is : %s\n", plain_text2);
free(cipher_text);
free(plain_text2);
return 0;
} |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #AutoHotkey | AutoHotkey | /* Generate Catalan Numbers
//
// smgs: 20th Feb, 2014
*/
Array := [], Array[2,1] := Array[2,2] := 1 ; Array inititated and 2nd row of pascal's triangle assigned
INI := 3 ; starts with calculating the 3rd row and as such the value
Loop, 31 ; every odd row is taken for calculating catalan number as such to obtain 15 we need 2n+1
{
if ( A_index > 2 )
{
Loop, % A_INDEX
{
old := ini-1, index := A_index, index_1 := A_index + 1
Array[ini, index_1] := Array[old, index] + Array[old, index_1]
Array[ini, 1] := Array[ini, ini] := 1
line .= Array[ini, A_index] " "
}
;~ MsgBox % line ; gives rows of pascal's triangle
; calculating every odd row starting from 1st so as to obtain catalan's numbers
if ( mod(ini,2) != 0)
{
StringSplit, res, line, %A_Space%
ans := res0//2, ans_1 := ans++
result := result . res%ans_1% - res%ans% " "
}
line :=
ini++
}
}
MsgBox % result |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Agena | Agena | scope
local dog := "Benjamin";
scope
local Dog := "Samba";
scope
local DOG := "Bernie";
if DOG <> Dog or DOG <> dog
then print( "The three dogs are named: " & dog & ", " & Dog & " and " & DOG )
else print( "There is just one dog named: " & DOG )
fi
epocs
epocs
epocs |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Aime | Aime | text dog, Dog, DOG;
dog = "Benjamin";
Dog = "Samba";
DOG = "Bernie";
o_form("The three dogs are named ~, ~ and ~.\n", dog, Dog, DOG); |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #C.23 | C# | using System;
namespace Chaocipher {
enum Mode {
ENCRYPT,
DECRYPT,
}
class Program {
const string L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
const string R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC";
static string Exec(string text, Mode mode, bool showSteps = false) {
char[] left = L_ALPHABET.ToCharArray();
char[] right = R_ALPHABET.ToCharArray();
char[] eText = new char[text.Length];
char[] temp = new char[26];
for (int i = 0; i < text.Length; ++i) {
if (showSteps) Console.WriteLine("{0} {1}", string.Join("", left), string.Join("", right));
int index = 0;
if (mode == Mode.ENCRYPT) {
index = Array.IndexOf(right, text[i]);
eText[i] = left[index];
} else {
index = Array.IndexOf(left, text[i]);
eText[i] = right[index];
}
if (i == text.Length - 1) break;
// permute left
for (int j = index; j < 26; ++j) temp[j - index] = left[j];
for (int j = 0; j < index; ++j) temp[26 - index + j] = left[j];
var store = temp[1];
for (int j = 2; j < 14; ++j) temp[j - 1] = temp[j];
temp[13] = store;
temp.CopyTo(left, 0);
// permute right
for (int j = index; j < 26; ++j) temp[j - index] = right[j];
for (int j = 0; j < index; ++j) temp[26 - index + j] = right[j];
store = temp[0];
for (int j = 1; j < 26; ++j) temp[j - 1] = temp[j];
temp[25] = store;
store = temp[2];
for (int j = 3; j < 14; ++j) temp[j - 1] = temp[j];
temp[13] = store;
temp.CopyTo(right, 0);
}
return new string(eText);
}
static void Main(string[] args) {
var plainText = "WELLDONEISBETTERTHANWELLSAID";
Console.WriteLine("The original plaintext is : {0}", plainText);
Console.WriteLine("\nThe left and right alphabets after each permutation during encryption are :\n");
var cipherText = Exec(plainText, Mode.ENCRYPT, true);
Console.WriteLine("\nThe ciphertext is : {0}", cipherText);
var plainText2 = Exec(cipherText, Mode.DECRYPT);
Console.WriteLine("\nThe recovered plaintext is : {0}", plainText2);
}
}
} |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #AWK | AWK |
# syntax: GAWK -f CATALAN_NUMBERS_PASCALS_TRIANGLE.AWK
# converted from C
BEGIN {
printf("1")
for (n=2; n<=15; n++) {
num = den = 1
for (k=2; k<=n; k++) {
num *= (n + k)
den *= k
catalan = num / den
}
printf(" %d",catalan)
}
printf("\n")
exit(0)
}
|
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #ALGOL_68 | ALGOL 68 | #!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
STRING dog = "Benjamin";
OP D = (INT og)STRING: "Samba";
OP DOG = (INT gy)STRING: "Bernie";
INT og=~, gy=~;
main:(
printf(($"The three dogs are named "g", "g" and "g"."l$, dog, Dog, DOGgy));
0
) |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #ALGOL_W | ALGOL W | begin
string(8) dog;
dog := "Benjamin";
begin
string(8) Dog;
Dog := "Samba";
begin
string(8) DOG;
DOG := "Bernie";
if DOG not = Dog
or DOG not = dog
then write( "The three dogs are named: ", dog, ", ", Dog, " and ", DOG )
else write( "There is just one dog named: ", DOG )
end
end
end. |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #C.2B.2B | C++ | #include <iostream>
enum class Mode {
ENCRYPT,
DECRYPT,
};
const std::string L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
const std::string R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC";
std::string exec(std::string text, Mode mode, bool showSteps = false) {
auto left = L_ALPHABET;
auto right = R_ALPHABET;
auto eText = new char[text.size() + 1];
auto temp = new char[27];
memset(eText, 0, text.size() + 1);
memset(temp, 0, 27);
for (size_t i = 0; i < text.size(); i++) {
if (showSteps) std::cout << left << ' ' << right << '\n';
size_t index;
if (mode == Mode::ENCRYPT) {
index = right.find(text[i]);
eText[i] = left[index];
} else {
index = left.find(text[i]);
eText[i] = right[index];
}
if (i == text.size() - 1) break;
// permute left
for (int j = index; j < 26; ++j) temp[j - index] = left[j];
for (int j = 0; j < index; ++j) temp[26 - index + j] = left[j];
auto store = temp[1];
for (int j = 2; j < 14; ++j) temp[j - 1] = temp[j];
temp[13] = store;
left = temp;
// permurte right
for (int j = index; j < 26; ++j) temp[j - index] = right[j];
for (int j = 0; j < index; ++j) temp[26 - index + j] = right[j];
store = temp[0];
for (int j = 1; j < 26; ++j) temp[j - 1] = temp[j];
temp[25] = store;
store = temp[2];
for (int j = 3; j < 14; ++j) temp[j - 1] = temp[j];
temp[13] = store;
right = temp;
}
return eText;
}
int main() {
auto plainText = "WELLDONEISBETTERTHANWELLSAID";
std::cout << "The original plaintext is : " << plainText << "\n\n";
std::cout << "The left and right alphabets after each permutation during encryption are :\n";
auto cipherText = exec(plainText, Mode::ENCRYPT, true);
std::cout << "\nThe ciphertext is : " << cipherText << '\n';
auto plainText2 = exec(cipherText, Mode::DECRYPT);
std::cout << "\nThe recovered plaintext is : " << plainText2 << '\n';
return 0;
} |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #Batch_File | Batch File | @echo off
setlocal ENABLEDELAYEDEXPANSION
set n=15
set /A nn=n+1
for /L %%i in (0,1,%nn%) do set t.%%i=0
set t.1=1
for /L %%i in (1,1,%n%) do (
set /A ip=%%i+1
for /L %%j in (%%i,-1,1) do (
set /A jm=%%j-1
set /A t.%%j=t.%%j+t.!jm!
)
set /A t.!ip!=t.%%i
for /L %%j in (!ip!,-1,1) do (
set /A jm=%%j-1
set /A t.%%j=t.%%j+t.!jm!
)
set /A ci=t.!ip!-t.%%i
echo !ci!
)
)
pause |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #APL | APL | DOG←'Benjamin'
Dog←'Samba'
dog←'Bernie'
'The three dogs are named ',DOG,', ',Dog,', and ',dog
The three dogs are named Benjamin, Samba, and Bernie |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Arturo | Arturo | dog: "Benjamin"
Dog: "Samba"
DOG: "Bernie"
dogs: @[dog Dog DOG]
print ["The" size dogs "dog(s) are named" join.with:", " dogs] |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #D | D | import std.stdio;
import std.string;
immutable L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
immutable R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC";
enum Mode {
ENCRYPT,
DECRYPT,
}
string exec(string text, Mode mode, bool showSteps = false) {
char[] left = L_ALPHABET.dup;
char[] right = R_ALPHABET.dup;
char[] eText;
eText.length = text.length;
char[26] temp;
foreach (i; 0..text.length) {
if (showSteps) writeln(left, ' ', right);
int index;
if (mode == Mode.ENCRYPT) {
index = right.indexOf(text[i]);
eText[i] = left[index];
} else {
index = left.indexOf(text[i]);
eText[i] = right[index];
}
if (i == text.length - 1) break;
// permute left
foreach (j; index..26) temp[j - index] = left[j];
foreach (j; 0..index) temp[26 - index + j] = left[j];
auto store = temp[1];
foreach (j; 2..14) temp[j - 1] = temp[j];
temp[13] = store;
left = temp.dup;
// permute right
foreach (j; index..26) temp[j - index] = right[j];
foreach (j; 0..index) temp[26 - index + j] = right[j];
store = temp[0];
foreach (j; 1..26) temp[j - 1] = temp[j];
temp[25] = store;
store = temp[2];
foreach (j; 3..14) temp[j - 1] = temp[j];
temp[13] = store;
right = temp.dup;
}
return eText.idup;
}
void main() {
auto plainText = "WELLDONEISBETTERTHANWELLSAID";
writeln("The original plaintext is : ", plainText);
writeln("\nThe left and right alphabets after each permutation during encryption are :\n");
auto cipherText = exec(plainText, Mode.ENCRYPT, true);
writeln("\nThe ciphertext is : ", cipherText);
auto plainText2 = exec(cipherText, Mode.DECRYPT);
writeln("\nThe recovered plaintext is : ", plainText2);
} |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #C | C |
//This code implements the print of 15 first Catalan's Numbers
//Formula used:
// __n__
// | | (n + k) / k n>0
// k=2
#include <stdio.h>
#include <stdlib.h>
//the number of Catalan's Numbers to be printed
const int N = 15;
int main()
{
//loop variables (in registers)
register int k, n;
//necessarily ull for reach big values
unsigned long long int num, den;
//the nmmber
int catalan;
//the first is not calculated for the formula
printf("1 ");
//iterating from 2 to 15
for (n=2; n<=N; ++n) {
//initializaing for products
num = den = 1;
//applying the formula
for (k=2; k<=n; ++k) {
num *= (n+k);
den *= k;
catalan = num /den;
}
//output
printf("%d ", catalan);
}
//the end
printf("\n");
return 0;
}
|
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #AutoHotkey | AutoHotkey | dog := "Benjamin"
Dog := "Samba"
DOG := "Bernie"
MsgBox There is just one dog named %dOG% |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #AWK | AWK | BEGIN {
dog = "Benjamin"
Dog = "Samba"
DOG = "Bernie"
printf "The three dogs are named %s, %s and %s.\n", dog, Dog, DOG
} |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #11l | 11l | print((1..3).reduce((x, y) -> x + y))
print((1..3).reduce(3, (x, y) -> x + y))
print([1, 1, 3].reduce((x, y) -> x + y))
print([1, 1, 3].reduce(2, (x, y) -> x + y)) |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #Delphi | Delphi |
program Chaocipher;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
TMode = (mcEncrypt, mcDecrypt);
const
lAlphabet = 'HXUCZVAMDSLKPEFJRIGTWOBNYQ';
rAlphabet = 'PTLNBQDEOYSFAVZKGJRIHWXUMC';
function Chao(text: AnsiString; Mode: TMode; showSteps: boolean): AnsiString;
begin
var len := Length(text);
var left: AnsiString := lAlphabet;
var right: AnsiString := rAlphabet;
var eText: AnsiString;
SetLength(eText, len);
var temp: AnsiString;
SetLength(temp, 26);
for var i := 0 to len - 1 do
begin
if showSteps then
writeln(left, ' ', right);
var index := 0;
if Mode = mcEncrypt then
begin
index := pos(text[i + 1], right) - 1;
eText[i + 1] := left[index + 1];
end
else
begin
index := pos(text[i + 1], left) - 1;
eText[i + 1] := right[index + 1];
end;
if i = len - 1 then
Break;
// premute left
for var j := index to 25 do
temp[j - index + 1] := left[j + 1];
for var j := 0 to index - 1 do
temp[27 - index + j] := left[j + 1];
var store := temp[2];
for var j := 2 to 13 do
temp[j] := temp[j + 1];
temp[14] := store;
left := temp;
// permute right
for var j := index to 25 do
temp[j - index + 1] := right[j + 1];
for var j := 0 to index - 1 do
temp[27 - index + j] := right[j + 1];
store := temp[0 + 1];
for var j := 1 to 25 do
temp[j] := temp[j + 1];
temp[26] := store;
store := temp[3];
for var j := 3 to 13 do
temp[j] := temp[j + 1];
temp[14] := store;
right := temp;
end;
Result := eText;
end;
begin
var plainText := 'WELLDONEISBETTERTHANWELLSAID';
writeln('The original plaintext is :', plainText);
write(#10'The left and right alphabets after each permutation ');
writeln('during encryption are :'#10);
var cipherText := Chao(plainText, mcEncrypt, true);
writeln(#10'The ciphertext is :', cipherText);
var plainText2 := Chao(cipherText, mcDecrypt, false);
writeln(#10'The recovered plaintext is : ', plainText2);
readln;
end. |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #C.23 | C# |
int n = 15;
List<int> t = new List<int>() { 0, 1 };
for (int i = 1; i <= n; i++)
{
for (var j = i; j > 1; j--) t[j] += t[j - 1];
t.Add(t[i]);
for (var j = i + 1; j > 1; j--) t[j] += t[j - 1];
Console.Write(((i == 1) ? "" : ", ") + (t[i + 1] - t[i]));
}
|
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #BASIC | BASIC | DOG$ = "Benjamin"
DOG$ = "Samba"
DOG$ = "Bernie"
PRINT "There is just one dog, named "; DOG$ |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #BASIC256 | BASIC256 | dog = "Benjamin"
Dog = "Samba"
DOG = "Bernie"
print "There is just one dog, named "; dog
end |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #6502_Assembly | 6502 Assembly | define catbuf $10
define catbuf_temp $12
ldx #0
ramloop:
txa
sta $00,x
inx
cpx #$10
bne ramloop
;load zero page addresses $00-$0f with values equal
;to that address
ldx #0 ;zero X
loop_cata:
lda $00,x ;load the zeroth element
clc
adc $01,x ;add the first to it.
inx
inx ;inx twice. Otherwise the same element
;would get added twice
sta catbuf_temp ;store in temp ram
lda catbuf
clc
adc catbuf_temp ;add to previously stored value
sta catbuf ;store in result
cpx #$10 ;is the range over?
bne loop_cata ;if not, loop again
ldx #$00
lda catbuf
sta $00,x
;store the sum in the zeroth entry of the range
inx
lda #$00
;now clear the rest of zeropage, leaving only the sum
clear_ram:
sta $00,x
inx
cpx #$ff
bne clear_ram |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #F.23 | F# |
// Implement Chaocipher. Nigel Galloway: July 13th., 2019
let pL n=function g when g=n->0 |g when g=(n+1)%26->13 |g->let x=(25+g-n)%26 in if x<13 then x else x+1
let pR n=function g when g=n->25 |g when g=(n+3)%26->13 |g when g=(n+1)%26->0 |g when g=(n+2)%26->1 |g->let x=(24+g-n)%26 in if x<13 then x else x+1
let encrypt lW rW txt=Array.scan(fun (lW,rW) t->let n=Array.findIndex(fun n->n=t) rW in ((Array.permute(pL n) lW,(Array.permute(pR n) rW))))(lW,rW) txt
|>Array.skip 1|>Array.map(fun(n,_)->n.[0])|>System.String
let decrypt lW rW txt=Array.scan(fun (_,lW,rW) t->let n=Array.findIndex(fun n->n=t) lW in ((Array.item n rW,Array.permute(pL n) lW,(Array.permute(pR n) rW))))('0',lW,rW) txt
|>Array.skip 1|>Array.map(fun(n,_,_)->n)|>System.String
|
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #C.2B.2B | C++ | // Generate Catalan Numbers
//
// Nigel Galloway: June 9th., 2012
//
#include <iostream>
int main() {
const int N = 15;
int t[N+2] = {0,1};
for(int i = 1; i<=N; i++){
for(int j = i; j>1; j--) t[j] = t[j] + t[j-1];
t[i+1] = t[i];
for(int j = i+1; j>1; j--) t[j] = t[j] + t[j-1];
std::cout << t[i+1] - t[i] << " ";
}
return 0;
} |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Batch_File | Batch File |
@echo off
set dog=Benjamin
set Dog=Samba
set DOG=Bernie
echo There is just one dog named %dog%.
pause>nul
|
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #BBC_BASIC | BBC BASIC | dog$ = "Benjamin"
Dog$ = "Samba"
DOG$ = "Bernie"
PRINT "The three dogs are " dog$ ", " Dog$ " and " DOG$ "." |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #ABAP | ABAP |
report z_catamorphism.
data(numbers) = value int4_table( ( 1 ) ( 2 ) ( 3 ) ( 4 ) ( 5 ) ).
write: |numbers = { reduce string(
init output = `[`
index = 1
for number in numbers
next output = cond string(
when index eq lines( numbers )
then |{ output }, { number } ]|
when index > 1
then |{ output }, { number }|
else |{ output } { number }| )
index = index + 1 ) }|, /.
write: |sum(numbers) = { reduce int4(
init result = 0
for number in numbers
next result = result + number ) }|, /.
write: |product(numbers) = { reduce int4(
init result = 1
for number in numbers
next result = result * number ) }|, /.
data(strings) = value stringtab( ( `reduce` ) ( `in` ) ( `ABAP` ) ).
write: |strings = { reduce string(
init output = `[`
index = 1
for string in strings
next output = cond string(
when index eq lines( strings )
then |{ output }, { string } ]|
when index > 1
then |{ output }, { string }|
else |{ output } { string }| )
index = index + 1 ) }|, /.
write: |concatenation(strings) = { reduce string(
init text = ``
for string in strings
next text = |{ text } { string }| ) }|, /.
|
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #Factor | Factor | USING: arrays combinators fry io kernel locals math namespaces
prettyprint sequences sequences.extras strings ;
IN: rosetta-code.chaocipher
CONSTANT: zenith 0
CONSTANT: nadir 13
SYMBOLS: l-alphabet r-alphabet last-index ;
: init-alphabets ( -- )
"HXUCZVAMDSLKPEFJRIGTWOBNYQ" l-alphabet
"PTLNBQDEOYSFAVZKGJRIHWXUMC" r-alphabet [ set ] 2bi@ ;
: zero-alphabet ( seq -- seq' )
last-index get rotate ;
: 3append ( a b c d -- abcd )
append append append ;
:: permute-l-alphabet ( -- )
l-alphabet get zero-alphabet dup
zenith 1 + swap nth :> extracted-char
{
[ 1 head ]
[ nadir 1 + head 2 tail ]
[ drop extracted-char 1string ]
[ nadir 1 + tail ]
} cleave
3append l-alphabet set ;
:: permute-r-alphabet ( -- )
r-alphabet get zero-alphabet
1 rotate dup
zenith 2 + swap nth :> extracted-char
{
[ 2 head ]
[ nadir 1 + head 3 tail ]
[ drop extracted-char 1string ]
[ nadir 1 + tail ]
} cleave
3append r-alphabet set ;
: encipher-char ( char alpha1 alpha2 -- char' )
'[ _ get index dup last-index set _ get nth ] call ;
: encipher ( str quot -- str' )
[ permute-l-alphabet permute-r-alphabet ] compose map
init-alphabets ; inline
: encrypt ( str -- str' )
[ r-alphabet l-alphabet encipher-char ] encipher ;
: decrypt ( str -- str' )
[ l-alphabet r-alphabet encipher-char ] encipher ;
: main ( -- )
init-alphabets
"WELLDONEISBETTERTHANWELLSAID" encrypt dup decrypt
[ print ] bi@ ;
MAIN: main |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #Common_Lisp | Common Lisp | (defun catalan (n)
"Return the n-th Catalan number"
(if (<= n 1) 1
(let ((result 2))
(dotimes (k (- n 2) result)
(setq result (* result (/ (+ n k 2) (+ k 2)))) ))))
(dotimes (n 15)
(print (catalan (1+ n))) ) |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #bc | bc | obase = 16
ibase = 16
/*
* Store the hexadecimal number 'BE27A312'
* in the variable 'd'.
*/
d = BE27A312
"There is just one dog named "; d
quit |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #Ada | Ada | with Ada.Text_IO;
procedure Catamorphism is
type Fun is access function (Left, Right: Natural) return Natural;
type Arr is array(Natural range <>) of Natural;
function Fold_Left (F: Fun; A: Arr) return Natural is
Result: Natural := A(A'First);
begin
for I in A'First+1 .. A'Last loop
Result := F(Result, A(I));
end loop;
return Result;
end Fold_Left;
function Max (L, R: Natural) return Natural is (if L > R then L else R);
function Min (L, R: Natural) return Natural is (if L < R then L else R);
function Add (Left, Right: Natural) return Natural is (Left + Right);
function Mul (Left, Right: Natural) return Natural is (Left * Right);
package NIO is new Ada.Text_IO.Integer_IO(Natural);
begin
NIO.Put(Fold_Left(Min'Access, (1,2,3,4)), Width => 3);
NIO.Put(Fold_Left(Max'Access, (1,2,3,4)), Width => 3);
NIO.Put(Fold_Left(Add'Access, (1,2,3,4)), Width => 3);
NIO.Put(Fold_Left(Mul'Access, (1,2,3,4)), Width => 3);
end Catamorphism; |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import(
"fmt"
"strings"
"unicode/utf8"
)
type Mode int
const(
Encrypt Mode = iota
Decrypt
)
const(
lAlphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
rAlphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC"
)
func Chao(text string, mode Mode, showSteps bool) string {
len := len(text)
if utf8.RuneCountInString(text) != len {
fmt.Println("Text contains non-ASCII characters")
return ""
}
left := lAlphabet
right := rAlphabet
eText := make([]byte, len)
temp := make([]byte, 26)
for i := 0; i < len; i++ {
if showSteps {
fmt.Println(left, " ", right)
}
var index int
if mode == Encrypt {
index = strings.IndexByte(right, text[i])
eText[i] = left[index]
} else {
index = strings.IndexByte(left, text[i])
eText[i] = right[index]
}
if i == len - 1 {
break
}
// permute left
for j := index; j < 26; j++ {
temp[j - index] = left[j]
}
for j := 0; j < index; j++ {
temp[26 - index + j] = left[j]
}
store := temp[1]
for j := 2; j < 14; j++ {
temp[j - 1] = temp[j]
}
temp[13] = store
left = string(temp[:])
// permute right
for j := index; j < 26; j++ {
temp[j - index] = right[j]
}
for j := 0; j < index; j++ {
temp[26 - index + j] = right[j]
}
store = temp[0]
for j := 1; j < 26; j++ {
temp[j - 1] = temp[j]
}
temp[25] = store
store = temp[2]
for j := 3; j < 14; j++ {
temp[j - 1] = temp[j]
}
temp[13] = store
right = string(temp[:])
}
return string(eText[:])
}
func main() {
plainText := "WELLDONEISBETTERTHANWELLSAID"
fmt.Println("The original plaintext is :", plainText)
fmt.Print("\nThe left and right alphabets after each permutation ")
fmt.Println("during encryption are :\n")
cipherText := Chao(plainText, Encrypt, true)
fmt.Println("\nThe ciphertext is :", cipherText)
plainText2 := Chao(cipherText, Decrypt, false)
fmt.Println("\nThe recovered plaintext is :", plainText2)
} |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #D | D | void main() {
import std.stdio;
enum uint N = 15;
uint[N + 2] t;
t[1] = 1;
foreach (immutable i; 1 .. N + 1) {
foreach_reverse (immutable j; 2 .. i + 1)
t[j] += t[j - 1];
t[i + 1] = t[i];
foreach_reverse (immutable j; 2 .. i + 2)
t[j] += t[j - 1];
write(t[i + 1] - t[i], ' ');
}
} |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Bracmat | Bracmat | ( Benjamin:?dog
& Samba:?Dog
& Bernie:?DOG
& out$("There are three dogs:" !dog !Dog and !DOG)
); |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Brlcad | Brlcad |
opendb dogs.g y # Create a database to hold our dogs
units ft # The dogs are measured in feet
in dog.s sph 0 0 0 1 # Benjie is a little Scottie dog
in Dog.s sph 4 0 0 3 # Samba is a Labrador
in DOG.s sph 13 0 0 5 # Bernie is massive. He is a New Foundland
echo The three dogs are named Benjamin, Samba and Bernie |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #Aime | Aime | integer s;
s = 0;
list(1, 2, 3, 4, 5, 6, 7, 8, 9).ucall(add_i, 1, s);
o_(s, "\n"); |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #Go | Go | package main
import(
"fmt"
"strings"
"unicode/utf8"
)
type Mode int
const(
Encrypt Mode = iota
Decrypt
)
const(
lAlphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
rAlphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC"
)
func Chao(text string, mode Mode, showSteps bool) string {
len := len(text)
if utf8.RuneCountInString(text) != len {
fmt.Println("Text contains non-ASCII characters")
return ""
}
left := lAlphabet
right := rAlphabet
eText := make([]byte, len)
temp := make([]byte, 26)
for i := 0; i < len; i++ {
if showSteps {
fmt.Println(left, " ", right)
}
var index int
if mode == Encrypt {
index = strings.IndexByte(right, text[i])
eText[i] = left[index]
} else {
index = strings.IndexByte(left, text[i])
eText[i] = right[index]
}
if i == len - 1 {
break
}
// permute left
for j := index; j < 26; j++ {
temp[j - index] = left[j]
}
for j := 0; j < index; j++ {
temp[26 - index + j] = left[j]
}
store := temp[1]
for j := 2; j < 14; j++ {
temp[j - 1] = temp[j]
}
temp[13] = store
left = string(temp[:])
// permute right
for j := index; j < 26; j++ {
temp[j - index] = right[j]
}
for j := 0; j < index; j++ {
temp[26 - index + j] = right[j]
}
store = temp[0]
for j := 1; j < 26; j++ {
temp[j - 1] = temp[j]
}
temp[25] = store
store = temp[2]
for j := 3; j < 14; j++ {
temp[j - 1] = temp[j]
}
temp[13] = store
right = string(temp[:])
}
return string(eText[:])
}
func main() {
plainText := "WELLDONEISBETTERTHANWELLSAID"
fmt.Println("The original plaintext is :", plainText)
fmt.Print("\nThe left and right alphabets after each permutation ")
fmt.Println("during encryption are :\n")
cipherText := Chao(plainText, Encrypt, true)
fmt.Println("\nThe ciphertext is :", cipherText)
plainText2 := Chao(cipherText, Decrypt, false)
fmt.Println("\nThe recovered plaintext is :", plainText2)
} |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #Delphi | Delphi |
(define dim 100)
(define-syntax-rule (Tidx i j) (+ i (* dim j)))
;; generates Catalan's triangle
;; T (i , j) = T(i-1,j) + T (i, j-1)
(define (T n)
(define i (modulo n dim))
(define j (quotient n dim))
(cond
((zero? i) 1) ;; left column = 1
((= i j) (T (Tidx (1- i) j))) ;; diagonal value = left value
(else (+ (T (Tidx (1- i) j)) (T (Tidx i (1- j)))))))
(remember 'T #(1))
|
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #C | C | #include <stdio.h>
static const char *dog = "Benjamin";
static const char *Dog = "Samba";
static const char *DOG = "Bernie";
int main()
{
printf("The three dogs are named %s, %s and %s.\n", dog, Dog, DOG);
return 0;
} |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #C.23 | C# |
using System;
class Program
{
static void Main(string[] args)
{
string dog = "Benjamin";
string Dog = "Samba";
string DOG = "Bernie";
Console.WriteLine(string.Format("The three dogs are named {0}, {1}, and {2}.", dog, Dog, DOG));
}
} |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #ALGOL_68 | ALGOL 68 | # applies fn to successive elements of the array of values #
# the result is 0 if there are no values #
PROC reduce = ( []INT values, PROC( INT, INT )INT fn )INT:
IF UPB values < LWB values
THEN # no elements #
0
ELSE # there are some elements #
INT result := values[ LWB values ];
FOR pos FROM LWB values + 1 TO UPB values
DO
result := fn( result, values[ pos ] )
OD;
result
FI; # reduce #
# test the reduce procedure #
BEGIN print( ( reduce( ( 1, 2, 3, 4, 5 ), ( INT a, b )INT: a + b ), newline ) ) # sum #
; print( ( reduce( ( 1, 2, 3, 4, 5 ), ( INT a, b )INT: a * b ), newline ) ) # product #
; print( ( reduce( ( 1, 2, 3, 4, 5 ), ( INT a, b )INT: a - b ), newline ) ) # difference #
END |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #Groovy | Groovy | class Chaocipher {
private enum Mode {
ENCRYPT,
DECRYPT
}
private static final String L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
private static final String R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC"
private static int indexOf(char[] a, char c) {
for (int i = 0; i < a.length; ++i) {
if (a[i] == c) {
return i
}
}
return -1
}
private static String exec(String text, Mode mode) {
return exec(text, mode, false)
}
private static String exec(String text, Mode mode, Boolean showSteps) {
char[] left = L_ALPHABET.toCharArray()
char[] right = R_ALPHABET.toCharArray()
char[] eText = new char[text.length()]
char[] temp = new char[26]
for (int i = 0; i < text.length(); ++i) {
if (showSteps) {
println("${new String(left)} ${new String(right)}")
}
int index
if (mode == Mode.ENCRYPT) {
index = indexOf(right, text.charAt(i))
eText[i] = left[index]
} else {
index = indexOf(left, text.charAt(i))
eText[i] = right[index]
}
if (i == text.length() - 1) {
break
}
// permute left
if (26 - index >= 0) System.arraycopy(left, index, temp, 0, 26 - index)
System.arraycopy(left, 0, temp, 26 - index, index)
char store = temp[1]
System.arraycopy(temp, 2, temp, 1, 12)
temp[13] = store
left = Arrays.copyOf(temp, temp.length)
// permute right
if (26 - index >= 0) System.arraycopy(right, index, temp, 0, 26 - index)
System.arraycopy(right, 0, temp, 26 - index, index)
store = temp[0]
System.arraycopy(temp, 1, temp, 0, 25)
temp[25] = store
store = temp[2]
System.arraycopy(temp, 3, temp, 2, 11)
temp[13] = store
right = Arrays.copyOf(temp, temp.length)
}
return new String(eText)
}
static void main(String[] args) {
String plainText = "WELLDONEISBETTERTHANWELLSAID"
println("The original plaintext is : $plainText")
println("\nThe left and right alphabets after each permutation during encryption are:")
String cipherText = exec(plainText, Mode.ENCRYPT, true)
println("\nThe cipher text is : $cipherText")
String plainText2 = exec(cipherText, Mode.DECRYPT)
println("\nThe recovered plaintext is : $plainText2")
}
} |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #EchoLisp | EchoLisp |
(define dim 100)
(define-syntax-rule (Tidx i j) (+ i (* dim j)))
;; generates Catalan's triangle
;; T (i , j) = T(i-1,j) + T (i, j-1)
(define (T n)
(define i (modulo n dim))
(define j (quotient n dim))
(cond
((zero? i) 1) ;; left column = 1
((= i j) (T (Tidx (1- i) j))) ;; diagonal value = left value
(else (+ (T (Tidx (1- i) j)) (T (Tidx i (1- j)))))))
(remember 'T #(1))
|
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #C.2B.2B | C++ | #include <iostream>
#include <string>
using namespace std;
int main() {
string dog = "Benjamin", Dog = "Samba", DOG = "Bernie";
cout << "The three dogs are named " << dog << ", " << Dog << ", and " << DOG << endl;
} |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Clojure | Clojure | user=> (let [dog "Benjamin" Dog "Samba" DOG "Bernie"] (format "The three dogs are named %s, %s and %s." dog Dog DOG))
"The three dogs are named Benjamin, Samba and Bernie." |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #11l | 11l | F cart_prod(a, b)
V p = [(0, 0)] * (a.len * b.len)
V i = 0
L(aa) a
L(bb) b
p[i++] = (aa, bb)
R p
print(cart_prod([1, 2], [3, 4]))
print(cart_prod([3, 4], [1, 2]))
[Int] empty_array
print(cart_prod([1, 2], empty_array))
print(cart_prod(empty_array, [1, 2])) |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #APL | APL | +/ 1 2 3 4 5 6 7
28
×/ 1 2 3 4 5 6 7
5040 |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #Haskell | Haskell | import Data.List (elemIndex)
chao :: Eq a => [a] -> [a] -> Bool -> [a] -> [a]
chao _ _ _ [] = []
chao l r plain (x : xs) = maybe [] go (elemIndex x src)
where
(src, dst)
| plain = (l, r)
| otherwise = (r, l)
go n =
dst !! n :
chao
(shifted 1 14 (rotated n l))
((shifted 2 14 . shifted 0 26) (rotated n r))
plain
xs
rotated :: Int -> [a] -> [a]
rotated n = take . length <*> drop n . cycle
shifted :: Int -> Int -> [a] -> [a]
shifted src dst s = concat [x, rotated 1 y, b]
where
(a, b) = splitAt dst s
(x, y) = splitAt src a
encode, decode :: Bool
encode = False
decode = True
main :: IO ()
main = do
let chaoWheels =
chao
"HXUCZVAMDSLKPEFJRIGTWOBNYQ"
"PTLNBQDEOYSFAVZKGJRIHWXUMC"
plainText = "WELLDONEISBETTERTHANWELLSAID"
cipherText = chaoWheels encode plainText
mapM_
print
[ plainText,
cipherText,
chaoWheels decode cipherText
] |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #EDSAC_order_code | EDSAC order code |
[Catalan numbers from Pascal triangle, Rosetta Code website.
EDSAC program, Initial Orders 2]
..PZ [blank tape and terminator]
T54K [refer to working array with 'C']
P300F [address of working array]
T46K [to call print subroutine with 'G N']
P56F [address of print subroutine]
[Modification of library subroutine P7.
Prints non-negative integer, up to 10 digits, right-justified.
55 locations, load at even address.]
E25KTN
GKA3FT42@A47@T31@ADE10@T31@A48@T31@SDTDH44#@NDYFLDT4DS43@
TFH17@S17@A43@G23@UFS43@T1FV4DAFG50@SFLDUFXFOFFFSFL4FT4DA49@
T31@A1FA43@G20@XFP1024FP610D@524D!FO46@O26@XFO46@SFL8FT4DE39@
[Main program]
PK T200K GK
[Constants]
[0] PD [short constant 1]
[1] P2F [to inc address by 2]
[2] T#C [used in manufacturing EDSAC orders]
[3] MF [add to T order to make A order with same address]
[4] #F [set figures]
[5] &F [line feed]
[6] @F [carriage return]
[7] P7D [maximum n = 15]
[Variable]
[8] PF [n]
[Enter with acc = 0]
[9] O4@ [set teleprinter to figures]
T4#C T2#C T#C A@ TC [initialize first 3 terms to 1, 0, 0]
T8@ E58@ [set n := 0; jump to inc n and print C_n]
[Outer loop; here with n updated]
[17] TF A8@ [acc := latest n]
L1F A2@ T22@ [make and store order 'T 2n #C']
[22] T#C [sets term := 0; also used to test for end of loop]
A2@ [load 'T#C', initial value of order 31]
[Loop to convert e.g. (20, 15, 6, 1) to (35, 21, 7, 1); works left to right]
[24] U31@ A3@ U29@ A1@ T30@ [set up orders on next line]
[29] A#C A#C T#C [replaced by manufactured orders]
A31@ A1@ S22@ E38@ [inc address in order 31, jump out if done]
A22@ E24@ [not done, loop back]
[38] A22@ T48@ [initialize order 48]
[Loop to convert e.g. (35, 21, 7, 1) to (70, 56, 28, 8, 1); works right to left]
[40] TF A48@ A3@ U46@ S1@ T47@ [set up orders on next line]
[46] A#C A#C T#C [replaced by manufactured orders]
A48@ S1@ T48@ [dec address in order 48]
A2@ S48@ G40@ [test for done, loop back if not]
A#C LD T#C [double first term, e.g. 35 -> 70 (not done in loop)]
[Increment n and print Catalan number C_n]
[58] TD [clear 0D, ensures sandwich bit = 0]
A8@ A@ U8@ TF [inc n; set 0D := n by setting 0F := n]
A63@ GN [print n]
A#C S4#C TD A68@ GN [print Catalan number C_n, e.g. C_5 = 70 - 28 = 42]
O6@ O5@ [print CR, LF]
A8@ S7@ G17@ [test for maximum n, loop back if not]
[75] O4@ ZF [flush printer buffer; stop]
E9Z PF [define entry point; enter with acc = 0]
|
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #COBOL | COBOL | * Case sensitivity of identifiers
*>* Commented-out lines in the working storage
*>* are considered as invalid redefinitions
*>* of ''dog'' that can only be ambiguously
*>* referenced in the procedure body.
IDENTIFICATION DIVISION.
PROGRAM-ID. case-sensitivity.
DATA DIVISION.
WORKING-STORAGE SECTION.
*>* 01 dog PICTURE X(8) VALUE IS "Benjamin".
*>* 01 Dog PICTURE X(5) VALUE IS "Samba".
01 DOG PICTURE X(6) VALUE IS "Bernie".
PROCEDURE DIVISION.
DISPLAY
*>* "The three dogs are named "
*>* dog ", " Dog " and " DOG "."
"There is just one dog named " DOG "."
END-DISPLAY
STOP RUN.
END PROGRAM case-sensitivity. |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #CoffeeScript | CoffeeScript |
dog="Benjamin"
Dog = "Samba"
DOG = "Bernie"
console.log "The three dogs are names #{dog}, #{Dog}, and #{DOG}."
|
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
{1, 2} × {} = {}
{} × {1, 2} = {}
For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.
Use your n-ary Cartesian product function to show the following products:
{1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1}
{1, 2, 3} × {30} × {500, 100}
{1, 2, 3} × {} × {500, 100}
| #Action.21 | Action! | DEFINE MAX_COUNT="10"
DEFINE MAX_RESULT="100"
DEFINE PTR="CARD"
PROC PrintInput(PTR ARRAY a INT count)
INT i,j,n
INT ARRAY tmp
FOR i=0 TO count-1
DO
tmp=a(i) n=tmp(0)
Put('[)
FOR j=1 TO n
DO
PrintI(tmp(j))
IF j<n THEN Put(',) FI
OD
Put('])
IF i<count-1 THEN Put('x) FI
OD
RETURN
PROC PrintOutput(INT ARRAY a INT groups,count)
INT i,j,k
Put('[)
k=0
FOR i=0 TO groups-1
DO
Put('()
FOR j=0 TO count-1
DO
PrintI(a(k)) k==+1
IF j<count-1 THEN Put(',) FI
OD
Put('))
IF i<groups-1 THEN Put(',) FI
OD
Put('])
RETURN
PROC Product(PTR ARRAY a INT count
INT ARRAY r INT POINTER groups)
INT ARRAY ind(MAX_COUNT),tmp
INT i,j,k
IF count>MAX_COUNT THEN Break() FI
groups^=1
FOR i=0 TO count-1
DO
ind(i)=1 tmp=a(i)
groups^==*tmp(0)
OD
IF groups^=0 THEN RETURN FI
j=count-1 k=0
DO
FOR i=0 TO count-1
DO
tmp=a(i)
r(k)=tmp(ind(i)) k==+1
OD
DO
tmp=a(j)
IF ind(j)<tmp(0) THEN
ind(j)==+1
FOR i=j+1 TO count-1
DO
ind(i)=1
OD
j=count-1
EXIT
ELSE
IF j=0 THEN RETURN FI
j==-1
FI
OD
OD
RETURN
PROC Test(PTR ARRAY a INT count)
INT ARRAY r(MAX_RESULT)
INT groups
IF count<2 THEN Break() FI
Product(a,count,r,@groups)
PrintInput(a,count)
Put('=)
PrintOutput(r,groups,count)
PutE()
RETURN
PROC Main()
INT ARRAY
a1=[2 1 2],a2=[2 3 4],a3=[0],
a4=[2 1776 1789],a5=[2 7 12],
a6=[3 4 14 23],a7=[2 0 1],
a8=[3 1 2 3],a9=[1 30],a10=[2 500 100]
PTR ARRAY a(4)
a(0)=a1 a(1)=a2 Test(a,2)
a(0)=a2 a(1)=a1 Test(a,2)
a(0)=a1 a(1)=a3 Test(a,2)
a(0)=a3 a(1)=a1 Test(a,2) PutE()
a(0)=a4 a(1)=a5 a(2)=a6 a(3)=a7 Test(a,4) PutE()
a(0)=a8 a(1)=a9 a(2)=a10 Test(a,3) PutE()
a(0)=a8 a(1)=a3 a(2)=a10 Test(a,3)
RETURN |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: Fold
Wikipedia article: Catamorphism
| #AppleScript | AppleScript | ---------------------- CATAMORPHISMS ---------------------
-- the arguments available to the called function f(a, x, i, l) are
-- a: current accumulator value
-- x: current item in list
-- i: [ 1-based index in list ] optional
-- l: [ a reference to the list itself ] optional
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- the arguments available to the called function f(a, x, i, l) are
-- a: current accumulator value
-- x: current item in list
-- i: [ 1-based index in list ] optional
-- l: [ a reference to the list itself ] optional
-- foldr :: (a -> b -> a) -> a -> [b] -> a
on foldr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from lng to 1 by -1
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldr
--- OTHER FUNCTIONS DEFINED IN TERMS OF FOLDL AND FOLDR --
-- concat :: [String] -> string
on concat(xs)
foldl(my append, "", xs)
end concat
-- product :: Num a => [a] -> a
on product(xs)
script
on |λ|(a, b)
a * b
end |λ|
end script
foldr(result, 1, xs)
end product
-- str :: a -> String
on str(x)
x as string
end str
-- sum :: Num a => [a] -> a
on sum(xs)
script
on |λ|(a, b)
a + b
end |λ|
end script
foldl(result, 0, xs)
end sum
--------------------------- TEST -------------------------
on run
set xs to {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
{sum(xs), product(xs), concat(map(str, xs))}
--> {55, 3628800, "10987654321"}
end run
-------------------- GENERIC FUNCTIONS -------------------
-- append :: String -> String -> String
on append(a, b)
a & b
end append
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of xs.
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn |
http://rosettacode.org/wiki/Chaocipher | Chaocipher | Description
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.
The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.
Task
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
| #Java | Java | import java.util.Arrays;
public class Chaocipher {
private enum Mode {
ENCRYPT,
DECRYPT
}
private static final String L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
private static final String R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC";
private static int indexOf(char[] a, char c) {
for (int i = 0; i < a.length; ++i) {
if (a[i] == c) {
return i;
}
}
return -1;
}
private static String exec(String text, Mode mode) {
return exec(text, mode, false);
}
private static String exec(String text, Mode mode, Boolean showSteps) {
char[] left = L_ALPHABET.toCharArray();
char[] right = R_ALPHABET.toCharArray();
char[] eText = new char[text.length()];
char[] temp = new char[26];
for (int i = 0; i < text.length(); ++i) {
if (showSteps) {
System.out.printf("%s %s\n", new String(left), new String(right));
}
int index;
if (mode == Mode.ENCRYPT) {
index = indexOf(right, text.charAt(i));
eText[i] = left[index];
} else {
index = indexOf(left, text.charAt(i));
eText[i] = right[index];
}
if (i == text.length() - 1) {
break;
}
// permute left
if (26 - index >= 0) System.arraycopy(left, index, temp, 0, 26 - index);
System.arraycopy(left, 0, temp, 26 - index, index);
char store = temp[1];
System.arraycopy(temp, 2, temp, 1, 12);
temp[13] = store;
left = Arrays.copyOf(temp, temp.length);
// permute right
if (26 - index >= 0) System.arraycopy(right, index, temp, 0, 26 - index);
System.arraycopy(right, 0, temp, 26 - index, index);
store = temp[0];
System.arraycopy(temp, 1, temp, 0, 25);
temp[25] = store;
store = temp[2];
System.arraycopy(temp, 3, temp, 2, 11);
temp[13] = store;
right = Arrays.copyOf(temp, temp.length);
}
return new String(eText);
}
public static void main(String[] args) {
String plainText = "WELLDONEISBETTERTHANWELLSAID";
System.out.printf("The original plaintext is : %s\n", plainText);
System.out.println("\nThe left and right alphabets after each permutation during encryption are:");
String cipherText = exec(plainText, Mode.ENCRYPT, true);
System.out.printf("\nThe cipher text is : %s\n", cipherText);
String plainText2 = exec(cipherText, Mode.DECRYPT);
System.out.printf("\nThe recovered plaintext is : %s\n", plainText2);
}
} |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #Elixir | Elixir | defmodule Catalan do
def numbers(num) do
{result,_} = Enum.reduce(1..num, {[],{0,1}}, fn i,{list,t0} ->
t1 = numbers(i, t0)
t2 = numbers(i+1, Tuple.insert_at(t1, i+1, elem(t1, i)))
{[elem(t2, i+1) - elem(t2, i) | list], t2}
end)
Enum.reverse(result)
end
defp numbers(0, t), do: t
defp numbers(n, t), do: numbers(n-1, put_elem(t, n, elem(t, n-1) + elem(t, n)))
end
IO.inspect Catalan.numbers(15) |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
Sequence A000108 on OEIS has a lot of information on Catalan Numbers.
Related Tasks
Pascal's triangle
| #Erlang | Erlang |
-module(catalin).
-compile(export_all).
mul(N,D,S,S)->
N2=N*(S+S),
D2=D*S,
K = N2 div D2 ;
mul(N,D,S,L)->
N2=N*(S+L),
D2=D*L,
K = mul(N2,D2,S,L+1).
catl(Ans,16) -> Ans;
catl(D,S)->
C=mul(1,1,S,2),
catl([D|C],S+1).
main()->
Ans=catl(1,2).
|
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Common_Lisp | Common Lisp | CL-USER> (let* ((dog "Benjamin") (Dog "Samba") (DOG "Bernie"))
(format nil "There is just one dog named ~a." dog))
; in: LAMBDA NIL
; (LET* ((DOG "Benjamin") (DOG "Samba") (DOG "Bernie"))
; (FORMAT NIL "There is just one dog named ~a." DOG))
;
; caught STYLE-WARNING:
; The variable DOG is defined but never used.
;
; caught STYLE-WARNING:
; The variable DOG is defined but never used.
;
; compilation unit finished
; caught 2 STYLE-WARNING conditions
"There is just one dog named Bernie." |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language that is lettercase insensitive, we get the following output:
There is just one dog named Bernie.
Related task
Unicode variable names
| #Crystal | Crystal | dog = "Benjamin"
Dog = "Samba"
DOG = "Bernie"
puts "The three dogs are named #{dog}, #{Dog} and #{DOG}." |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.