hey guys so i am trying to solve this problem I am makeing a java method that takes in a 2D array and 2 ints to dictate a starting position of a coin gatherer in the array. The gatherer is greedy and lazy when deciding to which adjacent location (either up, down, left, right) to move next. It’s greedy because it moves to the location with the highest number of coins; and it’s lazy because it will stop moving if no adjacent location increases its coin treasure. If several adjacent locations had the same highest number of coins, the gatherer will choose to move to the highest in a clockwise fashion (up, right, down, left). Diagonal locations are not considered adjacent. The gatherer empties the coins from any location it visits. Lastly, the method returns the coins acquired up to the point when the gatherer doesn't move anymore. this is what i have so far but the issue i am running into is the when running a junit test it gets a out of bounds error with the way i am checking the values of the surrounding values. any help fixing this would be appreciated.
public class Program3 {
public static void main(String[] args)
{
}
public static int getCoins(int[][] map, int row, int col)
{
int cointotal = map[row][col];
int[] numbers = new int[4];
int big = 0;
int a = map[row-1][col];
int b = map[row-1][col-1];
int c = map[row][col-1];
int d = map[row+1][col];
while(a > cointotal || b > cointotal || c > cointotal || d > cointotal)
{
numbers[0] = a;
numbers[1] = b;
numbers[2] = c;
numbers[3] = d;
big = findLargest(numbers);
cointotal = cointotal + big;
a = map[row-1][col];
b = map[row-1][col-1];
c = map[row][col-1];
d = map[row+1][col];
if(numbers[0] == big)
{
row = row -1;
col = col;
}
if(numbers[1] == big)
{
row = row - 1;
col = col - 1;
}
if(numbers[2] == big)
{
row = row;
col = col - 1;
}
if(numbers[3] == big)
{
row = row + 1;
col = col;
}
}
return cointotal;
}
public static int findLargest(int[] numbers){
int largest = numbers[0];
for(int i = 1; i < numbers.length; i++){
if(numbers[i] > largest){
largest = numbers[i];
}
}
return largest;
}
}