Unit 8 ArrayList Notes:

Creating a 2D Array

int[][] numbers = // initialize array here;

Iteration

  • Use a for loop. First iterate through the rows, then iterate over the columns
for(int i = 0; i< array.length; i++) {
    for(int j = 0; j < array[i].length; j++) {
        // code here
    }
}
  • Printing backwards:
for(int i = array.length-1; i>=0; i--) {
    for(int j = array[i].length-1; j>= 0; j--) {
        // code here
    }
}

2019 FRQ 4:

public class Lightboard {
    private boolean[][] lights;

    // part a
    public Lightboard(int numRows, int numCols) {
        lights = new boolean[numRows][numCols];

        for(int r = 0; r < numRows; r++) {
            for(int c = 0; c < numCols; c++) {
                double random = Math.random() * 4;

                lights[r][c] = random < 0.4;
            }
        }
    }

    // part b
    public boolean evaluateLight(int row, int col) {
        int columnLightsOn = 0;

        for(int light = 0; light < col; light++) {
            if(lights[row][light]) {
                columnLightsOn++;
            }
        }

        if(lights[row][col] && columnLightsOn % 2 == 0) {
            return false; 
        }

        if(!lights[row][col] && columnLightsOn % 3 == 0) {
            return true;
        }
        
        return lights[row][col];
    }

    public static void main(String[] args) {
        Lightboard newBoard = new Lightboard(5, 5);

        System.out.println(newBoard.evaluateLight(0,0));
    }
}

Lightboard.main(null);
true

Extra: Mosaic Board

Trust me, it's cool.

public class Mosaic {
    private String[][] characters;

    // part a
    public Mosaic(int numRows, int numCols) {
        lights = new boolean[numRows][numCols];

        for(int r = 0; r < numRows; r++) {
            for(int c = 0; c < numCols; c++) {
                double random = Math.random() * 4;

                lights[r][c] = random < 0.4;
            }
        }
    }

    // part b
    public boolean evaluateLight(int row, int col) {
        int columnLightsOn = 0;

        for(int light = 0; light < col; light++) {
            if(lights[row][light]) {
                columnLightsOn++;
            }
        }

        if(lights[row][col] && columnLightsOn % 2 == 0) {
            return false; 
        }

        if(!lights[row][col] && columnLightsOn % 3 == 0) {
            return true;
        }
        
        return lights[row][col];
    }

    public static void main(String[] args) {
        Lightboard newBoard = new Mosaic(5, 5);

        System.out.println(newBoard.evaluateLight(0,0));
    }
}

Lightboard.main(null);