So this somewhat ugly code crashes spectacularly in the REPL (its own words!), but compiles and executes fine.
Uppercase letters indicate values, I pick from the set to iterate over them. Lowercase letters are generated. z = 38 - X - Y for example, and e = 38 - X - A. With e and J we get n and so on.
/**
X Y z
A B c d
e f g h i
J k l m
n o p
*/
object MagicHexagon extends App {
val set =(1 to 19)toSet
// row 1
for (x <- set;
y <-(set - x);
z = 38 - y - x;
dummy <- ((set - x - y) -- (set - x - y - z));
rest1=(set - x - y - z);
a <- rest1;
e = 38 - x - a;
dummy2 <- ((rest1 - a) -- (rest1 - a - e));
j <- rest1 - a - e;
n = 38 - e - j;
dummy3 <- ((rest1 - a - e - j) -- (rest1 - a - e - j - n));
b <- rest1 - a - e - n;
rest2=(rest1 - a - e - j - n - b);
f = 38 - y - b - j;
dummy4 <- ((rest2) -- (rest2 - f));
c <- rest2 - f;
d = 38 - a - b - c;
dummy5 <- ((rest2 - f - c) -- (rest2 - f - c - d));
i = 38 - z - d;
dummy6 <- ((rest2 - f - c - d) -- (rest2 - f - c - d - i));
rest3 = rest2 - f - c - d - i;
g <- rest3;
h = 38 - e - f - g - i;
dummy7 <- ((rest3 - g) -- (rest3 - g - h));
k = 38 - z - c - g - n;
dummy8 <- ((rest3 - g - h) -- (rest3 - g - h - k));
o = 38 - a - f - k;
rest4 = (rest3 - g - h - k - o);
dummy9 <- ((rest3 - g - h - k) -- rest4);
m = 38 - y - c - h;
dummyA <- (rest4 -- (rest4 - m));
p = 38 - i - m;
dummyB <- (rest4 - m) -- (rest4 - m - p);
l = 38 - j - k - m;
dummyC <- (rest4 - m - p) -- (rest4 - m - p - l);
buf = List( List(" ",x,y,z), List(" ",a,b,c,d), List("",e,f,g,h,i), List(" ",j,k,l,m), List(" ",n,o,p))) {
println (buf.map (_.mkString ("", ", ", "")).mkString ("\n"))
println ()
}
}
The dummy-variables are a kind of hack to allow the loop to terminate prematurely if a generated value doesn't match one of the left values from the set, especially 0 or negative values must be avoided.
Result:
scala MagicHexagon
, 10, 12, 16
, 13, 4, 2, 19
, 15, 8, 5, 7, 3
, 14, 6, 1, 17
, 9, 11, 18
, 10, 13, 15
, 12, 4, 8, 14
, 16, 2, 5, 6, 9
, 19, 7, 1, 11
, 3, 17, 18
, 9, 11, 18
, 14, 6, 1, 17
, 15, 8, 5, 7, 3
, 13, 4, 2, 19
, 10, 12, 16
, 9, 14, 15
, 11, 6, 8, 13
, 18, 1, 5, 4, 10
, 17, 7, 2, 12
, 3, 19, 16
, 3, 19, 16
, 17, 7, 2, 12
, 18, 1, 5, 4, 10
, 11, 6, 8, 13
, 9, 14, 15
, 3, 17, 18
, 19, 7, 1, 11
, 16, 2, 5, 6, 9
, 12, 4, 8, 14
, 10, 13, 15
, 18, 11, 9
, 17, 1, 6, 14
, 3, 7, 5, 8, 15
, 19, 2, 4, 13
, 16, 12, 10
, 18, 17, 3
, 11, 1, 7, 19
, 9, 6, 5, 2, 16
, 14, 8, 4, 12
, 15, 13, 10
, 16, 19, 3
, 12, 2, 7, 17
, 10, 4, 5, 1, 18
, 13, 8, 6, 11
, 15, 14, 9
, 16, 12, 10
, 19, 2, 4, 13
, 3, 7, 5, 8, 15
, 17, 1, 6, 14
, 18, 11, 9
, 15, 13, 10
, 14, 8, 4, 12
, 9, 6, 5, 2, 16
, 11, 1, 7, 19
, 18, 17, 3
, 15, 14, 9
, 13, 8, 6, 11
, 10, 4, 5, 1, 18
, 12, 2, 7, 17
, 16, 19, 3
Runs in 17s on 7y'o' Laptop.
most efficient
? Lowest network traffic, size on HDD, size in RAM or highest speed? If highest speed: Shall we assume a multi core system, or a single CPU? \$\endgroup\$