CS 110 Arrays II – Multi-dimensional Arrays 1 Copyright C. Tanner 2010 • Organize information in a way that solves more complex problems than can be done with a linear or one dimensional array • 2-dimensioanl array – matrix o simplest o Table o All elements must be of the same data type o Fixed size • Examples o Classroom seating chart 6 desk in a row with 5 rows X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X String [] [] desk = new String [5][6] o Employee Time time Emp Mon Tues Wed Thurs Fri Sat Sun double [] [] timeCard= new double [30][7] o Girl Scout Cookie Orders Customer ThinMints DoSiDoes Treffoils • int [] [] cookieOrders = new int [#customers][3] • Reference a element • Need both row and column index • matrix[r][c] • desk [0][5] – the student’s name in the first row door seat • cookieOrder[3][0] – the number of ThinMints customer 3 ordered custTotal =0 for (int i = 0; i <3; i++) custTotal += cookieOrder[3][i];CS 110 Arrays II – Multi-dimensional Arrays 2 Copyright C. Tanner 2010 • Memory Allocation of 2 dimensional Arrays • Initialization when declared o double matrix [] [] = {{3.2,4.2,1.0}, {5.7,6.1,0.0}} Creates [2][3] • Processing o Nested loops o For each row For each col • Process element [r][c] o [0][0],[0][1],[0][2][1][0][1][2] etc o Row major order o If we switch the loops then we process in column major order • Sum the elements int sumMatrix (int [] [] matrix) { int sum =0; for (int r=0; r<matrix.length;r++0 for (int c=0; c < matrix[r].length;c++) sum += matrix[r][c]; return sum; } • Determining the length of the matrix o Allows for general purpose algorithms o # row Î arrayName.length o # col Î arrayName[row].length Must do this because each row is an array itselfCS 110 Arrays II – Multi-dimensional Arrays 3 Copyright C. Tanner 2010 • Write a general purpose method to print a 2 dimensional array in table format void printMatrix( int [] [] matrix) { for (int r=0;r<matrix.length;r++) { for (int c=0; c<matrix[r].legnth;c++0 System.out.print(matrix[r][c] + “ “); System.out.println(); } } Arrays with more than 2 dimensions o No limit on the number of dimensions o Consider monthly sales for last 5 years for each salesperson sales [person][years][months] Programming Problem Jet Propulsion Laboratory: Take matrix representing digitized representation of night sky and locate stars on it. Each element of the array represents the amount of light hitting that portion of the image when the picture was taken. Intensities range from 0 - 20. A star is located in [i][j] element area if intense[i][j] + sum of surrounding 4/5 > 6.0 0 3 4 0 0 0 6 85 13 6 0 0 0 2 3 2 6 2 7 3 0 10 00 0 4 15 4 1 6 00 0 7 12 6 9 10 45 0 6 10 6 4 8 0 6 x 8 section ignoring edges [1][1] = 13 [0][1] +[1][0]+[2][1]+[1][2]CS 110 Arrays II – Multi-dimensional Arrays 4 Copyright C. Tanner 2010 Sample Program Stars.java Adjacent Elements [i-1][j] [i][j-1] [i][j] [i][j+1]
View Full Document