Straddling checkerboard: Difference between revisions
Added FreeBASIC
m (→{{header|Phix}}: syntax coloured, made p2js compatible) |
(Added FreeBASIC) |
||
(3 intermediate revisions by 3 users not shown) | |||
Line 10:
{{trans|Python}}
<
[String(‘’), ‘H’, ‘O’, ‘L’, ‘’, ‘M’, ‘E’, ‘S’, ‘’, ‘R’, ‘T’],
[String(‘3’), ‘A’, ‘B’, ‘C’, ‘D’, ‘F’, ‘G’, ‘I’, ‘J’, ‘K’, ‘N’],
Line 37:
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(‘’))</
{{out}}
Line 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 167:
))
)</
Output:
<pre>
Line 176:
=={{header|AutoHotkey}}==
<
(
ET AON RIS
Line 216:
}
}
MsgBox % dec</
=={{header|C}}==
{{libheader|GLib}}
<
#include <stdlib.h>
#include <string.h>
Line 433:
return 0;
}</
===Shorter version===
<
#include <stdlib.h>
Line 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 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 579:
}
}
}</
<pre>139539363509369743061399059745399365901344308320791798798798367430685972839363935
ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING</pre>
=={{header|C++}}==
<
#include <string>
#include <map>
Line 673:
return out;
}
};</
Test program:
<
{
StraddlingCheckerboard sc("HOLMESRTABCDFGIJKNPQUVWXYZ./", 3, 7);
Line 689:
return 0;
}</
Output:
Line 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 735:
writeln("Encoded: ", O.straddle);
writeln("Decoded: ", O.straddle.unStraddle);
}</
{{out}}
<pre>Encoded: 139539363509369743061399059745399365901344308320791798798798367430685972839363935
Line 743:
{{trans|C++}}
Same output:
<
struct StraddlingCheckerboard {
Line 817:
writeln("Encoded: ", en);
writeln("Decoded: ", sc.decode(en));
}</
===Dictionary-Based Version===
{{trans|Java}}
<
immutable string[const string] val2key, key2val;
Line 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 875 ⟶ 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 961 ⟶ 1,051:
}
return
}</
{{out}}
<pre>
Line 970 ⟶ 1,060:
=={{header|Haskell}}==
<
import Data.Map
Line 1,017 ⟶ 1,107:
in mapM_ putStrLn [ "Original: " ++ orig
, "Encoded: " ++ enc
, "Decoded: " ++ dec ]</
{{out}}
Line 1,026 ⟶ 1,116:
=={{header|Icon}} and {{header|Unicon}}==
<
StraddlingCheckerBoard("setup","HOLMESRTABCDFGIJKNPQUVWXYZ./", 3,7)
Line 1,066 ⟶ 1,156:
}
}
end</
Output:<pre>text = "One night. it was on the twentieth of March, 1888. I was returning"
Line 1,074 ⟶ 1,164:
=={{header|J}}==
'''Solution:'''
<
'Nums Alpha'=: '0123456789';'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Charset=: Nums,Alpha,Stop
Line 1,098 ⟶ 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,115 ⟶ 1,205:
'''Solution:'''
<
NB. creates verbs encode and decode which change between unencoded text and lists of encoded numbers
setcode=: 3 :0
Line 1,131 ⟶ 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,143 ⟶ 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,194 ⟶ 1,284:
return sb.toString();
}
}</
<pre>139539363509369743061399059745399365901344308320791798798798367430685972839363935
Line 1,200 ⟶ 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,240 ⟶ 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,249 ⟶ 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,315 ⟶ 1,405:
decoded = straddlingcheckerboard(btable, encoded, false)
println("Original: $message\nEncoded: $encoded\nDecoded: $decoded")
</syntaxhighlight>
{{output}}
<pre>
Line 1,324 ⟶ 1,414:
=={{header|Kotlin}}==
<
val board = "ET AON RISBCDFGHJKLMPQ/UVWXYZ."
Line 1,404 ⟶ 1,494:
println("Decrypted : $decrypted")
}
}</
{{out}}
Line 1,430 ⟶ 1,520:
=={{header|Lua}}==
<
local brd = { "HOL MES RT", "ABCDFGIJKN", "PQUVWXYZ./" }
local dicE, dicD, s1, s2 = {}, {}, 0, 0
Line 1,503 ⟶ 1,593:
-- entry point
enterText()
</syntaxhighlight>
{{out}}
<pre>
Line 1,524 ⟶ 1,614:
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
module Straddling_checkerboard {
function encrypt$(message$, alphabet) {
Line 1,648 ⟶ 1,738:
}
Straddling_checkerboard
</syntaxhighlight>
{{out}}
Line 1,686 ⟶ 1,776:
=={{header|Nim}}==
I used the same example as in the Go solution (and, fortunately, got the same result).
<
const
Line 1,776 ⟶ 1,866:
let crypted = board.encrypt(message)
echo "Crypted: ", crypted
echo "Decrypted: ", board.decrypt(crypted)</
{{out}}
Line 1,785 ⟶ 1,875:
=={{header|Perl}}==
{{trans|Raku}}
<
use warnings;
use feature 'say';
Line 1,835 ⟶ 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,848 ⟶ 1,938:
=={{header|Phix}}==
{{trans|C}}
<!--<
<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>
Line 1,928 ⟶ 2,018:
<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>
<!--</
{{out}}
<pre>
Line 1,943 ⟶ 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,977 ⟶ 2,067:
}
main('One night-it was on the twentieth of March, 1888-I was returning');</
<pre>
139539363509369743061399059745399365901344308320791798798798367430685972839363935
Line 1,984 ⟶ 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 2,011 ⟶ 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 2,020 ⟶ 2,110:
=={{header|PureBasic}}==
<
Static notEscape.s = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ."
Protected preDigit_1.s = Str(blank_1), preDigit_2.s = Str(blank_2)
Line 2,115 ⟶ 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 2,124 ⟶ 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,144 ⟶ 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,153 ⟶ 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,181 ⟶ 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,222 ⟶ 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,240 ⟶ 2,330:
(straddling "ET AON RIS"
"BCDFGHJKLM"
"PQ/UVWXYZ."))</
{{out}}
<pre>#<straddling ("HOL MES RT" "ABCDFGIJKN" "PQUVWXYZ./")>
Line 2,258 ⟶ 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,317 ⟶ 2,407:
say "Decoded: $de";
}
}</
Output:<pre> 0 1 2 3 4 5 6 7 8 9
Line 2,339 ⟶ 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 /*obtain optional message from the C.L.*/
if msg='' then msg= 'One night-it was the twentieth of March, 1888-I was returning'
Line 2,376 ⟶ 2,466:
if pos(x, @.r)\==0 then do; j= j+1; rw=x; x=substr(!, j, 1); end
$= $ || substr(@.rw, x+1, 1) /*add a character to decrypted message.*/
end /*j*/; return $</
{{out|output|text= when using the default input:}}
<pre>
Line 2,386 ⟶ 2,476:
=={{header|Ruby}}==
{{works with|Ruby|2.0}}
<
EncodableChars = "A-Z0-9."
SortedChars = " ./" + [*"A".."Z"].join
Line 2,446 ⟶ 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,488 ⟶ 2,578:
assert_raise(ArgumentError) {StraddlingCheckerboard.new "ET ON RISBCDFGHJKLMPQ/UVWXYZ.!"}
end
end</
output
Line 2,507 ⟶ 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,532 ⟶ 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,571 ⟶ 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,583 ⟶ 2,673:
puts "Input: $input"
puts "Encoded: $encrypted"
puts "Decoded: $output"</
Output:
<pre>
Line 2,593 ⟶ 2,683:
=={{header|VBScript}}==
{{trans|PureBasic}}
<
Function encrypt(ByVal originalText, ByVal alphabet, blank1, blank2)
Line 2,680 ⟶ 2,770:
decoded = decrypt(encoded, cipher, 3, 7)
Buffer=Buffer & "decoded: " & decoded & vbCrlf
Wscript.Echo Buffer </
{{out}}
<pre>
Line 2,691 ⟶ 2,781:
{{trans|Kotlin}}
{{libheader|Wren-str}}
<
var board = "ET AON RISBCDFGHJKLMPQ/UVWXYZ."
Line 2,772 ⟶ 2,862:
System.print("Encrypted : %(encrypted)")
System.print("Decrypted : %(decrypted)")
}</
{{out}}
Line 2,799 ⟶ 2,889:
=={{header|zkl}}==
{{trans|D}}
<
val2key=Dictionary(
"A","30", "B","31", "C","32", "D","33", "E","5", "F","34", "G","35",
Line 2,810 ⟶ 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>
|