CS51 - Fall 2009 - Lecture 27
Book problem 15.4.1
- university enrolls int NUM_STUDENTS students
- students can take one or more courses
- Grades for each course are between 0.0 and 4.0
- Calculate the average for each student:
public int[] getAverage(double[][] grades)
- Note: it's convenient to think about 2D arrays as matrices, but they're not always matrices. Sometimes, you will have rows without the same number of columns. A 2D array is an array of arrays!
Show
TicTacToe demo
- Using a multidimensional array, how can we keep track of the board?
- private int NUM_ROWS = 3;
- private int NUM_COLS = 3;
- 3 by 3 array of integers: int[][] marks = new int[NUM_ROWS][NUM_COLS];
- private int EMPTY_MARK = 0;
- private int X_MARK = 1;
- private int O_MARK = 2;
- How do we check for a win?
- need to check four cases:
- rows all the same
- columns all the same
- top-left to bottom-right diagonal all the same
- top-right to bottom-left diagonal all the same
- Note: when we're checking for a win, we're checking if a particular player has won for the last move
- we know the mark the player made (i.e. X or O)
- we know the row and col position where the mark was made
- Given
LEFT // x value of the left of the board
TOP // y value of the top of the board
CELL_SIZE // the size of the an individual cell in the board
that the user clicked at x, y, which we know is in the board
- How do we figure out what cell/board space the user clicked in?
x = x - LEFT;
y = y - TOP;
int col = (int)(x/CELL_SIZE);
int row = (int)(y/CELL_SIZE);
magic square
- a magic square is an n by n matrix
- containing the numbers 1 through n^2
- such that all the rows, columns and diagonals sum to the same number
take a few minutes and try to do a 3 by 3 magic square
show
MagicSquares demo
- How can we represent a magic square?
- an n by n integer array
- int[][] magicArray = new magicArray[n][n];
- if n is odd, you can build a magic square with the following rules
- put a 1 in the center of the bottom row
- place the next number (i.e. 2 follows 1, etc) in
- the cell one slot below and one slot to the right
- if you fall off the bottom or right, wrap around
- if that cell already has a number, put it in the slot above the original position
show
MagicSquares code
(specifically MagicSquare.fillSquare)