☰ Contents Nested and 2D Structures

Nested and 2D Structures in Summary

A Theater method int[] freeSeatsPerRow() returns one number per row: how many seats in that row are free. Which loop pattern fits each loop?
The outer loop, over seats:
The inner loop, over one row:
Fill in freeSeatsPerRow.
record Theater(boolean[][] seats) {
int[] freeSeatsPerRow() {
int[] result = ;
int index = 0;
for(boolean[] row: seats) {
int free = 0;
for(boolean seat: row) {
if(seat) { free += 1; }
}


}
return result;
}
}
boolean[] top = { true, false, true, true, true, true };
boolean[] middle = { true, false, false, false, true };
boolean[] bottom = { true, true, false, false };
boolean[][] seats = { top, middle, bottom };
Theater theater = new Theater(seats);
int[] perRow = theater.freeSeatsPerRow();
Someone moves int free = 0; up, above the outer loop, so it runs once before either loop starts. With the same theater, what does theater.freeSeatsPerRow() return now?
  1. [5, 7, 9]
  2. [5, 2, 2]
    That’s the answer with free reset for every row. Now it starts at 0 once, and keeps counting from row to row.
  3. [9, 9, 9]
    result[index] = free; runs right after each row’s inner loop, so each slot gets the count so far, not the final count.
  4. It doesn’t compile
    free is still declared before it’s used, so the program compiles.
countWhite counts the pure white pixels in a raster. Which arguments go to colorAt?
import java.awt.Color;
int countWhite(Raster raster) {
int count = 0;
for(int row = 0; row < raster.height(); row += 1) {
for(int col = 0; col < raster.width(); col += 1) {
if(raster.colorAt().equals(Color.WHITE)) { count += 1; }
}
}
return count;
}
Color[][] stripes = {
{ Color.WHITE, Color.RED, Color.WHITE },
{ Color.RED, Color.RED, Color.BLUE }
};
Raster flag = new Raster(stripes);
int whites = countWhite(flag);