0

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;
    }
    }
4

1 回答 1

1

您的 numbers 数组大小为 3,因此它从 0 变为 2。

int[] numbers = new int[3];

但是您正在访问第四个元素

    numbers[0] = a;
    numbers[1] = b;
    numbers[2] = c;
    numbers[3] = d; //OutOfBound

尝试

 int[] numbers = new int[4];

编辑:

我建议,在访问您的数组之前验证索引。

int rowLength = map.length;
int columnLength = (rowLength==0)0:map[0].length;

//other code
boolean verify(int x, int y){
   return x < rowLength && y < columnLength;
}

//then you can do something like this
int a = verify(row-1,col)? map[row-1][col]: a; //don't change if the index is outOfBounds
于 2013-09-09T04:31:04.050 回答