Sunday, 8 September 2013

2d array game that moves to adjacent spaces picking up coins

2d array game that moves to adjacent spaces picking up coins

So I've been working on this problem for the better part of today. I did
get the code to pass the example case given below, but it still fails most
other cases like {1},{1} or { 1, 3 }, { 3, 1 }. Can someone help me figure
out where I went wrong?
Write a class "Program3" using java that has the method "getCoins" (below)
that receives a two-dimensional array of integers, and 2 integer numbers.
The array represents a map with coins, and the integers represent a row
and column location of a coin gatherer. 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. For example, given {{ 1,
1, 1 },{ 0, 1, 0 },{ 0, 8, 0 }} and row 0 and column 0 as the initial
location, the gatherer moves twice to the right and stops, after
collecting 3 coins.
public static int getCoins(int[][]map,int row,int col){
int[] coins = {0,0,0,0}; //up,right,down,left
int numOfCoins = 0;
boolean moreCoins = true;
//check if starting locations has coins
if(map[row][col] > 0){
numOfCoins += map[row][col];
map[row][col] = 0;
}
while(moreCoins == true){
//check if current map is out of bounds with row, col
//check if there are coins next to person
//check up
if(row > 0){
if(map[row-1][col] > 0){
coins[0] = map[row-1][col];
}
}
//check right
if(col < (map.length-2)){
if(map[row][col+1] > 0){
coins[1] = map[row][col+1];
}
}
//check down
if(row < map[0].length-2){
if(map[row+1][col] > 0){
coins[2] = map[row+1][col];
}
}
//check left
if(col > 0){
if(map[row][col-1] > 0){
coins[3] = map[row][col-1];
}
}
//pick up the greatest num of coins
int highestCoin = 0;
int newRow = 0;
int newCol = 0;
for(int i = 0; i < 4; i++){
if(coins[i] > highestCoin){
highestCoin = coins[i];
if(i == 0){
newRow = row - 1;
}else if(i == 1){
newCol = col + 1;
}else if(i == 2){
newRow = row + 1;
}else{
newCol = col - 1;
}
}
}
if (highestCoin == 0){
System.out.println("good");
moreCoins = false;
}else{
//System.out.println(numOfCoins);
row = newRow;
col = newCol;
numOfCoins += map[row][col];
map[row][col] = 0;
if(map[row][col] == 0){
break;
}
}
}
return numOfCoins;
}

No comments:

Post a Comment