Problem:
Write a program that randomly fills in 0s and 1s into a TicTacToe board, prints the board, and finds the rows, columns, or diagonals with all 0s or 1s. Use a two-dimensional array to represent a TicTacToe board.
Output:
101
111
110
All 1s on column 0
All 1s on row 1
All 1s on diagonal 1
111
110
All 1s on column 0
All 1s on row 1
All 1s on diagonal 1
Solution:
public class TicTacToe2 { public static int[][] randomFill() { int[][] tictactoe = new int[3][3]; for (int i =0;i<tictactoe.length;i++) { for (int j =0; j< tictactoe[i].length;j++) { tictactoe[i][j] = (int) (Math.random()*2); System.out.print(tictactoe[i][j]); } System.out.println(); } return tictactoe; } public static void checkUp(int[][] tictactoe) { for (int i =0;i<3;i++) { if ( tictactoe[i][0] == tictactoe[i][1] && tictactoe[i][1] == tictactoe[i][2]) System.out.println("All " + tictactoe[i][0] + "s on row " + i); if ( tictactoe[0][i] == tictactoe[1][i] && tictactoe[1][i] == tictactoe[2][i]) System.out.println("All " + tictactoe[0][i] + "s on column " + i); } if ( tictactoe[0][0] == tictactoe[1][1] && tictactoe[1][1] == tictactoe[2][2]) System.out.println("All " + tictactoe[0][0] + "s on diagonal " + 0); if ( tictactoe[1][2] == tictactoe[1][1] && tictactoe[1][1] == tictactoe[2][1]) System.out.println("All " + tictactoe[0][0] + "s on diagonal " + 1); } public static void main (String[] args) { int[][] tictactoe = randomFill(); checkUp(tictactoe); } }
No comments:
Post a Comment