Jump to content

Playfair cipher: Difference between revisions

→‎{{header|J}}: Fix to match task specs
m (Promote to task, lots of examples, little controversy)
(→‎{{header|J}}: Fix to match task specs)
Line 740:
 
=={{header|J}}==
{{incorrect|J|TREESTUMP -> TREXSTUMPX, should be TREXESTUMP}}
Rather than implement two versions of the rules, one for encrypt, one for decrypt, let's just make a lookup table (mapping character pairs to character pairs). To decrypt we can look up in the other direction.
 
'''Implementation:'''
<lang J>choose=:3 :0verb define
 
sel=. 'Q' e. y
<lang J>choose=:3 :0
alph=: (sel { 'JQ') -.~ a. {~ 65 + i.26
sel=. 'Q'e.y
norm=: [: dedouble alph restrict ('I' I.@:=&'J'@]} ])`(-.&'Q')@.sel@toupper
alph=:(sel{'JQ')-.~a.{~65+i.26
norm=: alph restrict('I' I.@:=&'J'@]} ])`(-.&'Q')@.sel@toupper
''
)
 
restrict=: ] -. -.~
dedouble=: verb define
while. +./ msk=. =/"1 ] _2 ]\ y do.
y =. (1 2 p. I. msk) ({. , 'X' , }.) y
end.
y
)
 
choose 'Q'
 
setkey=:3 :0verb define
key=. ~.norm y,alph
ref=: ,/ 2{."1 ~."1 (,"0/~ alph) ,"1 norm 'XQV'
mode=. #. =/"2 inds=. 5 5#:key i. ref
inds0=. (0 3,:2 1)&{@,"2 inds
inds1=. 5|1 0 +"1 inds NB. same column
inds2=. 5|0 1 +"1 inds NB. same row
alt=: key {~ 5 #. mode {"_1 inds0 ,"2 3 inds1 ,:"2 inds2
i. 0 0
)
 
pairs=: 3verb define :0
2{."1 -.&' '"1 ~."1 (_2]\ norm y) ,"1 'XQV'
)
 
encrypt=:3 :0verb define
,;:inv ;/ alt{~ref i. pairs y
)
 
decrypt=:3 :0verb define
,;:inv ;/ ref{~alt i. pairs y
)</lang>
 
'''Example use:'''
 
<lang J> choose 'IJ'
 
setkey 'playfair example'
encrypt 'Hide the gold in the tree stump'
BM OD ZB XD NA BE KU DM UI XM MO UV IF
BMODZBXDNABEKUDMUIXMKZZRYI
decrypt 'BMODZBXDNABEKUDMUIXMKZZRYIBM OD ZB XD NA BE KU DM UI XM MO UV IF'
HI DE TH EG OL DI NT HE TR EX ES TU MP</lang>
HIDETHEGOLDINTHETREXSTUMPX</lang>
 
=={{header|Java}}==
892

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.