/* Substitution cipher (Rosetta code) in Picat. http://rosettacode.org/wiki/Substitution_cipher """ """ This program was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ % import v3_utils. % import util. % import cp. main => go. go ?=> S = "The quick brown fox jumped over the lazy dog", cypher(S,E), println(E), cypher(D, E), println(D), S == D, println(ok), nl. go => true. % {{trans|Prolog) cypher(O, S) :- nonvar(O), var(S), sub_chars(O,S). cypher(O, S) :- nonvar(S), var(O), sub_chars(O,S). base("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz "). subs("VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWob LkESYMTN"). sub_chars(Original,Subbed) :- base(Base), subs(Subs), maplist($sub_char(Base,Subs),Original,Subbed). sub_char([Co|_],[Cs|_],Co,Cs) :- !. sub_char([_|To],[_|Ts], Co, Cs) :- sub_char(To,Ts,Co,Cs). maplist(Goal, List1, List2) :- maplist_(List1, List2, Goal). maplist_([], X, _) :- X = []. maplist_([Elem1|Tail1], [Elem2|Tail2], Goal) :- call(Goal, Elem1, Elem2), maplist_(Tail1, Tail2, Goal). % Using maps % Using the same base/1 and subs/1 as above go2 => S = "The quick brown fox jumped over the lazy dog!!!", E = encrypt(S), println(E), D = decrypt(E), println(D), % checking D == S, println(ok), nl. encrypt(L) = [EncryptMap.get(C,C) : C in L] => base(Base), subs(Subs), EncryptMap = new_map([B=S : {B,S} in zip(Base,Subs)]). decrypt(L) = [DecryptMap.get(C,C) : C in L] => base(Base), subs(Subs), DecryptMap = new_map([S=B : {B,S} in zip(Base,Subs)]).