Skip to content

Instantly share code, notes, and snippets.

@martinsson
Last active December 11, 2017 17:38
Show Gist options
  • Save martinsson/a86b301c1e0ab85f92673bbca28b60a9 to your computer and use it in GitHub Desktop.
Save martinsson/a86b301c1e0ab85f92673bbca28b60a9 to your computer and use it in GitHub Desktop.
One-liner solution to the TicTacToe kata ;o)
// Not what I'd call good readable code, but it amuses me ;D
private boolean playerWon(char player, char[] board) {
return of(
// rows
of(0, 1, 2), of(3, 4, 5), of(6, 7, 8),
// columns
of(0, 3, 6), of(1, 4, 7), of(2, 5, 8),
// diagonals
of(0, 4, 8),of(2, 4, 6)
).anyMatch(combination -> combination.allMatch(position -> board[position] == player));
}
// It gets simpler when we replace the concept of board with a list of spots occupied by the player.
// Yet another example of how design gets simpler by the right choice of data-structure.
private Stream<List<Integer>> winningCombinations = Stream.of(
// rows
asList(0, 1, 2), asList(3, 4, 5), asList(6, 7, 8),
// columns
asList(0, 3, 6), asList(1, 4, 7), asList(2, 5, 8),
// diagonals
asList(0, 4, 8), asList(2, 4, 6)
);
private boolean playerWon(List<Integer> playerSpots) {
return winningCombinations.anyMatch(playerSpots::containsAll);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment