/* Mystery Number in Picat. From MindYourDecisions """ N is a three-digit number. The digits of N can be swapped to give five new numbers. If we add these five numbers, we get 2022. What is the value of N ? """ Picat> between(100,999,N),A=N.to_string,permutations(A).map(to_int).sum-N==2022 N = 642 A = ['6','4','2'] ?; This program was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import util. import cp. main => go. go ?=> between(100,999,N), permutations(N.to_string).map(to_int).sum - N == 2022, println(N), fail, nl. go => true. /* This is a very complex way of doing the same thing: ns = [642,246,264,426,462,624] xs = {{6,4,2},{2,4,6},{2,6,4},{4,2,6},{4,6,2},{6,2,4}} ps = {{1,2,3},{3,2,1},{3,1,2},{2,3,1},{2,1,3},{1,3,2}} CPU time 0.129 seconds. Backtracks: 0 */ go2 ?=> Ns = new_list(6), Ns :: 100..999, % Digits representation of Ns Xs = new_array(6,3), Xs :: 0..9, % Permutations Ps = new_array(6,3), Ps :: 1..3, all_different(Ns), increasing(Ns.tail), % Symmetry breaking foreach(I in 1..6) to_num(Xs[I],10,Ns[I]), permutation3(Xs[1],Ps[I],Xs[I]), all_different(Ps[I]) end, Ps[1] #= {1,2,3}, % only CP accepts this % Ps[1,1] #= 1, Ps[1,2] #= 2, Ps[1,3] #= 3, % The rest of the numbers sums to 2022 sum(Ns.tail) #= 2022, Vars = Ns ++ Xs ++ Ps, solve($[constr,split],Vars), println(ns=Ns), println(xs=Xs), println(ps=Ps), nl, fail, nl. go2 => true. /* Are there more puzzles like that for years between 1900..2100: Yes 1900 = 542 1904 = 316 1909 = 533 1913 = 307 1914 = 750 1918 = 524 1923 = 741 1927 = 515 1932 = 732 1936 = 506 1940 = 280 1941 = 723 1946 = 940 1949 = 271 1950 = 714 1955 = 931 1958 = 262 1959 = 705 1964 = 922 1967 = 253 1972 = 470 1973 = 913 1976 = 244 1981 = 461 1982 = 904 1985 = 235 1990 = 452 1994 = 226 1999 = 443 2003 = 217 2004 = 660 2008 = 434 2012 = 208 2013 = 651 2017 = 425 2022 = 642 2026 = 416 2030 = 190 2031 = 633 2035 = 407 2036 = 850 2039 = 181 2040 = 624 2045 = 841 2048 = 172 2049 = 615 2054 = 832 2057 = 163 2058 = 606 2062 = 380 2063 = 823 2066 = 154 2071 = 371 2072 = 814 2075 = 145 2080 = 362 2081 = 805 2084 = 136 2089 = 353 2093 = 127 2094 = 570 2098 = 344 */ go3 ?=> between(1900,2100,S), between(100,999,N), permutations(N.to_string).map(to_int).sum - N == S, println(S=N), fail, nl. go3 => true. % The permutation from A <-> B using the permutation P permutation3(A,P,B) => foreach(I in 1..A.length) % B[I] #= A[P[I]] PI #= P[I], BI #= B[I], element(PI, A, BI) end. % Converts a number Num to/from a list List of integers given a base Base to_num(List, Base, Num) => Len = length(List), Num #= sum([List[I]*Base**(Len-I) : I in 1..Len]). to_num(List, Num) => to_num(List, 10, Num).