Skip to content

Instantly share code, notes, and snippets.

@hakank
Created April 27, 2011 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hakank/944913 to your computer and use it in GitHub Desktop.
Save hakank/944913 to your computer and use it in GitHub Desktop.
SEND + MORE = MONEY in K (Kona)
/ Here are some ways of solving the SEND+MORE=MONEY puzzle
/ in K (Kona).
/ See http://en.wikipedia.org/wiki/SEND_MORE_MONEY
/
/ The first version might not be the best K way, but this
/ declarative version is the on I'm used to from
/ constraint programming etc.
/ perm defined the permutations.
/ E.g.
/ perm 10
/ gives all the permutations of the digits 0..9
perm:{:[1<x;,/(>:'(x,x)#1,x#0)[;0,'1+_f x-1];,!x]}
/ Note the symmetry breaking of the dummy variables a < b
pp@&{[s;e;n;d;m;o;r;y;a;b]((((1000*s)+(100*e)+(10*n)+d) + ((1000*m)+(100*o)+(10*r)+e)) = ((10000*m)+(1000*o)+(100*n)+(10*e)+y)) & (s>0)&(m>0)&(a<b)}.'(pp:perm 10)
/ Result: 9 5 6 7 1 0 8 2 3 4
/ i.e. s:9 e:5 n:6 d:7 m:1 o:0 r:8 y:2
/ The digits 3 and 4 are not used.
/
/ Another approach
/ Here we use an utility function which makes it slightly easier
/ to see the structure of the problem.
/
/ The function f converts a list of digits to the corresponding number
f:{+/(_10^|!#x)*x}
/ Example:
f[(1;2;4;0)]
/ result: 1240
/ Here here's the SEND+MORE=MONEY again
pp@&{[s;e;n;d;m;o;r;y;a;b]((f[(s;e;n;d)]+f[(m;o;r;e)])=f[(m;o;n;e;y)])&(s>0)&(m>0)&(a<b)}.'pp:(perm 10)
/ 9 5 6 7 1 0 8 2 3 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment