/* Scrambled sum in Picat. From Alex Bellos "Can you solve it? The srcmalbed nmebur plzuze" https://www.theguardian.com/science/2020/nov/16/can-you-solve-it-the-srcmalbed-nmebur-plzuze """ Yuor fsrit tsak is to udnretsnad tihs sntecnee As mnay of you wlil be aarwe, to raed a txet the oedrr in wihch the lrtetes of ecah idniadiuvl wrod aepapr is not ipmotanrt, so lnog as the fsrit and lsat ltetres are crorect. Tihs is ovboisuly not the csae wtih nmuebrs beacsue if one slcarbmes the iretnnal ditgis of a nmbeur, it is not pissolbe to wrok out waht the ogirianl nemubr was. Go fugrie. Tehre are, hwoveer, cirtaen cesas in wchih tehre is sufuficnet inmoartfion to fnid out the onriiagl neumbrs, scuh as in the sum bolew. The itenarnl diigts of ecah of the nmbeurs hvae been srcmalbed but the fsrit and lsat dgitis rmaein the smae. Can you rseotre the oigrianl atdiiodn and its sum? 3 4 6 1 4 5 2 8 7 6 + 7 2 5 4 8 ------------ 1 8 7 3 0 8 For those who weren’t able to read the above: the numbers in this addition have been changed. For each number, the first and last digit remained the same, but the middle digits have been scrambled. Recreate the original addition. The above problem was devised by Bernardo Recamán, a Colombian maths teacher, and his students. It features in his lovely new book, The Bogotá Puzzles. Bernardo is probably best known in recreational maths circles as the inventor of the (slightly spooky) Recamán sequence. """ This Picat model was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import cp. main => go. go ?=> R1 = [3,4,6,1,4], scramble(R1,_P1,_Sol1,N1), R2 = [5,2,8,7,6], scramble(R2,_P2,_Sol2,N2), R3 = [7,2,5,4,8], scramble(R3,_P3,_Sol3,N3), S = [1,8,7,3,0,8], scramble(S,_PS,_SolS,NS), NS #= N1+N2+N3, % Note: No solve is needed! % Vars = P1 ++ P2 ++ P3 ++ PS ++ Sol1 ++ Sol2 ++ Sol3 ++ SolS ++ [NS,N1,N2,N3], % solve(Vars), println([n1=N1,n2=N2,n3=N3,ns=NS]), % println([p1=P1,p2=P2,p3=P3,ps=PS]), nl, fail, nl. go => true. % (Un)scramble the line: % Generate a permutation (P) from R (orignal list) to Sol (the solution list) % which yield the number N. scramble(R,P,Sol,N) => Len = R.length, P = new_list(Len), P :: 1..Len, P[1] #= 1, P[Len] #= Len, all_different(P), Sol = new_list(Len), Sol :: R, permutation3(R,P,Sol), to_num(Sol,10,N). % The permutation from A <-> B using the permutation P permutation3(A,P,B) => foreach(I in 1..A.length) PI #= P[I], BI #= B[I], element(PI, A, BI) end. % % converts a number Num to/from a list of integer List given a base Base % to_num(List, Base, Num) => Len = length(List), Num #= sum([List[I]*Base**(Len-I) : I in 1..Len]).