Skip to content

Commit e88f7c3

Browse files
committed
optimized child generation
1 parent 39078ea commit e88f7c3

File tree

1 file changed

+28
-3
lines changed

1 file changed

+28
-3
lines changed

src/main/java/main/java/codingame/TicTacToe/TicTacToe.java

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,14 @@ public int selectChild(final LargeBoard board) {
106106
double maxUtility = child.map(TreeNode::getUtility).orElse(0d);
107107
int bestColumn = child.map(c -> c.col).orElse(0);
108108
final Set<Integer> expandedSet = children.keySet();
109-
for (int i = 0; i < 81; i++) {
109+
final int currentBoardIndex = board.currentBoard();
110+
int max = 81;
111+
int i = 0;
112+
if (currentBoardIndex != -1) {
113+
i = (currentBoardIndex / 3) * 27 + (currentBoardIndex % 3) * 3;
114+
max = i + 21;
115+
}
116+
for (; i < max; i++) {
110117
if (board.canPlay(i) && !expandedSet.contains(i)) {
111118
final double utility = Math.sqrt(Math.log(plays + 1)) + (0.05 / Math.abs(9 / 2.0 - i));
112119
if (utility > maxUtility) {
@@ -126,9 +133,16 @@ private double simulate(final LargeBoard board, int player) {
126133
int numberOfMovesPlayed = board.movesPlayed;
127134
final int originalPlayer = player;
128135
while (board.result() == -1) {
129-
final int possibilities[] = new int[81];
136+
final int currentBoardIndex = board.currentBoard();
137+
int max = 81;
138+
int position = 0;
139+
if (currentBoardIndex != -1) {
140+
position = (currentBoardIndex / 3) * 27 + (currentBoardIndex % 3) * 3;
141+
max = position + 21;
142+
}
143+
final int possibilities[] = new int[max - position];
130144
int movesToPlay = 0;
131-
for (int position = 0; position < possibilities.length; position++) {
145+
for (; position < max; position++) {
132146
if (board.canPlay(position)) {
133147
possibilities[movesToPlay] = position;
134148
movesToPlay++;
@@ -295,6 +309,17 @@ public boolean canPlay(final int p) {
295309
&& (boards[bRow * 3 + bCol].occupied & (1 << (row * 3 + col))) == 0;
296310
}
297311

312+
public int currentBoard() {
313+
if (movesPlayed > 0) {
314+
final int previousMove = moves[movesPlayed - 1];
315+
final int pMoveRow = (previousMove / 9) % 3, pMoveCol = previousMove % 3;
316+
if ((largeOccupied & (1 << (pMoveRow * 3 + pMoveCol))) == 0) {
317+
return pMoveRow * 3 + pMoveCol;
318+
}
319+
}
320+
return -1;
321+
}
322+
298323
@Override
299324
public String toString() {
300325
return "LargeBoard{" +

0 commit comments

Comments
 (0)