gpt4 book ai didi

Java : verifying if an object already exists in a List?

转载 作者:行者123 更新时间:2023-11-30 02:28:08 25 4
gpt4 key购买 nike

这里详细描述了问题: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 是否已经存在于位于此列表中的点中。我该怎么办?

最佳答案

xy相同时,您需要重写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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com