Skip to content

Instantly share code, notes, and snippets.

@marco-schmidt
Created May 30, 2021 22:43
Show Gist options
  • Save marco-schmidt/2096e517b73d55f69d874d34eca9ece2 to your computer and use it in GitHub Desktop.
Save marco-schmidt/2096e517b73d55f69d874d34eca9ece2 to your computer and use it in GitHub Desktop.
Java application to compute the number of distinct tic-tac-toe games
/**
* Compute number of distinct tic-tac-toe games.
* This is a popular interview question.
* With Java 11+ run as:
* <pre>
* java HowManyTicTacToeGames.java
* </pre>
* @see https://en.wikipedia.org/wiki/Tic-tac-toe
* @author Marco Schmidt
*/
public class HowManyTicTacToeGames
{
public static void main(String[] args)
{
final byte[] data = new byte[9];
final long number = countGames(data, true);
System.out.println(number + " games");
}
private static long countGames(byte[] data, boolean first)
{
if (isOver(data))
{
return 1;
}
long sum = 0;
for (int i = 0; i < 9; i++)
{
if (data[i] == 0)
{
final byte[] a = new byte[9];
System.arraycopy(data, 0, a, 0, 9);
a[i] = first ? (byte) 1 : (byte) 2;
sum += countGames(a, !first);
}
}
if (sum == 0)
{
sum = 1;
}
return sum;
}
private static boolean isOver(byte[] data)
{
return ident(data, 0, 1, 2) || ident(data, 3, 4, 5) || ident(data, 6, 7, 8) || ident(data, 0, 3, 6)
|| ident(data, 1, 4, 7) || ident(data, 2, 5, 8) || ident(data, 0, 4, 8) || ident(data, 2, 4, 6);
}
private static boolean ident(byte[] data, int a, int b, int c)
{
return data[a] != 0 && data[a] == data[b] && data[b] == data[c];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment