my cool blog

whats up

JAVA FRQs. On 2D Arrays • 49 min read

Description

Help you solve 2d array java problems

changing or adding data for arrays

// Arrays are fixed in size
public class arrayTests {
    // Java standard runtime entry point
    public static void main(String[] args) {    
        // Initialize an array
int[] myArray = {1, 2, 3, 4, 5};

// Change the value at a specific index (e.g., index 2)
myArray[2] = 10;

// Add a new element at the end of the array
int newValue = 6;
myArray = Arrays.copyOf(myArray, myArray.length + 1); //only way to edit this array is to make a copy of it and add our new item to the copied list
myArray[myArray.length - 1] = newValue;
System.out.println(Arrays.toString(myArray)); // Print the array

    }
}
// A method call allows us to execute code that is wrapped in Class

arrayTests.main(null);   // Class prefix allows reference of Static Method
[1, 2, 10, 4, 5, 6]

using arraylists


//ARRAYLISTS ARE RESIZEABLE, ARRAYS ARE FIXED
public class arrayListinfo { // Initialize an ArrayList

public static void main(String[] args) {
    
ArrayList<Integer> myList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

// Change the value at a specific index (e.g., index 2)
myList.set(2, 10);

// Add a new element at the end of the ArrayList
int newValue = 6;
myList.add(newValue);

System.out.println(myList); // Print the ArrayList

}}
arrayListinfo.main(null);
[1, 2, 10, 4, 5, 6]

2D arrays

public class Arraysin2d {
    
    public static void main(String[] args) {
        int[][] myArray = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
    };
    System.out.println(myArray[1][2]); //left is row, right is col, here we go down to row 2 (4,5,6) from the [1], then go to the 6 in column 2 (4,5,6)

    for (int row = 0; row < myArray[0].length; row++) {
        for (int col = 0; col < myArray.length; col++) {
            System.out.print(myArray[row][col] + "\t");
            }
            System.out.println(); // Move to the next column
}

}
}
Arraysin2d.main(null);
6
1	2	3	
4	5	6	
7	8	9	

MY ATTEMPT AT THE FRQ

public class data {
    public static final int MAX = 12 /*change to appropriate value*/;
    private int grid [][];
    
    public void repopulate() {
        for i in grid[][] {
            for j in grid[i] {
                grid[i][j] = random.randint(1,MAX); //random number
                i++;
                j++;}}
    }

    public int countIncreasingCols(){ /* to be implemented in part b */}
    // there may be instances, variables, constructors, and methods not shown
    
}

quickly go over results

  1. the response recieves a point for traversing the grid with the for loops that iterates through rows and columns
  2. the response recieves a point for generating a random integer within max.
  3. the response recieves a point for ensuring the random integer is divisible by 10 but not by 100
  4. the response recieves a point for assigning the values to the grid (2d array)

4 TOTAL POINTS OBTAINABLE IN SECTION A

I forgot to set I to a value or J to a value meaning I miss the 1st point, I also didn’t attempt to add 3. I got 2 at least for including max. I at least get point 4 because I assign a value to the grid correctly, but I should review for loops b/c those threw me off.

2/4 for A

public int countIncreasingCols(){ 
    for i in grid[][] { //idk
        for j in grid[i] {
            if j > grid[i][j-1] {
            count++
        }
    }
    system.out.println("Number of increasing columns: " + count);
}}


explanation

  1. my for loops are really wrong so I cannot traverse the grid correctly, losing 1 point.
  2. I also can’t compare elements in the grid since I don’t access those elements correctly.
  3. I also never correctly determine if column is increasing or not
  4. I miss 2 more points because I didn’t initialize a sum variable and try to store how many columns are ordered
  5. same as 4

I missed a lot of points because I just didn’t have good understanding of java syntax and didn’t really try to solve the problem right. I really needed to calm down and break the problem down instead of panicking and trying what I thought would work and hoping that I could barely pass.

FRQS

2022 FRQS

2022 FRQ ANSWERS

question 4 FRQ ANSWER from 2022 exam

public class data {
    public static final int MAX = 12 /*change to appropriate value*/;
    private int grid [][];
    
    public void repopulate(){

        /* write this in part a */
    
        /* return number of columns in grid that are in increasing order, as described in part b*/
    }

    public int countIncreasingCols(){ /* to be implemented in part b */}
    // there may be instances, variables, constructors, and methods not shown
}

(a): write the repopulate method, which assigns a newly generated random value to each element of grid. each value is to meet all of the following criteria, and all values must have an equal chance of being generated:

- the value is between 0 and MAX (inclusive)
- the value is divisible by 10
- the value is not divisible by 100

Complete the repopulate method.

ANSWER

/**
 * Fills all elements of a grid with randomly generated values, as described in part (a).
 * PRECONDITION: grid is not null. grid has at least 1 element.
 */
public void repopulate() {

    // Loop through each row of the grid
    for (int row = 0; row < grid.length; row++) { 

        // Loop through each column of the grid
        for (int col = 0; col < grid[0].length; col++) {

            // Generate a random integer value between 1 and MAX (inclusive)
            int rval = (int)(Math.random() * MAX) + 1;

            // Ensure that rval is a multiple of 10 and not a multiple of 100
            while (rval % 10 != 0 || rval % 100 == 0) {

                // If rval doesn't meet the criteria, generate a new random value
                rval = (int)(Math.random() * MAX) + 1;

            }

            // Set the generated random value in the current grid element
            grid[row][col] = rval;
        }
    }
}

EXPLANATION

  1. the response recieves a point for traversing the grid with the for loops that iterates through rows and columns
  2. the response recieves a point for generating a random integer in range based on MAX
  3. the response recieves a point for ensuring the random integer is divisible by 10 but not by 100
  4. the response recieves a point for assigning the values to the grid (2d array)

4 TOTAL POINTS OBTAINABLE IN SECTION A

PART B

(b): Write the count IncreasingCols method, which returns the number of columns in grid that are in increasing order. A column is considered to be in increasing order if the element in each row after the first row is greater than or equal to the element in the previous row. A column with only one row is considered to be in increasing order.

The following examples show the count Increasing Cols return values for possible contents of grid.

The return value for the following contents of grid is 1, since the first column is in increasing order but the second and third columns are not. 10 50 40 20 40 20 30 50 30

The return value for the following contents of grid is 2, since the first and third columns are in increasing order but the second and fourth columns are not.

10 540 440 440 220 450 440 190

Complete the count IncreasingCols method.

public int countIncreasingCols() {
    // Initialize a counter to keep track of the number of increasing columns.
    int count = 0;

    // Loop through each column of the grid.
    for (int col = 0; col < grid[0].length; col++) 
    {
        // Assume that the current column is ordered until proven otherwise.
        boolean ordered = true;

        // Loop through each row in the current column starting from the second row (row 1).
        for (int row = 1; row < grid.length; row++) {
            // Check if the current element is less than the element in the previous row
            // in the same column. If so, the column is not ordered.
            if (grid[row][col] < grid[row - 1][col]) 
            {
                ordered = false;
            }
        }

        // If the 'ordered' flag is still true after checking all rows in the column,
        // it means the column is in increasing order, so increment the count.
        if (ordered) 
        {
            count++;
        }
    }

    // Return the count of columns that are in increasing order.
    return count;
}

explanation

  1. 1 point earned for traversing the grid in column major order. You must access the grid correctly to earn this point.
  2. 1 point earned for comparing 2 different elements of the grid correctly, with the if statement.
  3. 1 point earned for determining if a single column is actually increasing order or not, with the “ordered” flag and correct code.
  4. 1 point earned for incrementing the “orderedColumns” counter when a column is determined to be in order.
  5. 1 point earned for correctly returning the number of ordered columns at the end.

completed code but it actually runs

import java.util.Random; // Import the Random class for random number generation

public class Data {
    public static final int MAX = 1000; // Change to the appropriate value (maximum random number)
    private int[][] grid; // Declare a 2D array for the grid

    // Constructor to initialize the grid
    public Data(int rows, int cols) {
        grid = new int[rows][cols];
    }

    // Method to repopulate the grid with random numbers
    public void repopulate() {
        Random rand = new Random(); // Create a Random object for random number generation

        for (int row = 0; row < grid.length; row++) {
            for (int col = 0; col < grid[0].length; col++) {
                int rval;

                do {
                    rval = rand.nextInt(MAX) + 1; // Generate a random number between 1 and MAX
                } while (rval % 10 != 0 || rval % 100 == 0); //uses modulus (%) to eensure number is divisible by 10 but not by 100

                grid[row][col] = rval;
            }
        }
    }

