Lecture Notes for Chapter 7

advertisement
Computer Science Notes
Chapter 7
Page 1 of 10
Chapter 7: Multidimensional Arrays
These notes are meant to accompany Introduction to Java Programming: Brief Version, eighth edition by Y.
Daniel Lang.
Programming Skills in a Nutshell:
At the end of this chapter you should have the following programming skills:
1. To recognize when a block of information could best be stored as a two-dimensional array.
2. To manipulate the array correctly or perform calculations using the array using nested loops.
3. Here is a template that uses the key programming skills you should have at this point:
Write a program that does length conversions between inches, feet, cm, and meters using a 2D array.
1 foot = 12 inches
1 inch = 2.54 cm
1 meter = 100 cm
Convert row to
column by
multiplying by:
Inches
[0]
Feet
[1]
Centimeters
[2]
Meters
[3]
Inches
[0]
Feet
[1]
Centimeters
[2]
Meters
[3]
1
1/12 (i.e., divide by
12)
1
2.54
2.54 / 100
12 * 2.54
12 * 2.54 / 100
1 / 2.54 / 12
1
100 / 2.54 / 12
100
1 / 100 (i.e., divide
by 100)
1
12
1 / 2.54 (i.e., divide
by 2.54)
100 / 2.54
import java.util.Scanner;
/**
* The Chap07Basics class implements an application that
* converts length measurement units, and illustrates the basics of working
* with two-dimensional arrays.
* This is meant as an example of the material in Chapter 7 of the text
* _Introduction to Java Programming: Brief Version_, 8th ed. by Y. D. Liang
* @author Kevin Mirus
*/
public class Chap07Basics
{
/**
* @param args is not used
*/
public static void main(String[] args)
{
final int INCHES = 0;
final int FEET = 1;
final int CENTIMETERS = 2;
final int METERS = 3;
String[] unitNames = {"inches", "feet", "centimeters", "meters"};
/*
double[][] conversionFactors = new double[4][4];
initalizeArray(conversionFactors, INCHES, FEET, CENTIMETERS, METERS);
Computer Science Notes
Chapter 7
Page 2 of 10
*/
double[][] conversionFactors = initializeArray();
print2DArray(conversionFactors);
Scanner keyboard = new Scanner(System.in);
double oldUnitValue, newUnitValue;
int oldUnit, newUnit;
System.out.println("This program converts length units");
/*
System.out.println("Enter " + INCHES + ") for inches as the old unit.");
System.out.println("Enter " + FEET + ") for feet as the old unit.");
System.out.println("Enter " + CENTIMETERS + ") for centimeters as the old
unit.");
System.out.println("Enter " + METERS + ") for meters as the old unit.");
*/
for (int i = 0; i < unitNames.length; i++)
System.out.println("Enter " + i + ") for " + unitNames[i] + " as the
old unit.");
oldUnit = keyboard.nextInt();
System.out.println("Enter the amount of that unit");
oldUnitValue = keyboard.nextDouble();
/*
System.out.println("Enter " + INCHES + ") for inches as the new unit.");
System.out.println("Enter " + FEET + ") for feet as the new unit.");
System.out.println("Enter " + CENTIMETERS + ") for centimeters as the new
unit.");
System.out.println("Enter " + METERS + ") for meters as the new unit.");
*/
for (int i = 0; i < unitNames.length; i++)
System.out.println("Enter " + i + ") for " + unitNames[i] + " as the
new unit.");
newUnit = keyboard.nextInt();
newUnitValue = oldUnitValue * conversionFactors[oldUnit][newUnit];
System.out.println(oldUnitValue + " " + unitNames[oldUnit] + " = " +
newUnitValue + " " + unitNames[newUnit]);
}
/**
* Prints all elements is a two-dimensional array
* @param array is the 2-D array to print
*/
public static void print2DArray(double[][] array)
{
for (int row = 0; row < array.length; row++)
{
for (int col = 0; col < array[0].length; col++)
{
System.out.printf("%10.5f ", array[row][col]);
}
System.out.println();
}
Computer Science Notes
Chapter 7
Page 3 of 10
}
/**
* Puts the appropriate conversion factors into the appropriate array elements.
* @param array
* @param inches
* @param feet
* @param centimeters
* @param meters
*/
public static void initalizeArray(double[][] array, int inches, int feet, int
centimeters, int meters)
{
array[inches][inches] = 1;
array[inches][feet] = 1. / 12;
array[inches][centimeters] = 2.54;
array[inches][meters] = 2.54 / 100;
array[feet][inches] = 12;
array[feet][feet] = 1;
array[feet][centimeters] = 12 * 2.54;
array[feet][meters] = 12 * 2.54 / 100;
array[centimeters][inches] = 1 / 2.54 ;
array[centimeters][feet] = 1 / 2.54 / 12;
array[centimeters][centimeters] = 1;
array[centimeters][meters] = 1. / 100;
array[meters][inches] = 100 / 2.54;
array[meters][feet] = 100 / 2.54 / 12;
array[meters][centimeters] = 100;
array[meters][meters] = 1;
}
public static double[][] initializeArray()
{
/*
double[][] cF = {
{1, 1./12, 2.54, 2.54/100},
{12, 1, 12*2.54, 12 * 2.54 / 100},
{1/2.54, 1/2.54/12, 1, 1./100},
{100/2.54, 100/2.54/12, 100, 1} };
*/
//return cF;
//return a new, anonymous array with the values stored in it.
return new double[][] {
{1, 1./12, 2.54, 2.54/100},
{12, 1, 12*2.54, 12 * 2.54 / 100},
{1/2.54, 1/2.54/12, 1, 1./100},
{100/2.54, 100/2.54/12, 100, 1} };
}
}
Computer Science Notes
Chapter 7
Page 4 of 10
Book’s Statement of Skills:
1. To give examples of representing data using two-dimensional arrays (7.1)
2. To declare variables for two-dimensional arrays, create arrays, and access array elements in a twodimensional array using row and column indexes (7.2)
3. To program common operations for two-dimensional arrays (displaying arrays, summing all elements,
finding min and max elements, and random shuffling) (7.3)
4. To pass two-dimensional arrays to methods (7.4)
5. To write a program for grading multiple-choice questions using two-dimensional arrays (7.5)
6. To solve the closest-pair problem using to-dimensional arrays (7.6)
7. To check a Sudoku solution using two-dimensional arrays. (7.7)
8. To use multi-dimensional arrays. (7.8)
Computer Science Notes
Chapter 7
Page 5 of 10
Section 7.1: Introduction
.
Section 7.2: Two-Dimensional Array Basics

A two-dimensional array is used to store a matrix or a table of values, like the color of each pixel on a
monitor, a table of distances between pairs of cities, or a tic-tac-toe board.
Section 7.2.1: Declaring Variables of Two-Dimensional Arrays and Creating Two-Dimensional Arrays

Syntax for declaring a two-dimensional array:
dataType[][] arrayRefVar;
//Example
int[][] matrix;

To create a two-dimensional array, use the new keyword with the dimension of the rows and columns:
//Example
matrix = new int[4][3];
[0]
[1]
[2]
[0]
0
0
0
[1]
0
0
0
[2]
0
0
0
[3]
0
0
0

To assign a value to an element, use an index pair:
//Example
matrix[2][1] = 7;
[0]
[1]
[0]
0
0
[1]
0
0
[2]
0
7
[3]
0
0
[2]
0
0
0
0
Computer Science Notes

Chapter 7
Page 6 of 10
To declare, create, and initialize a two-dimensional array, use nested sets of values in {}:
//Example
int[][] matrix = {{1, 2, 3}, {3, 2, 1}, {0, 0, 0}, {8, 5, 9}};
[0]
[1]
[2]
[0]
1
2
3
[1]
3
2
1
[2]
0
0
0
[3]
8
5
9
Section 7.2.2: Obtaining the Lengths of Two-Dimensional Arrays

A two-dimensional array is actually a one-dimensional array of one-dimensional arrays…
//Example
System.out.println(matrix.length);
//Prints 4 because there are 4 rows
System.out.println(matrix[0].length);
//Prints 3 because there are 3 columns in the first row
System.out.println(matrix[1].length);
//Prints 3 because there are 3 columns in the second row
System.out.println(matrix[2].length);
//Prints 3 because there are 3 columns in the third row
System.out.println(matrix[3].length);
//Prints 3 because there are 3 columns in the fourth row
Section 7.2.3: Ragged Arrays

A ragged array is a two-dimensional array in which each row has a different number of elements.
//Example
int[][] triangleArray = {{1, 2, 3}, {3, 2}, {0}};
[0]
[1]
[2]
[0]
1
2
3
[1]
3
2
N/A
[2]
0
N/A
N/A
//Example
System.out.println(matrix.length);
//Prints 3 because there are 3 rows
System.out.println(matrix[0].length);
//Prints 3 because there are 3 columns in the first row
System.out.println(matrix[1].length);
//Prints 2 because there are 2 columns in the second row
System.out.println(matrix[2].length);
//Prints 1 because there is 1 column in the third row
Computer Science Notes
Chapter 7
Page 7 of 10
Section 7.3: Processing Two-Dimensional Arrays

Use nested loops
Two-Dimensional Array Algorithms: Initializing a two-dimensional array with random values
int[][] matrix = new int[10][10];
//Initialize the array with random numbers.
for (int row = 0; row < matrix.length; row++)
for (int col = 0; col < matrix[row].length; col++)
matrix[row][col] = (int)(Math.random() * 10);
Two-Dimensional Array Algorithms: Printing a two-dimensional array (you have to print each element
separately)
int[][] matrix = new int[10][10];
//Print the array.
System.out.println("Here are the elements of the array");
for (int row = 0; row < matrix.length; row++)
{
for (int col = 0; col < matrix[row].length; col++)
System.out.print(matrix[row][col] + " ");
System.out.println();
}
Here are the elements of the array
5 6 7 7 8 3 2 7 7 2
7 0 9 6 0 7 3 9 2 9
6 9 2 4 2 8 2 7 0 0
4 1 8 0 9 7 4 9 5 2
3 4 2 6 8 6 1 3 7 2
4 8 6 8 5 2 9 2 5 1
2 5 9 1 9 6 3 0 4 7
1 3 9 4 0 7 1 8 9 2
3 2 2 8 1 2 0 8 8 7
1 3 2 3 6 8 8 3 6 7
Two-Dimensional Array Algorithms: Summing a two-dimensional array
int[][] matrix = new int[10][10];
//Compute the sum of all elements in the array.
double sum = 0.0;
for (int row = 0; row < matrix.length; row++)
for (int col = 0; col < matrix[row].length; col++)
sum += matrix[row][col];
System.out.println(sum);
465.0
Computer Science Notes
Chapter 7
Page 8 of 10
Two-Dimensional Array Algorithms: Summing rows of a two-dimensional array
int[][] matrix = new int[10][10];
double sum = 0.0;
//Compute the sum of all elements in each row of the array.
for (int row = 0; row < matrix.length; row++)
{
sum = 0.0;
for (int col = 0; col < matrix[row].length; col++)
sum += matrix[row][col];
System.out.println("The sum for row " + row + " = " + sum);
}
The sum for row 0 = 54.0
The sum for row 1 = 52.0
The sum for row 2 = 40.0
The sum for row 3 = 49.0
The sum for row 4 = 42.0
The sum for row 5 = 50.0
The sum for row 6 = 46.0
The sum for row 7 = 44.0
The sum for row 8 = 41.0
The sum for row 9 = 47.0
Two-Dimensional Array Algorithms: Summing columns of a two-dimensional array
int[][] matrix = new int[10][10];
double sum = 0.0;
//Compute the sum of all elements in each column of the array.
for (int col = 0; col < matrix[0].length; col++)
{
sum = 0.0;
for (int row = 0; row < matrix.length; row++)
sum += matrix[row][col];
System.out.println("The sum for column " + col + " = " + sum);
}
The sum for column 0 = 36.0
The sum for column 1 = 41.0
The sum for column 2 = 56.0
The sum for column 3 = 47.0
The sum for column 4 = 48.0
The sum for column 5 = 56.0
The sum for column 6 = 33.0
The sum for column 7 = 56.0
The sum for column 8 = 53.0
The sum for column 9 = 39.0
Computer Science Notes
Chapter 7
Page 9 of 10
Section 7.4: Passing Two-Dimensional Arrays to Methods
Section 7.5: Problem: Grading a Multiple-Choice Test

See http://www.cs.armstrong.edu/liang/intro8e/html/GradeExam.html
Section 7.6: Problem: Finding a Closest Pair

See http://www.cs.armstrong.edu/liang/intro8e/html/FindNearestPoints.html
Section 7.7: Problem: Sudoku

See http://www.cs.armstrong.edu/liang/intro8e/html/CheckSudokuSolution.html
Section 7.8: Multidimensional Arrays

A multidimensional array is an array of arrays of one lower dimension.

Thus, a three-dimensional array is an array of two-dimensional arrays (which is an array of onedimensional arrays).
//Example
public static double[][][] incomeCutoffs
{{{26250.00, 63550.00, 132600.00,
{43850.00, 105950.00, 161450.00,
{21925.00, 52975.00, 80725.00,
{35150.00, 90800.00, 147050.00,
{{27050.00, 65550.00, 136750.00,
{45200.00, 109250.00, 166500.00,
{22600.00, 54625.00, 83250.00,
{36250.00, 93650.00, 151650.00,
=
288350.00,
288350.00,
144175.00,
288350.00,
297350.00,
297350.00,
148675.00,
297350.00,
288350.00}, //SINGLE 2000
288350.00}, //JOINT 2000
144175.00}, //SEPARATE 2000
288350.00}},//HEAD 2000
297350.00}, //SINGLE 2001
297350.00}, //JOINT 2001
148675.00}, //SEPARATE 2001
297350.00}}}//HEAD 2001
Computer Science Notes
Chapter 7
Page 10 of 10
Section 7.8.1: Problem: Daily Temperature and Humidity

See http://www.cs.armstrong.edu/liang/intro8e/html/Weather.html
Section 7.8.2: Problem: Guessing Birth Dates

See http://www.cs.armstrong.edu/liang/intro8e/html/GuessBirthdayUsingArray.html
Download