Question 31 X and O Board

  • Collegeboard asks what represents the output of the following code segment that the provide.
String[][] board = new String[5][5];
for(int row = 0; row < 5; row++){
    for(int col = 0; col < 5; col++){
            board[row][col] = "O";
        }
    }

for(int val = 0; val <5; val++){
    if (val % 2 == 1){
        int row = val;
        int col = 0;
        while(col < 5 && row >=0){
            board[row][col] = "X";
            col++;
            row--;
        }
    }
}

The first for loop creates a 5x5 2d array populated ith “O”s. This simulates and creates the board that the second loop edits to insert the “X”s. As seen when the for loop is executed bellow.

String[][] board = new String[5][5];
for (int row = 0; row < 5; row++) {
    for (int col = 0; col < 5; col++) {
        board[row][col] = "O";
    }
}

// Printing board to appear as in the solutions
System.out.print("  ");
for (int col = 0; col < 5; col++) {
    System.out.print(col + " ");
}
System.out.println();

for (int row = 0; row < 5; row++) {
    System.out.print(row + " ");
    for (int col = 0; col < 5; col++) {
        System.out.print(board[row][col] + " ");
    }
    System.out.println();
}

  0 1 2 3 4 


0 O O O O O 
1 O O O O O 
2 O O O O O 
3 O O O O O 
4 O O O O O 
for(int val = 0; val <5; val++){
    if (val % 2 == 1){
        int row = val;
        int col = 0;
        while(col < 5 && row >=0){
            board[row][col] = "X";
            col++;
            row--;
        }
    }
}
  • The second for loop is where all the logic is located for the problem. - Where for each iteration as val which is incremented by 1 per loop, is checked to see if it is odd.
  • If met then then row is set to val.
  • After which we would enter the while loop we would being at the row determined by val which is either 0 or 3 in this case as it the loop iterates through the values 0-4
  • With the diagonal being created by the row being decremented by 1 and columns being incremented by 1 per loop till the edge has been reached. Aka it would be populated from left right. Which we can see below.
for(int val = 0; val <5; val++){
    if (val % 2 == 1){
        int row = val;
        int col = 0;
        while(col < 5 && row >=0){
            board[row][col] = "X";
            col++;
            row--;
        }
    }
}

// Printing board to appear as in the solutions
System.out.print("  ");
for (int col = 0; col < 5; col++) {
    System.out.print(col + " ");
}
System.out.println();

for (int row = 0; row < 5; row++) {
    System.out.print(row + " ");
    for (int col = 0; col < 5; col++) {
        System.out.print(board[row][col] + " ");
    }
    System.out.println();
}


  0 1 2 3 4 
0 O X O X O 
1 X O X O O 
2 O X O O O 
3 X O O O O 
4 O O O O O 

Hacks

What are 2d arrays? How did CollegeBoard manipulate the 2d array, and how might it have been confusing?