作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这里详细描述了问题:https://adventofcode.com/2015/day/3简而言之:由于文本文件中给出的指示,我连续访问了多个位置,并且我想知道我至少访问过多少个位置。
我创建了一个像这样的类 Point :
public class Point {
private int x;
private int y;
public Point (int x, int y) {
this.x=x;
this.y=y;
}
public int getAbs() {
return x;
}
public int getOrd() {
return y;
}
}
它只是由两个坐标组成的点,用于指示房屋的位置。我在这里使用它:
public class Exo3 {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("C:/Users/mpv15_000/Documents/Advent/input3.txt");
int c = fr.read();
int x=0;
int y=0;
Point init = new Point(x,y);
List<Point> visitedHouses = new ArrayList<Point>();
visitedHouses.add(init);
Boolean b = true;
while ((c == '^') || (c == 'v') || (c == '<') || (c == '>'))
{
if (c == '^')
y++;
else if (c == 'v')
y--;
else if (c == '<')
x--;
else
x++;
for (Point p : visitedHouses) {
if ((p.getAbs() != x) || (p.getOrd() != y))
b = true;
else
b = false;
}
if (b == true) {
visitedHouses.add(new Point(x,y));
}
c = fr.read();
}
System.out.println("Number of houses visited at least once : " + visitedHouses.size());
fr.close();
}
}
我得到“8193”,这是我认为的迭代总数,但不是我正在寻找的。我想知道我至少去过一次的地点有哪些。我认为问题来自visitedHouses 列表上的for 循环。我想比较当前的 x 和 y 是否已经存在于位于此列表中的点中。我该怎么办?
最佳答案
当x
和y
相同时,您需要重写Point类中的equals
方法以返回true。像这样的东西:
@Override
public boolean equals(Object other)
{
if (this == other) return true;
if (!(other instanceof Point)) return false;
return (this.x == ((Point)other).x) && (this.y == ((Point)other).y);
}
然后使用 Set 而不是 List。集合将仅保存唯一的积分。
如果您想继续使用 List,只需执行以下操作:
if (b == true)
{
Point visitedPoint = new Point(x,y);
if (!visitedHouses.contains(visitedPoint)) {
visitedHouses.add(visitedPoint);
}
}
顺便说一句:如何识别访问过的房子取决于您......
关于Java : verifying if an object already exists in a List?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45043683/
我是一名优秀的程序员,十分优秀!