Skip to content

Instantly share code, notes, and snippets.

@joriki
Created January 23, 2024 14:21
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 joriki/82df06ead3f464c76138d2faa5abe7e2 to your computer and use it in GitHub Desktop.
Save joriki/82df06ead3f464c76138d2faa5abe7e2 to your computer and use it in GitHub Desktop.
Compute the value of a game of placing non-attacking kings on an n x n board; see https://math.stackexchange.com/questions/4849448.
import java.util.HashMap;
import java.util.Map;
public class Question4849448 {
final static int d = 8;
final static int n = d * d;
static long [] moves = new long [n];
static long [] [] transformedMoves = new long [n] [8];
public static void main(String [] args) {
// prepare moves and transformed moves
for (int i = 0;i < d;i++)
for (int j = 0;j < d;j++) {
long move = 0;
for (int k = Math.max (0,i - 1);k < Math.min (d,i + 2);k++)
for (int l = Math.max (0,j - 1);l < Math.min (d,j + 2);l++)
move |= 1L << (l * d + k);
moves [j * d + i] = move;
int k = i;
int l = j;
int m = 0;
for (int r = 0;r < 2;r++) {
for (int t = 0;t < 4;t++) {
transformedMoves [l * d + k] [m++] = move;
// rotate
int h = k;
k = l;
l = d - h - 1;
}
// reflect
k = d - k - 1;
}
}
for (int i = 0,m = 0;i < d;i++) {
for (int j = 0;j < d;j++,m++)
System.out.print(" " + (wins (transformedMoves [m]) ? '+' : '-'));
System.out.println();
}
}
static Map<Long,Boolean> cache = new HashMap<>();
static boolean wins (long [] state) {
boolean result = !evaluate (state);
for (int i = 0;i < 8;i++)
cache.put(state [i],result);
return result;
}
static boolean evaluate (long [] state) {
long bit = 1;
long position = state [0];
for (int i = 0;i < n;i++,bit <<= 1)
if ((position & bit) == 0) {
long newPosition = position | moves [i];
Boolean result = cache.get(newPosition);
if (result == null) {
long [] copy = state.clone();
for (int j = 0;j < 8;j++)
copy [j] |= transformedMoves [i] [j];
result = wins (copy);
}
if (result)
return true;
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment