Solve the Magic Hexagon A magic hexagon is a hexagon where every row and every diagonal add up to the same value. In this case the value is 38. Each number from 1 to 19 must be used exactly once.



This image shows a solution but I want a program that derives this result.

Your challenge is to solve the magic hexagon as fast as possible. You must derive the result yourself, no hard-coding.
C++

Uses some macros to enumerate the possible values.  (A-S, assigned lexicographically in the problem image.)  m is a bitmask of values that have been used so far.

#include &lt;stdio.h&gt;
#define LOOP(V) for(int V=1;V&lt;20;V++){if(m&amp;1&lt;&lt;V){m&amp;=~(1&lt;&lt;V);
#define ENDLOOP(V) m|=1&lt;&lt;V;}}
#define SET(V,e) int V=e;if(m&amp;1&lt;&lt;V){m&amp;=~(1&lt;&lt;V);
#define UNSET(V) m|=1&lt;&lt;V;}
int main() {
  int m=1048574;
  LOOP(A);
  LOOP(B);
  SET(C,38-A-B);
  LOOP(D);
  SET(H,38-A-D);
  LOOP(G);
  SET(L,38-C-G);
  LOOP(E);
  SET(F,38-D-E-G);
  LOOP(I);
  SET(M,38-B-E-I);
  SET(Q,38-H-M);
  LOOP(J);
  SET(N,38-C-F-J-Q);
  SET(R,38-D-I-N);
  SET(S,38-Q-R);
  SET(P,38-L-S);
  SET(K,38-B-F-P);
  SET(O,38-M-N-P);
  printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n",A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S);
  UNSET(O);
  UNSET(K);
  UNSET(P);
  UNSET(S);
  UNSET(R);
  UNSET(N);
  ENDLOOP(J);
  UNSET(Q);
  UNSET(M);
  ENDLOOP(I);
  UNSET(F);
  ENDLOOP(E);
  UNSET(L);
  ENDLOOP(G);
  UNSET(H);
  ENDLOOP(D);
  UNSET(C);
  ENDLOOP(B);
  ENDLOOP(A);
}


Runs in 30msec and generates the following:

3 17 18 19 7 1 11 16 2 5 6 9 12 4 8 14 10 13 15
3 19 16 17 7 2 12 18 1 5 4 10 11 6 8 13 9 14 15
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
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
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
16 12 10 19 2 4 13 3 7 5 8 15 17 1 6 14 18 11 9
16 19 3 12 2 7 17 10 4 5 1 18 13 8 6 11 15 14 9
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


The 4th line is the example solution.