2darrays Frq_ipynb_2_
import java.util.Arrays; //more convient for toString
int[] getColumnSums(int[][] input){
//creates a 1d array with a length of # of the columns in the input
int[] temp = new int[input[0].length];
//loop through columns
for (int column = 0; column < input[0].length; column++){
//for each column loop through the rows
for(int row = 0; row < input.length; row++){
//add the column value from each row to the temp array
temp[column] += input[row][column];
}
}
//return the array that is now filled with the column sums
return temp;
}
int[][] grassData = {
{2, 3, 1, 4, 3, 2, 5},
{1, 2, 3, 1, 4, 2, 3},
{3, 4, 2, 5, 1, 3, 2}
};
int[] columnSums = getColumnSums(grassData);
System.out.println(Arrays.toString(columnSums));
[6, 9, 6, 10, 8, 7, 10]
layout: post comments: true title: Period 3 2D Arrays Pt 2 - Sample Problem 2 menu: nav/CSA_Units/frqs/per3-2Darrays-pt2.html permalink: csa/frqs/p3/2darrays2/sample2 —
Sample Problem 2 - Competition!
For this problem, please listen to instructions. There will be an in-class competition which will be an opportunity for extra credit. However, you must complete this problem either way as part of the homework.
Problem
This question involves a path through a two-dimensional (2D) array of integers, where the path is based on the values of elements in the array. When an element of the 2D array is accessed, the first index is used to specify the row and the second index is used to specify the column. The following Location
class represents a row and column position in the 2D array.
public class Location {
private int theRow;
private int theCol;
public Location(int r, int c) {
theRow = r;
theCol = c;
}
public int getRow() {
return theRow;
}
public int getCol() {
return theCol;
}
}
public class GridPath {
/** Initialized in the constructor with distinct values that never change */
private int[][] grid;
public GridPath(int[][] values)
{
grid = values;
}
/**
* Returns the Location representing a neighbor of the grid element at row and col,
* as described in part (a)
* Preconditions: row is a valid row index and col is a valid column index in grid.
* row and col do not specify the element in the last row and last column of grid.
*/
public Location getNextLoc(int row, int col) {
//check for boundries
if(row+1 == this.grid.length && col+1 == this.grid[0].length){
return null; //there is no next location
}
else if(row+1 == this.grid.length){
return new Location(row,col+1); //we can only go right
}
else if(col+1 == this.grid[0].length){
return new Location(row+1,col); //we can only go down
}
else {
if(this.grid[row][col+1]<this.grid[row+1][col]){
return new Location(row,col+1); //value to the right is smaler
} else {
return new Location(row+1,col); //value to the bottom is smaller (or equal)
}
}
}
/**
* Computes and returns the sum of all values on a path through grid, as described in
* part (b)
* Preconditions: row is a valid row index and col is a valid column index in grid.
* row and col do not specify the element in the last row and last column of grid.
*/
public int sumPath(int row, int col) {
Location current = new Location(row,col);
int sum = 0;
while (current != null){ //while the are still in the grid
//add current grid value
sum += this.grid[current.getRow()][current.getCol()];
//set current location to the next location
current = getNextLoc(current.getRow(),current.getCol());
}
return sum;
};
// There may be instance variables, constructors, and methods that are not shown.
}
int[][] values = {
{1,3,5,7,9},
{8,6,4,8,10},
{1,3,5,7,9},
{2,6,4,8,10},
};
GridPath myPath = new GridPath(values);
System.out.println(myPath.sumPath(0,0));
40
Homework
import java.lang.Integer;
public class GrassPasture {
/** The 2D grid of pasture tastineess values */
private int[][] pastures;
/** Constructor initializes the field */
public GrassPasture(int[][] pastures) {
this.pastures = pastures;
}
/**
* Returns sum of total tastiness for all values in 2D array
*/
public int getTotalGrass() {
int sum = 0;
for (int i = 0; i<this.pastures.length;i++){
for(int j = 0; j<this.pastures[i].length;j++){
sum += this.pastures[i][j];
}
}
return sum;
}
/**
* Returns max sum of tastiness of a square in the 2D array (square can be 1x1, 2x2, etc.)
*/
public int maxSquare() {
int currentSquareSize = 1;
int maxSquareValue = Integer.MIN_VALUE;
while(currentSquareSize < this.pastures.length){
//loop through each index, this will be the top left (0,0) of each sqaure
for (int i = 0; i<this.pastures.length;i++){
for(int j = 0; j<this.pastures[i].length;j++){
// check if the subSquare is possible to make from given index
if(i+currentSquareSize-1 < this.pastures.length && j+currentSquareSize-1 < this.pastures.length){
//if it is possible, then get the sum from the subSqaure
int sum = 0;
for(int ii = i; ii<=i+currentSquareSize-1; ii++){
for(int jj = j; jj<=j+currentSquareSize-1; jj++){
sum += this.pastures[ii][jj];
}
}
//if the sum is larger than the current max
if(sum > maxSquareValue){
//then set the max to the sqaure sum
maxSquareValue = sum;
}
}
}
}
//increment the size of the square 1x1 -> 2x2 -> 3x3
currentSquareSize++;
}
return maxSquareValue;
}
/**
* Returns the maximum tastiness sum subarray in the flattened 2D grid
*/
public int maxSubarraySum() {
//create a new array with a length that matched the array of the 2d array
int[] flattenedArray = new int[this.pastures.length * this.pastures[0].length];
//fill in the array with values from the 2d array
for (int i = 0; i<this.pastures.length;i++){
for(int j = 0; j<this.pastures[i].length;j++){
flattenedArray[j + i*this.pastures[i].length] = this.pastures[i][j];
}
}
int subArrayStart = 0; //start at index 0
int subArrayMaxValue = Integer.MIN_VALUE; //start the min as the smallest value possible
while(subArrayStart < flattenedArray.length){
//search through each sub array that starts at the subArrayStart index
int sum = 0;
for(int i = subArrayStart; i<flattenedArray.length;i++){
sum += flattenedArray[i];
//if the sub array sum is larger than the max
if(sum > subArrayMaxValue){
//set the max to the subArraySum
subArrayMaxValue = sum;
}
}
//increment the starting index
subArrayStart++;
}
return subArrayMaxValue;
}
}
public class main{
public static void main(String[] param){
int[][] pastures = {
{-3, 6, -1},
{2, -1, 5},
{-9, 4, -1},
};
GrassPasture gp = new GrassPasture(pastures);
int total = gp.getTotalGrass();
System.out.println("Total Tastiness: " + total);
// answer should be -2
System.out.println("Max Square Sum: " + gp.maxSquare());
// answer should be 9
System.out.println("Max Subarray Sum: " + gp.maxSubarraySum());
// answer should be 11
}
}
main.main(null);
Total Tastiness: 2
Max Square Sum: 9
Max Subarray Sum: 11