Get Longest Run Index FR public int get
Get Longest Run Index (FR) public int get. Longest. Run. Index(int []values) { int max. Run. Start = -1, max. Run. Length = 1; int run. Start = 0, run. Length = 1; for(int i = 1; i <= values. length; i++) { run. Length++; } if(i < values. length && values[i] == values[i-1]) else { { if(run. Length > max. Run. Length) { max. Run. Start = run. Start; max. Run. Length = run. Length; } run. Start = i; run. Length = 1; } } return max. Run. Start; }
2 D Arrays • Two-Dimensional Arrays A two-dimensional array is a table/matrix -- with rows and columns -- where each row is an array, and there are several rows in a table. e. g. a two-dimensional array of 3 rows and 4 columns
Create 2 D Array To create a two-dimensional array, you specify the number of rows (first) and columns (second). int[][] i. Mat = new int[3][4]; // integer matrix of 3 rows, 4 columns double[][] d. Mat = new double[5][3]; // double matrix of 5 rows, 3 columns char[][] c. Mat = new char[3][3]; // char matrix -- 3 rows, 3 columns
Direct Initialization To give initial values for the elements in a twodimensional array, you can of course set up a loop. Another way is to provide the initial values directly in declaration. int[][] i. Mat = { {12, 48, 69, 7} , {5, 16, 27, 30}, {51, 3, 72, 9} };
Access an element in 2 D Array • Each row is an individual array • Column index starts at 0 To access an element in a twodimensional array, you specify the row index (first) and column index (second). System. out. println(i. Mat[0][2]); // prints an element at row 0, column 2 (69 in the example above) i. Mat[2][2] = 5; // assign 5 to row 2, column 1
Length 2 D array • Lengths of a Two-dimensional Arrays can contain different number of column elements at each row. LENGTH OF ROW AND COLUMN The Row length (number of rows in the array) is 0 1 2 3 +----+----+ 0 | 12 | 48 | 69 | 7 | +----+----+ 1 | 5 | 16 | 27 | | +----+----+ 2 | 51 | 3 | | +----+----+ found by using length. int num. Row = mat. length; Array to the side has 3 rows The Column Length is different for each row so you must access the row first then the column length. int column. Length = mat[0]. length // equal 4 int column. Length = mat[1]. length // equal 3
Traversing Over a 2 D Array with for loop Then we can utilize those two lengths to traverse over a two-dimensional array -- also by using a nested loop. Two for loops: First specify the row to loop through and then the column. Use Variables row and col to represent the row and column. int[][] i. Mat = { {12, 48, 69, 7} , int row, col; {5, 16, 27, 30}, for (row = 0; row < matrix. length; row++) {51, 3, 72, 9} }; { for (col = 0; col < matrix[row]. length; col++) System. out. print[matrix[row][col] + “ “ ); } System. out. println(); }
For Wednesday • Finish the 2 worksheets on arrays • Look over notes • Write the algorithms for the program
- Slides: 8