Monkeys Hacks
- Hack: Create method that sets all elements in array to n
- Hack: Find the average number of a diagonal in a 2d array
void setArray(int[] arr, int n) {
// your code here
}
int[] array = new int[10];
setArray(array, 10);
for (int i = 0; i < array.length; i++) {
array[i] = 10;
System.out.println(array[i]);
}
// Should print all 10s when working properly
//Example finding the max in an array.
//Finds the maximum in an array
public static int average(int[] array) {
// put your code here
int total = 0;
for (int i = 0; i < array.length; i++) {
total += array[i];
}
return total / array.length;
}
//tester array
int[] test = {3, 5, 7, 2, 10};
//returns 10
System.out.println(average(test));
public static int averageDiagonal (int[][] arr) {
int total = 0;
int count = 0;
for (int row = 0; row < arr.length; row++){
for (int col = 0; col < arr[row].length; col++){
if (row == col) {
total += arr[row][col];
count ++;
}
}
}
return total / count;
}
int[][] arr = {
{1,2,3,4,5,6},
{7,8,9,10,11,12},
{0,1,2,3,4,5},
{10,11,12,13,14,15},
{15,16,17,18,19,20}
};
System.out.println(averageDiagonal(arr));
public class HighSum {
public static int highestSum(int[][] arr) {
int maxSum = -1; // initialize with -1, since all sums are non-negative
int rowSum = 0;
int colSum = 0;
for (int i = 0; i < arr.length; i++) {
rowSum = 0;
colSum = 0;
for (int j = 0; j < arr[i].length; j++) {
rowSum += arr[i][j];
colSum += arr[j][i];
}
if (rowSum > maxSum) {
maxSum = rowSum;
}
if (colSum > maxSum) {
maxSum = colSum;
}
}
return maxSum;
}
public static void main(String[] args) {
int[][] arr = {
{12,5,19},
{2,26,11},
{34,8,16}
};
System.out.print(highestSum(arr));
}
}
HighSum.main(null);