Magic Hexagon

Construct a hexagon of the form

  A B C
 L M N D
K R S O E
 J Q P F
  I H G
using each of the numbers 1 to 19 once. The numbers in each of the 5 rows and each of the 10 diagonals should have the same sum.

hexagon:-
  R19=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19],
  remove(A, R19, R18),         
  choose1(C, B, A, R18, R16),
  A > C, % Avoid rotations
  choose1(E, D, C, R16, R14),
  A > E, % Avoid rotations
  choose1(G, F, E, R14, R12),
  A > G, % Avoid rotations
  choose1(I, H, G, R12, R10),
  A > I, % Avoid rotations
  choose1(K, J, I, R10,  R8),
  A > K, % Avoid rotations
  C > K, % Avoid reflections
  calc2(L, A, K, R8, R7),    
  choose2(N, O, B, F, R7, R5),
  calc3(M, D, N, L, R5, R4),  
  calc3(P, D, O, H, R4, R3),  
  calc3(R, J, M, B, R3, R2),  
  calc3(Q, J, P, F, R2, [S]),  
  tab(4),  writes([A,B,C]),
  tab(2), writes([L,M,N,D]),
         writes([K,R,S,O,E]),
  tab(2), writes([J,Q,P,F]),
  tab(4),  writes([I,H,G]), nl,
  fail.
hexagon.

choose1(X, Y, I, P, Q):-remove(X, P, R), Y is 38-X-I, remove(Y, R, Q).

choose2(X, Y, I, J, P, Q):-remove(X, P, R), Y is 38-X-I-J, remove(Y, R, Q).

calc2(X, I, J, P, Q):-X is 38-I-J, remove(X, P, Q).

calc3(X, I, J, K, P, Q):-X is 38-I-J-K, remove(X, P, Q).

writes([]):-nl.
writes([X|Xs]):-fwrite(i, 3, 0, X), tab(1), writes(Xs).

LPA Index     Home Page