    // Method to count columns with increasing values
    public int countIncreasingCols() {
        int count = 0;

        for (int col = 0; col < grid[0].length; col++) {
            boolean ordered = true;

            for (int row = 1; row < grid.length; row++) {
                if (grid[row][col] < grid[row - 1][col]) {
                    ordered = false;
                    break; // Optimization: No need to check further if not ordered
                }
            }

            if (ordered) {
                count++;
            }
        }

        return count;
    }

    public static void main(String[] args) {
        // Example usage of the Data class
        Data data = new Data(3, 4); // Create a Data object with a 3x4 grid
        data.repopulate(); // Populate the grid with random numbers
        data.printGrid(); // Print the grid
        int increasingCols = data.countIncreasingCols(); // Count columns with increasing values
        System.out.println("Number of columns with increasing values: " + increasingCols);
    }

    // Method to print the grid (added for clarity)
    public void printGrid() {
        for (int[] row : grid) {
            for (int val : row) {
                System.out.print(val + " ");
            }
            System.out.println(); // Move to the next row
        }
    }
}


Data.main(null);
70 320 770 410 
270 310 50 470 
70 180 50 710 
Number of columns with increasing values: 1

key takeaways

1: you must initialize the 2d array as ‘int[][] grid ‘, then you can set it = to arrays of arrays, or use a method to do it

2: printing out the array must be done by going by row and columns.

3: 2d arrays are just nested arrays, so you can access elements like grid[row][col]

4: make sure you initialize all your variables and know how to use for loops to traverse arrays or really do anything.

incredibly important code below!!!

public class Arraysin2d {
    
    public static void main(String[] args) {
        int[][] myArray = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
    };
    System.out.println(myArray[1][2]); //left is row, right is col, here we go down to row 2 (4,5,6) from the [1], then go to the 6 in column 2 (4,5,6)

    for (int row = 0; row < myArray[0].length; row++) {
        for (int col = 0; col < myArray.length; col++) {
            System.out.print(myArray[row][col] + "\t");
            }
            System.out.println(); // Move to the next column
}

}
}
Arraysin2d.main(null);

orginal TIC-TAC-TOE game

import java.util.Scanner;


public class TicTacToeGame { //put entire game in class to use methods

    private static void printBoard(String[] board) {  //optimization by moving printing to method
        System.out.println(board[0] + " | " + board[1] + " | " + board[2]);
        System.out.println(board[3] + " | " + board[4] + " | " + board[5]);
        System.out.println(board[6] + " | " + board[7] + " | " + board[8]);
    }

