public class NIM {
public static void main(String[] args) {
System.out.println(nim(8, 6));
}
public static Result nim(int m, int n) {
if (m == n || m == 0 || n == 0) {
return new Result(true, m, n);
}
if (m < n) {
int tmp = m;
m = n;
n = tmp;
}
Result[][] matrix = new Result[m][n];
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < m; j++) {
if (matrix[j][i] == null) {
propagateFalseResult(m, n, j, i, matrix);
if (matrix[m - 1][n - 1] != null) {
return matrix[m - 1][n - 1];
}
}
}
}
return matrix[m - 1][n - 1];
}
private static void propagateFalseResult(int m, int n, int x, int y, Result[][] matrix) {
matrix[x][y] = new Result(false, x + 1, y + 1);
Result tResult = new Result(true, x + 1, y + 1);
for (int i = y + 1; i < n; i++) {
matrix[x][i] = tResult;
}
for (int i = x + 1; i < m; i++) {
matrix[i][y] = tResult;
}
int steps = m - x;
if (steps > n - y) {
steps = n - y;
}
for (int i = 1; i < steps; i++) {
matrix[x + i][y + i] = tResult;
}
if (x < n) {
for (int i = x + 1; i < m; i++) {
matrix[i][x] = tResult;
}
}
printMatrix(matrix);
}
private static void printMatrix(Result[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.printf("%-15s", matrix[i][j]);
}
System.out.println();
}
System.out.println();
}
}
class Result {
public String toString() {
return state + " (" + x + ", " + y + ")";
}
public Result(boolean s, int x, int y) {
state = s;
this.x = x;
this.y = y;
}
public boolean state;
public int x, y;
}
[table]
|null|null|null|null|null|null|
|false (2, 1)|true (2, 1)|true (2, 1)|true (2, 1)|true (2, 1)|true (2, 1)|
|true (2, 1)|true (2, 1)|null|null|null|null|
|true (2, 1)|true (2, 1)|true (2, 1)|null|null|null|
|true (2, 1)|true (2, 1)|null|true (2, 1)|null|null|
|true (2, 1)|true (2, 1)|null|null|true (2, 1)|null|
|true (2, 1)|true (2, 1)|null|null|null|true (2, 1)|
|true (2, 1)|true (2, 1)|null|null|null|null|
[/table]
[table]
|null|null|null|null|null|null|
|false (2, 1)|true (2, 1)|true (2, 1)|true (2, 1)|true (2, 1)|true (2, 1)|
|true (2, 1)|true (2, 1)|null|null|null|null|
|true (2, 1)|true (2, 1)|true (2, 1)|null|null|null|
|true (2, 1)|true (2, 1)|false (5, 3)|true (5, 3)|true (5, 3)|true (5, 3)|
|true (2, 1)|true (2, 1)|true (5, 3)|true (5, 3)|true (5, 3)|null|
|true (2, 1)|true (2, 1)|true (5, 3)|null|true (5, 3)|true (2, 1)|
|true (2, 1)|true (2, 1)|true (5, 3)|null|true (5, 3)|true (5, 3)|
[/table]
true (5, 3)