Straddling checkerboard: Difference between revisions
Added FreeBASIC
SqrtNegInf (talk | contribs) m (→{{header|Tcl}}: Fix link and comment: Perl 6 --> Raku) |
(Added FreeBASIC) |
||
(8 intermediate revisions by 6 users not shown) | |||
Line 6:
Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
<br><br>
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">V t = [[String(‘79’), ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’],
[String(‘’), ‘H’, ‘O’, ‘L’, ‘’, ‘M’, ‘E’, ‘S’, ‘’, ‘R’, ‘T’],
[String(‘3’), ‘A’, ‘B’, ‘C’, ‘D’, ‘F’, ‘G’, ‘I’, ‘J’, ‘K’, ‘N’],
[String(‘7’), ‘P’, ‘Q’, ‘U’, ‘V’, ‘W’, ‘X’, ‘Y’, ‘Z’, ‘.’, ‘/’]]
F straddle(s)
R multiloop_filtered(Array(s.uppercase()), :t, (c, l) -> c C l, (c, l) -> l[0]‘’:t[0][l.index(c)]).join(‘’)
F unstraddle(s)
[String] r
V si = 0
F next()
R @s[@si++]
L
I si == s.len
L.break
V c = s[si++]
I c C (:t[2][0], :t[3][0])
V i = [:t[2][0], :t[3][0]].index(c)
V n = :t[2 + i][:t[0].index(next())]
r [+]= I n == ‘/’ {next()} E n
E
r [+]= :t[1][:t[0].index(c)]
R r
V O = ‘One night-it was on the twentieth of March, 1888-I was returning’
print(‘Encoded: ’straddle(O))
print(‘Decoded: ’unstraddle(straddle(O)).join(‘’))</syntaxhighlight>
{{out}}
<pre>
Encoded: 139539363509369743061399059745399365901344308320791798798798367430685972839363935
Decoded: ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING
</pre>
=={{header|ALGOL 68}}==
Line 12 ⟶ 50:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
<
PRIO MIN=5, MAX=5;
Line 129 ⟶ 167:
))
)</
Output:
<pre>
Line 138 ⟶ 176:
=={{header|AutoHotkey}}==
<
(
ET AON RIS
Line 178 ⟶ 216:
}
}
MsgBox % dec</
=={{header|C}}==
{{libheader|GLib}}
<
#include <stdlib.h>
#include <string.h>
Line 395 ⟶ 433:
return 0;
}</
===Shorter version===
<
#include <stdlib.h>
Line 485 ⟶ 523:
decipher(enc, dec, 1); printf("decoded: %s\n", dec);
return 0;
}</
encoded: 85621250626585107626916996966956265062650706225635247676226639162203702867623288640
decoded: IN THE WINTER 1965 WE WERE HUNGRY JUST BARELY ALIVE
Line 491 ⟶ 529:
No spaces:
encoded: 851250658510769169969669562650650702563524767622663912037028673288640
decoded: INTHEWINTER1965/WEWEREHUNGRY/JUSTBARELYALIVE</
=={{header|C sharp|C#}}==
Translation of [[Straddling_checkerboard#Java|Java]] via [[Straddling_checkerboard#D|D]]
<
using System.Collections.Generic;
using System.Linq;
Line 541 ⟶ 579:
}
}
}</
<pre>139539363509369743061399059745399365901344308320791798798798367430685972839363935
ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING</pre>
=={{header|C++}}==
<
#include <string>
#include <map>
Line 635 ⟶ 673:
return out;
}
};</
Test program:
<
{
StraddlingCheckerboard sc("HOLMESRTABCDFGIJKNPQUVWXYZ./", 3, 7);
Line 651 ⟶ 689:
return 0;
}</
Output:
Line 662 ⟶ 700:
=={{header|D}}==
Partially based on the PicoLisp version:
<
immutable T = ["79|0|1|2|3|4|5|6|7|8|9", "|H|O|L||M|E|S||R|T",
Line 697 ⟶ 735:
writeln("Encoded: ", O.straddle);
writeln("Decoded: ", O.straddle.unStraddle);
}</
{{out}}
<pre>Encoded: 139539363509369743061399059745399365901344308320791798798798367430685972839363935
Line 705 ⟶ 743:
{{trans|C++}}
Same output:
<
struct StraddlingCheckerboard {
Line 779 ⟶ 817:
writeln("Encoded: ", en);
writeln("Decoded: ", sc.decode(en));
}</
===Dictionary-Based Version===
{{trans|Java}}
<
immutable string[const string] val2key, key2val;
Line 810 ⟶ 848:
s.encode.writeln;
s.encode.decode.writeln;
}</
{{out}}
<pre>139539363509369743061399059745399365901344308320791798798798367430685972839363935
ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING</pre>
=={{header|FreeBASIC}}==
{{trans|Go}}
<syntaxhighlight lang="vbnet">Function Encipher(bd As String, pt As String) As String
Dim As String enc(256), row(3), r2d, r3d, d, num, ct
Dim As Integer i = 1, j, col
For j = 0 To 3
row(j) = Mid(bd, i, Instr(i, bd, Chr(10)) - i)
i = Instr(i, bd, Chr(10)) + 1
Next j
r2d = Mid(row(2), 1, 1)
r3d = Mid(row(3), 1, 1)
For col = 1 To 10
d = Mid(row(0), col+1, 1)
enc(Asc(Mid(row(1), col+1, 1))) = d
enc(Asc(Mid(row(2), col+1, 1))) = r2d + d
enc(Asc(Mid(row(3), col+1, 1))) = r3d + d
Next col
num = enc(Asc("/"))
enc(Asc("/")) = ""
enc(Asc(" ")) = ""
ct = ""
For i = 0 To Len(pt)-1
j = Asc(Mid(pt, i+1, 1))
If j <= Asc("9") And j >= Asc("0") Then
ct += num + Chr(j)
Else
If j <= Asc("z") And j >= Asc("a") Then
j -= Asc("a") - Asc("A")
End If
ct += enc(j)
End If
Next i
Return ct
End Function
Function Decipher(bd As String, ct As String) As String
Dim As String row(3), pt, b
Dim As Integer i = 1, j, cx(10), r2d, r3d, r, d
For j = 0 To 3
row(j) = Mid(bd, i, Instr(i, bd, Chr(10)) - i)
i = Instr(i, bd, Chr(10)) + 1
Next j
For i = 1 To 10
cx(Asc(Mid(row(0), i+1, 1)) - Asc("0")) = i
Next i
r2d = Asc(Mid(row(2), 1, 1)) - Asc("0")
r3d = Asc(Mid(row(3), 1, 1)) - Asc("0")
pt = ""
i = 0
While i < Len(ct)
d = Asc(Mid(ct, i+1, 1)) - Asc("0")
If d = r2d Then
r = 2
Elseif d = r3d Then
r = 3
Else
pt += Mid(row(1), cx(d)+1, 1)
i += 1
Continue While
End If
i += 1
b = Mid(row(r), cx(Asc(Mid(ct, i+1, 1)) - Asc("0"))+1, 1)
If b = "/" Then
i += 1
pt += Mid(ct, i+1, 1)
Else
pt += b
End If
i += 1
Wend
Return pt
End Function
Dim As String key = _
" 8752390146" + Chr(10) + _
" ET AON RIS" + Chr(10) + _
"5BC/FGHJKLM" + Chr(10) + _
"0PQD.VWXYZU"
Dim p As String = "you have put on 7.5 pounds since I saw you."
Print p
Dim c As String = Encipher(key, p)
Print c
Print Decipher(key, c)
Sleep</syntaxhighlight>
{{out}}
<pre>Same as Go entry.</pre>
=={{header|F_Sharp|F#}}==
<
(*
Encode and Decode using StraddlingCheckerboard
Line 837 ⟶ 966:
Seq.iter2 (fun ng gn->a.[(char i,char ng)]<-string gn;b.[gn]<-i+ng) z l
{n=char n;i=char i;g=a;e=b}
</syntaxhighlight>
{{out}}
<
let N = G "2" "6" "ETAONRIS" "BCDFGHJKLM" "PQ/UVWXYZ." ["0";"1";"2";"3";"4";"5";"6";"7";"8";"9"]
N.decode "450582425181653945125016505180125423293721256216286286288653970163758524"|>Seq.iter(fun n->printf "%s" n);; //ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING
N.encode "IN THE WINTER 1965 WE WERE HUNGRY JUST BARELY ALIVE"|>Seq.iter(fun n->printfn "%s" n);; //8562 125062 658510762 62162962662562 65062 6507062 256352476762 26639162 20370286762 3288640
N.decode "8562 125062 658510762 62162962662562 65062 6507062 256352476762 26639162 20370286762 3288640"|>Seq.iter(fun n->printf "%s" n);; //IN THE WINTER 1965 WE WERE HUNGRY JUST BARELY ALIVE
</syntaxhighlight>
=={{header|Go}}==
<
import (
Line 923 ⟶ 1,051:
}
return
}</
{{out}}
<pre>
Line 932 ⟶ 1,060:
=={{header|Haskell}}==
<
import Data.Map
Line 979 ⟶ 1,107:
in mapM_ putStrLn [ "Original: " ++ orig
, "Encoded: " ++ enc
, "Decoded: " ++ dec ]</
{{out}}
Line 988 ⟶ 1,116:
=={{header|Icon}} and {{header|Unicon}}==
<
StraddlingCheckerBoard("setup","HOLMESRTABCDFGIJKNPQUVWXYZ./", 3,7)
Line 1,028 ⟶ 1,156:
}
}
end</
Output:<pre>text = "One night. it was on the twentieth of March, 1888. I was returning"
Line 1,036 ⟶ 1,164:
=={{header|J}}==
'''Solution:'''
<
'Nums Alpha'=: '0123456789';'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Charset=: Nums,Alpha,Stop
Line 1,060 ⟶ 1,188:
}.board {~ _2 (_&".)\ idx
end.
)</
'''Example usage:'''
<
chkbrdRC=: chkbrd (3 7;'HOLMESRTABCDFGIJKNPQUVWXYZ./') NB. define adverb by applying Rosetta Code key to chkbrd conjunction
0 chkbrdRC preprocess 'One night-it was on the twentieth of March, 1888-I was returning'
139539363509369743061399059745399365901344308320791798798798367430685972839363935
1 chkbrdRC 0 chkbrdRC preprocess 'One night-it was on the twentieth of March, 1888-I was returning'
ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING</
Or using the rules proposed by [[User:Util|Util]] on the discussion page:
<
1 chkbrdRC 0 chkbrdRC preprocess 'One night-it was on the twentieth of March, 1888-I was returning'
ONE.NIGHT.IT.WAS.ON.THE.TWENTIETH.OF.MARCH..1888.I.WAS.RETURNING</
Line 1,077 ⟶ 1,205:
'''Solution:'''
<
NB. creates verbs encode and decode which change between unencoded text and lists of encoded numbers
setcode=: 3 :0
Line 1,093 ⟶ 1,221:
decode=: (alphabet {~ keys i. break f.) :. encode
i.0 0
)</
'''Example usage:'''
<
preprocess=: (#~ alphabet e.~ ])@toupper
,":"0 encode message=: preprocess 'One night-it was on the twentieth of March, 1888-I was returning'
Line 1,105 ⟶ 1,233:
OWVKRNEOAMTMXROWOHTMTMTROTQ4SEMRRLRZLVSTTLLOROMHALSFOHECMRWESWEE
((10|-) 0 4 5 2$~$)&.encode s
ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING</
=={{header|Java}}==
{{works with|Java|7}}
<
import java.util.Map;
import java.util.regex.*;
Line 1,156 ⟶ 1,284:
return sb.toString();
}
}</
<pre>139539363509369743061399059745399365901344308320791798798798367430685972839363935
Line 1,162 ⟶ 1,290:
=={{header|JavaScript}}==
<
var alphabet=new Array("ESTONIA R","BCDFGHJKLM","PQUVWXYZ./") // scramble alphabet as you wish
var prefixes=new Array("",alphabet[0].indexOf(" "),alphabet[0].lastIndexOf(" "))
Line 1,202 ⟶ 1,330:
document.writeln(straddle(str))
document.writeln(unstraddle(straddle(str)))
</script></
Output:<pre>One night-it was on the twentieth of March, 1888-I was returning.
Line 1,211 ⟶ 1,339:
Unlike the precomputed table versions, this version takes a 30-character string specifying the 3 rows of the checkerboard
as an argument, recomputing the lookup table each run, which allows easier changes of keys without modifying the code.
<
function straddlingcheckerboard(board, msg, doencode)
lookup = Dict()
Line 1,277 ⟶ 1,405:
decoded = straddlingcheckerboard(btable, encoded, false)
println("Original: $message\nEncoded: $encoded\nDecoded: $decoded")
</syntaxhighlight>
{{output}}
<pre>
Line 1,286 ⟶ 1,414:
=={{header|Kotlin}}==
<
val board = "ET AON RISBCDFGHJKLMPQ/UVWXYZ."
Line 1,366 ⟶ 1,494:
println("Decrypted : $decrypted")
}
}</
{{out}}
Line 1,392 ⟶ 1,520:
=={{header|Lua}}==
<
local brd = { "HOL MES RT", "ABCDFGIJKN", "PQUVWXYZ./" }
local dicE, dicD, s1, s2 = {}, {}, 0, 0
Line 1,465 ⟶ 1,593:
-- entry point
enterText()
</syntaxhighlight>
{{out}}
<pre>
Line 1,486 ⟶ 1,614:
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
module Straddling_checkerboard {
function encrypt$(message$, alphabet) {
Line 1,610 ⟶ 1,738:
}
Straddling_checkerboard
</syntaxhighlight>
{{out}}
Line 1,645 ⟶ 1,773:
ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING
</pre >
=={{header|Nim}}==
I used the same example as in the Go solution (and, fortunately, got the same result).
<syntaxhighlight lang="nim">import strutils, tables
const
FullStop = '.'
Escape = '/'
type Checkerboard = object
encryptTable: Table[char, string]
decryptTable: Table[string, char]
proc initCheckerboard(digits: string; row1, row2, row3: string): Checkerboard =
## Initialize a checkerboard with given digits in row 0 and the following given rows.
## No sanity check is performed.
var rowChars: seq[char] # The two characters to use to identify rows 2 and 3.
# Process row 1.
for col, ch in row1:
if ch == ' ':
rowChars.add digits[col]
else:
result.encryptTable[ch] = $digits[col]
if rowChars.len != 2:
raise newException(ValueError, "expected two blank spots in first letter row.")
# Add rows 2 and 3.
for col, ch in row2:
result.encryptTable[ch] = rowChars[0] & digits[col]
for col, ch in row3:
result.encryptTable[ch] = rowChars[1] & digits[col]
if Escape notin result.encryptTable:
raise newException(ValueError, "missing Escape character.")
# Build decrypt table from encrypt table.
for c, s in result.encryptTable.pairs:
result.decryptTable[s] = c
proc encrypt(board: Checkerboard; message: string): string =
## Encrypt a string.
let message = message.toUpperAscii
for ch in message:
case ch
of 'A'..'Z', FullStop, Escape:
result.add board.encryptTable[ch]
of '0'..'9':
result.add board.encryptTable[Escape]
result.add ch
else:
discard # Ignore other characters.
proc raiseError() =
## Raise a ValueError to signal a corrupt message.
raise newException(ValueError, "corrupt message")
proc decrypt(board: Checkerboard; message: string): string =
## Decrypt a message.
var escaped = false # Escape char previously encountered.
var str = "" # Current sequence of characters (contains 0, 1 or 2 chars).
for ch in message:
if ch notin '0'..'9': raiseError()
if escaped:
# Digit is kept as is.
result.add ch
escaped = false
else:
# Try to decrypt this new digit.
str.add ch
if str in board.decryptTable:
let c = board.decryptTable[str]
if c == Escape: escaped = true
else: result.add c
str.setLen(0)
elif str.len == 2:
# Illegal combination of two digits.
raiseError()
when isMainModule:
let board = initCheckerboard("8752390146", "ET AON RIS", "BC/FGHJKLM", "PQD.VWXYZU")
let message = "you have put on 7.5 pounds since I saw you."
echo "Message: ", message
let crypted = board.encrypt(message)
echo "Crypted: ", crypted
echo "Decrypted: ", board.decrypt(crypted)</syntaxhighlight>
{{out}}
<pre>Message: you have put on 7.5 pounds since I saw you.
Crypted: 01306592038080673955702555083069056649578462090130602
Decrypted: YOUHAVEPUTON7.5POUNDSSINCEISAWYOU.</pre>
=={{header|Perl}}==
{{trans|Raku}}
<
use warnings;
use feature 'say';
Line 1,698 ⟶ 1,925:
say 'Original: ', my $original = 'One night-it was on the twentieth of March, 1888-I was returning';
say 'Encoded: ', my $en = encode($original);
say 'Decoded: ', decode($en);</
{{out}}
<pre> 0 1 2 3 4 5 6 7 8 9
Line 1,711 ⟶ 1,938:
=={{header|Phix}}==
{{trans|C}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">read_table</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">cb</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">encode</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #000000;">128</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">decode</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">128</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">row</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cb</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">30</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"table wrong length"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">30</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">cb</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #008000;">' '</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">row</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span>
<span
<span style="color: #004080;">integer</span> <span style="color: #000000;">code</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">row</span><span style="color: #0000FF;">[</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">((</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]*</span><span style="color: #000000;">10</span><span style="color: #0000FF;">+</span><span style="color: #7060A8;">mod</span><span style="color: #0000FF;">((</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">),</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">encode</span><span style="color: #0000FF;">[</span><span style="color: #000000;">c</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">code</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">decode</span><span style="color: #0000FF;">[</span><span style="color: #000000;">code</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">c</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">encode</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">decode</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">encipher</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">encode</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">bool</span> <span style="color: #000000;">strip</span><span style="color: #0000FF;">=</span><span style="color: #004600;">false</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">upper</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]),</span> <span style="color: #000000;">code</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">>=</span><span style="color: #008000;">'0'</span> <span style="color: #008080;">and</span> <span style="color: #000000;">c</span><span style="color: #0000FF;"><=</span><span style="color: #008000;">'9'</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">encode</span><span style="color: #0000FF;">[</span><span style="color: #008000;">'.'</span><span style="color: #0000FF;">]&</span><span style="color: #000000;">c</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">>=</span><span style="color: #008000;">'A'</span> <span style="color: #008080;">and</span> <span style="color: #000000;">c</span><span style="color: #0000FF;"><=</span><span style="color: #008000;">'Z'</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">encode</span><span style="color: #0000FF;">[</span><span style="color: #000000;">c</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">elsif</span> <span style="color: #008080;">not</span> <span style="color: #000000;">strip</span> <span style="color: #008080;">or</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #008000;">'/'</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- (see note)</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">encode</span><span style="color: #0000FF;">[</span><span style="color: #008000;">'/'</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">decipher</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">decode</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">bool</span> <span style="color: #000000;">strip</span><span style="color: #0000FF;">=</span><span style="color: #004600;">false</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">i</span><span style="color: #0000FF;"><=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]-</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">decode</span><span style="color: #0000FF;">[</span><span style="color: #000000;">c</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">i</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">10</span><span style="color: #0000FF;">+</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]-</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">decode</span><span style="color: #0000FF;">[</span><span style="color: #000000;">c</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">=</span><span style="color: #008000;">'.'</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">i</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">=</span><span style="color: #008000;">'/'</span> <span style="color: #008080;">and</span> <span style="color: #008080;">not</span> <span style="color: #000000;">strip</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- (see note)</span>
<span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">' '</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">d</span>
<span style="color: #000000;">i</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">cb</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"ET AON RIS"</span><span style="color: #0000FF;">&</span>
<span style="color: #008000;">"BCDFGHJKLM"</span><span style="color: #0000FF;">&</span>
<span style="color: #008000;">"PQ/UVWXYZ."</span>
<span style="color: #004080;">sequence</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">encode</span><span style="color: #0000FF;">,</span><span style="color: #000000;">decode</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">read_table</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cb</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- Note there is a subtle difference in space handling, to exactly match other outputs try
-- {encode,decode} = read_table("
-- {encode,decode} = read_table("
-- {encode,decode} = read_table("ET AON RISBCDFGHJKLMPQ.UVWXYZ/") instead of
-- {encode,decode} = read_table("ET AON RISBCDFGHJKLMPQ/UVWXYZ.")</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">msg</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"In the winter 1965/we were hungry/just barely alive"</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"message: %s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">msg</span><span style="color: #0000FF;">})</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">enc</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">encipher</span><span style="color: #0000FF;">(</span><span style="color: #000000;">encode</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">msg</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">dec</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">decipher</span><span style="color: #0000FF;">(</span><span style="color: #000000;">decode</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">enc</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"encoded: %s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">enc</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"decoded: %s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">dec</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\nNo spaces:\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">enc</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">encipher</span><span style="color: #0000FF;">(</span><span style="color: #000000;">encode</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">msg</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">true</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">dec</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">decipher</span><span style="color: #0000FF;">(</span><span style="color: #000000;">decode</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">enc</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">true</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"encoded: %s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">enc</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"decoded: %s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">dec</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,803 ⟶ 2,033:
{{trans|Java}}
{{works with|PHP 7}}
<
"H"=>"0", "I"=>"36", "J"=>"37", "K"=>"38", "L"=>"2", "M"=>"4", "."=>"78", "N"=>"39",
"/"=>"79", "O"=>"1", "0"=>"790", "P"=>"70", "1"=>"791", "Q"=>"71", "2"=>"792",
Line 1,837 ⟶ 2,067:
}
main('One night-it was on the twentieth of March, 1888-I was returning');</
<pre>
139539363509369743061399059745399365901344308320791798798798367430685972839363935
Line 1,844 ⟶ 2,074:
=={{header|PicoLisp}}==
<
(NIL "H" "O" "L" NIL "M" "E" "S" NIL "R" "T")
("3" "A" "B" "C" "D" "F" "G" "I" "J" "K" "N")
Line 1,871 ⟶ 2,101:
(get (cdr @) (inc (format (pop 'L))))
(get (cdar *Straddling) (inc (format C))) ) )
(link (if (= "/" C) (pop 'L) C)) ) ) ) ) )</
Output:
<pre>: (straddle "One night-it was on the twentieth of March, 1888-I was returning")
Line 1,880 ⟶ 2,110:
=={{header|PureBasic}}==
<
Static notEscape.s = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ."
Protected preDigit_1.s = Str(blank_1), preDigit_2.s = Str(blank_2)
Line 1,975 ⟶ 2,205:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
Sample output:
<pre>Original: One night-it was on the twentieth of March, 1888-I was returning
Line 1,984 ⟶ 2,214:
=={{header|Python}}==
Partially based on the PicoLisp version:
<
["", "H", "O", "L", "", "M", "E", "S", "", "R", "T"],
["3", "A", "B", "C", "D", "F", "G", "I", "J", "K", "N"],
Line 2,004 ⟶ 2,234:
O = "One night-it was on the twentieth of March, 1888-I was returning"
print "Encoded:", straddle(O)
print "Decoded:", "".join(unstraddle(straddle(O)))</
Output:
<pre>Encoded: 139539363509369743061399059745399365901344308320791798798798367430685972839363935
Line 2,013 ⟶ 2,243:
We store the straddling checkerboard in a structure, so it can be reused or changed for the different examples. The “constructor” transforms the lines of the checkboard into an internal representation.
<
(struct *straddling (header main original)
Line 2,041 ⟶ 2,271:
(*straddling (list->vector (list* "?" "" header-tail)) main lines))
(define escape (straddling-encode-char #\/ temporal-board))
(*straddling (list->vector (list* escape "" header-tail)) main lines))</
Now we define the functions to straddle and unstraddle the message.
<
(or (for/or ([head (in-vector (*straddling-header board))]
[line (in-vector (*straddling-main board))])
Line 2,082 ⟶ 2,312:
(values #f (cons decoded rev-ret))))))])
(unless row ;check that last number was not missing
rev-ret)))))</
'''Two examples:'''
<
(let* ([encoded (straddle message board)]
[decoded (unstraddle encoded board)])
Line 2,100 ⟶ 2,330:
(straddling "ET AON RIS"
"BCDFGHJKLM"
"PQ/UVWXYZ."))</
{{out}}
<pre>#<straddling ("HOL MES RT" "ABCDFGIJKN" "PQUVWXYZ./")>
Line 2,118 ⟶ 2,348:
We build the full table during .new, which simplifies .encode and .decode.
<syntaxhighlight lang="raku"
has @!flat_board; # 10x3 stored as 30x1
has $!plain2code; # full translation table, invertable
Line 2,177 ⟶ 2,407:
say "Decoded: $de";
}
}</
Output:<pre> 0 1 2 3 4 5 6 7 8 9
Line 2,199 ⟶ 2,429:
:* no hard-coding of the location of the escape character,
:* support the usage of a blank in the 1<sup>st</sup> character (the top line of the table).
<
parse arg msg
if msg='' then msg= 'One night-it was the twentieth of March, 1888-I was returning'
say 'plain text=' msg
call genCipher 'et aon ris', 'bcdfghjklm', 'pq/uvwxyz.' /*build the cipher (board)*/
enc= encrypt(msg); say ' encrypted=' enc
dec= decrypt(enc); say ' decrypted=' dec
exit
/*──────────────────────────────────────────────────────────────────────────────────────*/
genCipher: @.=; arg @..,two,three; z= -1; @.z= @..
_= pos(' ', @.. ) - 1; @._= two
_= pos(' ', @.., _+2) - 1; @._= three
do j=0 for 9; @..= @.. || @.j
if @.j\=='' then @.r= @.r || j
_= pos('/', @.j)
if _\==0 then @.dig= j || (_-1)
end /*j*/
@..= space(@.., 0);
/*──────────────────────────────────────────────────────────────────────────────────────*/
encrypt: procedure expose @.; arg !,,$ /*$: output (encrypted text) so far.*/
do j=1 for length(!) /*process each of the plain─text chars.*/
x= substr(!, j, 1)
if datatype(x, 'W') then do; $= $ || @.dig || x; iterate; end /*numeral?
if pos(x, @..)==0 then iterate /*Not one of the allowable chars? Skip*/
do k=-1 for 10; y= pos(x, @.k)
if y==0 then iterate /*Not in this row? Then keep looking.*/
z= k;
$= $ || z || (y-1);
end /*k*/
end /*j*/; return $
/*──────────────────────────────────────────────────────────────────────────────────────*/
decrypt: procedure expose @.; parse arg !,,$
do j=1 to length(!); rw= -1
if substr(!,j,2)==@.dig then do; j= j+2; $= $ ||
if pos(x, @.r)\==0 then do; j= j+1; rw=x; x=substr(!, j, 1);
$= $ || substr(@.rw, x+1, 1)
end /*j*/; return $</syntaxhighlight>
{{out|output|text= when using the default input:}}
<pre>
Line 2,250 ⟶ 2,476:
=={{header|Ruby}}==
{{works with|Ruby|2.0}}
<
EncodableChars = "A-Z0-9."
SortedChars = " ./" + [*"A".."Z"].join
Line 2,310 ⟶ 2,536:
"#<%s board=%p, row_labels=%p, mapping=%p>" % [self.class, to_s, @row_labels, @mapping]
end
end</
The test suite
<
class StraddlingCheckerboardTest < Test::Unit::TestCase
def setup
Line 2,352 ⟶ 2,578:
assert_raise(ArgumentError) {StraddlingCheckerboard.new "ET ON RISBCDFGHJKLMPQ/UVWXYZ.!"}
end
end</
output
Line 2,371 ⟶ 2,597:
=={{header|Scala}}==
{{Out}}Best seen running in your browser either by [https://scalafiddle.io/sf/xCHsvaC/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/42qQPkm6TiONpAOC1ByTCg Scastie (remote JVM)].
<
private val dictonary = Map("H" -> "0", "O" -> "1",
Line 2,396 ⟶ 2,622:
println(enc)
println(decode(enc))
}</
=={{header|Tcl}}==
Structured as a class, the instances of which contain encoding and decoding mappings suitable for use with Tcl's built in string remapping engine. This uses the fact that no sequence of digits in the encoded form that maps to one character is a prefix of the sequence for any other character. (Inspired by the ''description'' of the [[#Raku|Raku]] solution.)<!--not a translation though; I didn't read the Raku code…-->
<
oo::class create StraddlingCheckerboardCypher {
Line 2,435 ⟶ 2,661:
string map $decmap [regsub -all {[^0-9]} $msg ""]
}
}</
Demonstration code:
<
{{} E T {} A O N {} R I S}
{2 B C D F G H J K L M}
Line 2,447 ⟶ 2,673:
puts "Input: $input"
puts "Encoded: $encrypted"
puts "Decoded: $output"</
Output:
<pre>
Line 2,457 ⟶ 2,683:
=={{header|VBScript}}==
{{trans|PureBasic}}
<
Function encrypt(ByVal originalText, ByVal alphabet, blank1, blank2)
Line 2,544 ⟶ 2,770:
decoded = decrypt(encoded, cipher, 3, 7)
Buffer=Buffer & "decoded: " & decoded & vbCrlf
Wscript.Echo Buffer </
{{out}}
<pre>
Line 2,550 ⟶ 2,776:
encoded: 139539363509369743061399059745399365901344308320791798798798367430685972839363935
decoded: ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING
</pre>
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-str}}
<syntaxhighlight lang="wren">import "./str" for Str
var board = "ET AON RISBCDFGHJKLMPQ/UVWXYZ."
var digits = "0123456789"
var rows = " 26"
var escape = "62"
var key = "0452"
var encrypt = Fn.new { |message|
var msg = Str.upper(message).
where { |c| (board.contains(c) || digits.contains(c)) && !" /".contains(c) }.join()
var sb = ""
for (c in msg) {
var idx = board.indexOf(c)
if (idx > -1) {
var row = (idx/10).floor
var col = idx % 10
sb = sb + ((row == 0) ? "%(col)" : "%(rows[row])%(col)")
} else {
sb = sb + "%(escape)%(c)"
}
}
var enc = sb.bytes.toList
var i = 0
for (c in enc) {
var k = key[i%4].bytes[0] - 48
if (k != 0) {
var j = c - 48
enc[i] = 48 + ((j + k) % 10)
}
i = i + 1
}
return enc.map { |b| String.fromByte(b) }.join()
}
var decrypt = Fn.new { |encoded|
var enc = encoded.bytes.toList
var i = 0
for (c in enc) {
var k = key[i%4].bytes[0] - 48
if (k != 0) {
var j = c - 48
enc[i] = 48 + ((j >= k) ? (j - k) % 10 : (10 + j - k) % 10)
}
i = i + 1
}
var len = enc.count
var sb = ""
i = 0
while (i < len) {
var c = enc[i]
var idx = rows.indexOf((c-48).toString)
if (idx == -1) {
var idx2 = c - 48
sb = sb + board[idx2]
i = i + 1
} else if ("%(c-48)%(enc[i + 1]-48)" == escape) {
sb = sb + (enc[i + 2] - 48).toString
i = i + 3
} else {
var idx2 = idx * 10 + enc[i + 1] - 48
sb = sb + board[idx2]
i = i + 2
}
}
return sb
}
var messages = [
"Attack at dawn",
"One night-it was on the twentieth of March, 1888-I was returning",
"In the winter 1965/we were hungry/just barely alive",
"you have put on 7.5 pounds since I saw you.",
"The checkerboard cake recipe specifies 3 large eggs and 2.25 cups of flour."
]
for (message in messages) {
var encrypted = encrypt.call(message)
var decrypted = decrypt.call(encrypted)
System.print("\nMessage : %(message)")
System.print("Encrypted : %(encrypted)")
System.print("Decrypted : %(decrypted)")
}</syntaxhighlight>
{{out}}
<pre>
Message : Attack at dawn
Encrypted : 3565257935743007
Decrypted : ATTACKATDAWN
Message : One night-it was on the twentieth of March, 1888-I was returning
Encrypted : 495786945533698149645468540384645875238925776668221480708005915367278976
Decrypted : ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING
Message : In the winter 1965/we were hungry/just barely alive
Encrypted : 89645417896270736648201450026959060839767024608116557470618482160
Decrypted : INTHEWINTER1965WEWEREHUNGRYJUSTBARELYALIVE
Message : you have put on 7.5 pounds since I saw you.
Encrypted : 61983605685800834914704829124087264189730245691940889
Decrypted : YOUHAVEPUTON7.5POUNDSSINCEISAWYOU.
Message : The checkerboard cake recipe specifies 3 large eggs and 2.25 cups of flour.
Encrypted : 160225770664742408892673362274738052905225343251668487244454469139746678907466041088039436848815704
Decrypted : THECHECKERBOARDCAKERECIPESPECIFIES3LARGEEGGSAND2.25CUPSOFFLOUR.
</pre>
=={{header|zkl}}==
{{trans|D}}
<
val2key=Dictionary(
"A","30", "B","31", "C","32", "D","33", "E","5", "F","34", "G","35",
Line 2,565 ⟶ 2,900:
fcn encode(txt){ txt.toUpper().pump(String,val2key.find.fp1("")) }
fcn decode(str){ RegExp("79.|3.|7.|.").pump(str,String,key2val.get) }</
<
str:=encode(txt);
println("Encoded: ", str);
println("Decoded: ", decode(str));</
{{out}}
<pre>
|