问题在这里详细描述: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是否已存在于此列表中的Point中。我该怎么办 ?
最佳答案
当equals
和x
相同时,您需要重写Point类中的y
方法以返回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。 Set将仅包含唯一点。
如果您想继续使用List,请执行以下操作:
if (b == true)
{
Point visitedPoint = new Point(x,y);
if (!visitedHouses.contains(visitedPoint)) {
visitedHouses.add(visitedPoint);
}
}
顺便说一句:您如何确定拜访的房子取决于您...