嘿伙计们,我正在尝试解决这个问题,我正在制作一个java方法,它接受一个2D数组和2个整数来指示数组中硬币收集器的起始位置。收集者在决定下一步移动到哪个相邻位置(上、下、左、右)时是贪婪和懒惰的。它很贪心,因为它移动到了该位置 拥有最多数量的硬币;它很懒,因为如果没有相邻位置增加其金币宝藏,它就会停止移动。如果几个相邻位置的硬币数量相同,则 收集者将选择以顺时针方式移动到最高处(上、右、下、左)。对角线位置不被视为相邻。收集器从它访问的任何位置清空硬币。最后, 该方法返回收集者不再移动时所获取的硬币。这是我到目前为止所遇到的,但我遇到的问题是,当运行 junit 测试时,它在检查周围值的值时出现越界错误。任何解决此问题的帮助将不胜感激。
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;
}
}
最佳答案
您的数字数组的大小为 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
关于java - public static int getCoins(int[][] map, int row, int col) 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18691459/