/* Rot 13 (Caesar cipher) in CP in Picat. This is a CP version in which the rotation is a variable. (See rot13.pi for a non-cp version.) This program was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import cp. main => go. go => Text = "picatisfun", println(text=Text), TextNum = trans(Text), println(text_num=TextNum), % Rot = 13, rot13(TextNum, Rotated,Rot), println(rotated=Rotated), println(rot=Rot), println(trans(Rotated)), nl, fail, nl. % The valid chars alpha("abcdefghijklmnopqrstuvwxyz"). % Text -> NumList trans(Text) = [I : C in Text,nth(I,Alpha,C)], ascii_alpha(Text[1]) => alpha(Alpha). % NumList -> Text trans(Nums) = [C : I in Nums,nth(I,Alpha,C)], number(Nums[1]) => alpha(Alpha). rot13(Text, Rotated,Rot) => AlphaLen = 26, % length of alphabet Len = Text.len, % string length % the rotated string Rotated = new_list(Len), Rotated :: 1..AlphaLen, Rot :: 1..26, % The rotate number foreach(I in 1..Len) M #= (Text[I] + Rot) mod AlphaLen, M :: 0..AlphaLen-1, M #= 0 #=> Rotated[I] #= AlphaLen, M #> 0 #=> Rotated[I] #= M end, Vars = Rotated ++ [Rot], solve(Vars).