【发布时间】:2018-03-25 00:13:00
【问题描述】:
我目前正在尝试解决题为战舰:沉没损坏还是未触及?的代码大战问题。给定一个包含“ships”的二维数组和另一个包含攻击坐标的二维数组,我必须生成一个分数。我用船舶位置填充哈希图,然后根据地图检查攻击位置。打印后,第一个测试用例的原始位置和攻击是相同的。尽管如此,map.get() 继续返回 null 而map.containsKey() 返回 false。
public class BattleshipsSDN {
public static Map<String,Double> damagedOrSunk(final int[][] board, final int[][] attacks) {
int y;
HashMap<int[], Integer> ships = new HashMap<>();
// build map of boat locations
for (int i = 0; i < board.length; i++) {
y = board.length - i;
for (int j = 0; j < board[i].length; j++) {
if (board[i][j] == 0) continue;
else {
int[] location = {j+1,y};
ships.put(location, board[i][j]);
System.out.println("Location: "+location[0]+","+location[1]);
//System.out.println("Value: "+ships.get(location));
}
}
}
//establish original boat lengths
int ship1 = Collections.frequency(new ArrayList<Integer>(ships.values()), 1);
int ship2 = Collections.frequency(new ArrayList<Integer>(ships.values()), 2);
int ship3 = Collections.frequency(new ArrayList<Integer>(ships.values()), 3);
System.out.println("Ships: "+ship1+ship2+ship3);
for(int[] x : ships.keySet()) System.out.println(x[0]+","+x[1]);
//check for hits
for (int[] x : attacks) {
System.out.println(x[0]+","+x[1]);
if (ships.get(x) == null) continue;
else{
System.out.println("Hit");
ships.remove(x);
}
}
double sunk = 0;
double hit = 0;
double missed = 0;
//find number of ship spots after attacks
int leftShip1 = Collections.frequency(new ArrayList<Integer>(ships.values()), 1);
int leftShip2 = Collections.frequency(new ArrayList<Integer>(ships.values()), 2);
int leftShip3 = Collections.frequency(new ArrayList<Integer>(ships.values()), 3);
System.out.println("Ships: "+leftShip1);
if (ship1 > 0) {
if (leftShip1 == 0) sunk++;
else if (ship1 % leftShip1 > 0) hit++;
else if (ship1 == leftShip1) missed++;
}
if (ship2 > 0) {
if (leftShip2 == 0) sunk++;
else if (ship2 % leftShip2 > 0) hit++;
else if (ship2 == leftShip2) missed++;
}
if (ship3 > 0) {
if (leftShip3 == 0) sunk++;
else if (ship3 % leftShip3 > 0) hit ++;
else if (ship3 == leftShip3) missed++;
}
HashMap<String, Double> score = new HashMap<>();
score.put("sunk", sunk);
score.put("damaged", hit);
score.put("notTouched", missed);
score.put("points", sunk + hit/2 - missed);
return score;
}
}
我不是要你为我解决问题。我完全不知道为什么我的 HashMap 会这样。这可能意味着这是一些非常小的愚蠢的事情。
注意:位置的 y 值是翻转的,因为在问题“板”中,y 坐标是从底部测量的。因此,在 4x4 板或数组中,索引 [0][0] 对应于坐标 (1,4)
【问题讨论】:
-
int[]s不要覆盖equals和hashCode;他们按身份进行比较。 -
一般用于数组。数组作为映射中的键不起作用。尝试其他数据结构。
-
对于
<your favourite deity>的喜爱,使用集合而不是数组。如果您改用List<Integer>而不是int[],您的问题就会消失。