/* Enigma 1224 - Age-changingin Picat. From Enigma 1224: Age-changing https://enigmaticcode.wordpress.com/2015/06/20/enigma-1224-age-changing/ """ From New Scientist #2380, 1st February 2003 If you start with my age, in years, and apply the four operations: [ +2 /8 -3 *7 ] in some order, then the final answer you get is my husband’s age in years. Funnily enough, if you start with his age and apply the same four operations in a different order, then you get my age. What are our two ages? """ Using two different approaches: - strings and parse_term (go/0) - function + logic (go2/0) This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import util. main => go. % As strings and parse_term/1 go ?=> Ops = ["+2", "/8", "-3", "*7"], between(16,110,M), % Calculate husband's age permutation(Ops,Permute1), H = f(M,Permute1), ceiling(H) == truncate(H), % Check with my age permutation(Ops,Permute2), Permute1 != Permute2, P2 = f(truncate(H),Permute2), ceiling(P2) == truncate(P2), truncate(P2) == truncate(M), println(myAge=M), println(permute1=Permute1), println(husbandsAge=truncate(H)), println(permute2=Permute2), println(check=truncate(P2)), nl, fail, nl. go => true. % Functional + logic approach go2 => Ops = [g1,g2,g3,g4], % my age between(16,110,M), permutation(Ops,Ops1), chain(Ops1,M,P1), ceiling(P1) == truncate(P1), permutation(Ops,Ops2), Ops1 != Ops2, chain(Ops2,truncate(P1),P2), ceiling(P2) == truncate(P2), truncate(P2) == M, H = truncate(P1), % husband's age println(ops1=Ops1), println(ops2=Ops2), println([M,H]), nl, fail, nl. % % for go/0 % f(X,P) = N => % TT = "((((" ++ X.to_string() ++ P.join(')') ++ ")", TT = ["(" : _ in 1..P.len].join('') ++ X.to_string() ++ P.join(')') ++ ")", PT = parse_term(TT), N = apply(PT). % % for go2/0 % g1(X) = X + 2. g2(X) = X / 8. g3(X) = X - 3. g4(X) = X * 7. chain([],Acc0,Acc) => Acc = Acc0. chain([F|Fs],Acc0,Acc) => Acc1 = apply(F,Acc0), chain(Fs,Acc1,Acc).