    private static boolean checkWin(String[] board, String player) { //optimization by moving victory check to method
        int[][] winCombinations = { // 2d array? unit 8?

                {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, // Rows
                {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, // Columns
                {0, 4, 8}, {2, 4, 6}            // Diagonals
                
        };
        for (int[] winCombination : winCombinations) {
            if (board[winCombination[0]].equals(player) &&
                board[winCombination[1]].equals(player) &&
                board[winCombination[2]].equals(player)) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        System.out.println("Tic Tac Toe");
        Scanner scTTT = new Scanner(System.in);
        String[] board = {"1", "2", "3", "4", "5", "6", "7", "8", "9"};
        String player = "X";
        String player2 = "O";
        int turn = 0;
        boolean quit = false;

        System.out.println("Do you want to play against a friend or the computer?");
        System.out.println("Type 1 for friend, 2 for computer");
        int choice = scTTT.nextInt();

        while (!quit) {
            System.out.println("Player " + player + " turn");
            printBoard(board);
            int move = scTTT.nextInt();


            if (board[move - 1].equals("X") || board[move - 1].equals("O")) {
                System.out.println("That square is already taken, try again");
                continue;
            }

            board[move - 1] = player;
            turn++;


            if (checkWin(board, player)) {   // check victory (call checkWin)
                System.out.println("Player " + player + " wins!");
                quit = true;
                break;
            } else if (turn == 9) {
                System.out.println("It's a tie!");
                quit = true;
                break;
            }

            if (choice == 1) {
                player = (player.equals("X")) ? "O" : "X";
            } else if (choice == 2) {
                player = "X";
                int move2 = (int)(Math.random() * 9) + 1;
                while (board[move2 - 1].equals("X") || board[move2 - 1].equals("O")) {
                    move2 = (int)(Math.random() * 9) + 1;
                }
                board[move2 - 1] = player2;

                if (checkWin(board, player2)) {
                    printBoard(board);
                    System.out.println("Computer wins!");
                    quit = true;
                    break;
                } else if (turn == 9) {
                    printBoard(board);
                    System.out.println("It's a tie!");
                    quit = true;
                    break;
                }
            }
        }

        scTTT.close();
    }
}

TicTacToeGame.main(null);

Tic Tac Toe
Do you want to play against a friend or the computer?
Type 1 for friend, 2 for computer
Player X turn
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
Player X turn
X | 2 | 3
4 | 5 | 6
O | 8 | 9
Player X turn
X | 2 | 3
4 | X | O
O | 8 | 9
Player X wins!

TIC-TAC-TOE REWRITTEN WITH 2D ARRAYS

import java.util.Scanner;

public class TicTacToeGame {

    private static void printBoard(String[][] board) {
        // Loop through the 2D array and print the board
        for (int row = 0; row < 3; row++) {
            for (int col = 0; col < 3; col++) {
                System.out.print(board[row][col]);
                if (col < 2) {
                    System.out.print(" | ");
                }
            }
            System.out.println();
            if (row < 2) {
                System.out.println("---------");
            }
        }
    }

    private static boolean checkWin(String[][] board, String player) {
        int[][] winCombinations = {
            {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, // Rows
            {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, // Columns
            {0, 4, 8}, {2, 4, 6}            // Diagonals
        };

        for (int[] winCombination : winCombinations) {
            int row1 = winCombination[0] / 3;
            int col1 = winCombination[0] % 3;
            int row2 = winCombination[1] / 3;
            int col2 = winCombination[1] % 3;
            int row3 = winCombination[2] / 3;
            int col3 = winCombination[2] % 3;

            if (board[row1][col1].equals(player) &&
                board[row2][col2].equals(player) &&
                board[row3][col3].equals(player)) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        System.out.println("Tic Tac Toe");
        Scanner scTTT = new Scanner(System.in);
        String[][] board = { //using a 2d array now for the board
            {"1", "2", "3"},
            {"4", "5", "6"},
            {"7", "8", "9"}
        };
        String player = "X";
        String player2 = "O";
        int turn = 0;
        boolean quit = false;

        System.out.println("Do you want to play against a friend or the computer?");
        System.out.println("Type 1 for friend, 2 for computer");
        int choice = scTTT.nextInt();

        while (!quit) {
            System.out.println("Player " + player + " turn");
            printBoard(board);
            int move = scTTT.nextInt(); 

            int row = (move - 1) / 3; //we traverse the board (2d array) with this
            int col = (move - 1) % 3;

            if (!board[row][col].equals(String.valueOf(move))) {
                System.out.println("That square is already taken, try again");
                continue;
            }

            board[row][col] = player; //append player's move to the board
            turn++;

            if (checkWin(board, player)) {
                System.out.println("Player " + player + " wins!");
                quit = true;
                break;
            } else if (turn == 9) {
                System.out.println("It's a tie!");
                quit = true;
                break;
            }

            if (choice == 1) {
                player = (player.equals("X")) ? "O" : "X";
            } else if (choice == 2) {
                player = "X";
                int move2;
                do {
                    move2 = (int) (Math.random() * 9) + 1;
                    row = (move2 - 1) / 3;
                    col = (move2 - 1) % 3;
                } while (!board[row][col].equals(String.valueOf(move2)));

                board[row][col] = player2;

                if (checkWin(board, player2)) {
                    printBoard(board);
                    System.out.println("Computer wins!");
                    quit = true;
                    break;
                } else if (turn == 9) {
                    printBoard(board);
                    System.out.println("It's a tie!");
                    quit = true;
                    break;
                }
            }
        }

        scTTT.close();
    }
}

TicTacToeGame.main(null);
Tic Tac Toe
Do you want to play against a friend or the computer?
Type 1 for friend, 2 for computer
Player X turn
1 | 2 | 3
---------
4 | 5 | 6
---------
7 | 8 | 9
Player X turn
X | 2 | 3
---------
4 | 5 | 6
---------
7 | 8 | 9
Player X turn
X | 2 | 3
---------
X | 5 | 6
---------
7 | 8 | 9
Player X turn
X | 2 | 3
---------
X | X | 6
---------
7 | 8 | 9
Player X wins!
Scroll to top