Created
June 20, 2022 21:25
-
-
Save mathieurousseau/2c6aeb3bf9cb48f132d7e6b5a918e99a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TicTacToe { | |
public static boolean valid(String[] plays) { | |
int xCount = 0; | |
int oCount = 0; | |
for (String p : plays) { | |
if (!"x".equals(p) && !"o".equals(p) && !"".equals(p)) { | |
return false; | |
} | |
if ("x".equals(p)) | |
xCount++; | |
if ("o".equals(p)) | |
oCount++; | |
} | |
if (plays.length != 9) | |
return false; | |
if (xCount > oCount + 1 || xCount < oCount - 1) | |
return false; | |
return true; | |
} | |
public static int[][] winningPositions = new int[][] { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }, | |
{ 0, 3, 6 }, { 1, 4, 7 }, { 2, 5, 8 }, | |
{ 0, 4, 8 }, { 2, 4, 6 } }; | |
public static boolean playerWins(String player, String[] plays) { | |
for (int[] valid : winningPositions) { | |
if (player.equals(plays[valid[0]]) && player.equals(plays[valid[1]]) && player.equals(plays[valid[2]])) | |
return true; | |
} | |
return false; | |
} | |
public static String winner(String game) { | |
game = game.toLowerCase(); | |
String[] plays = game.split(",", -1); | |
if (!valid(plays)) { | |
return "Error"; | |
} | |
boolean xWin = playerWins("x", plays); | |
boolean oWin = playerWins("o", plays); | |
if (xWin && oWin) | |
return "Error - 2 winners"; | |
if (xWin) | |
return "X-Winner"; | |
if (oWin) | |
return "O-Winner"; | |
for (String play : plays) { | |
if ("".equals(play)) | |
return "Incomplete"; | |
} | |
return "Tie"; | |
} | |
public static void main(String[] args) { | |
check(winner("o,x,O,,,,,,"), "Incomplete"); | |
check(winner("x,o,x,o,x,o,,o,x"), "X-Winner"); | |
check(winner("x,x,x,o,o,o,x,o,x"), "Error - 2 winners"); | |
check(winner("x,x,x,o,o,o,x,x,x"), "Error"); | |
check(winner("x,o,x,o,x,o,x,o,x"), "X-Winner"); | |
check(winner("x,x,x,o,,o,o,,"), "X-Winner"); | |
check(winner("dsfds"), "Error"); | |
check(winner("x,o,x,"), "Error"); | |
check(winner("x,o,x,a,a,a,a,a,a"), "Error"); | |
check(winner("o,x,o,x,x,o,x,o,x"), "Tie"); | |
check(winner("o,x,o,x,x,o,x,o,"), "Incomplete"); | |
} | |
public static void check(String a, String b) { | |
System.out.println(String.format("%s: %s -> %s", a.equals(b), a, b)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment