gpt4 book ai didi

java - 乘法表

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

我正在制作乘法表(从 2 到 9)- 例如,这是 10 个随机生成的样本

2 * 3 = 
4 * 5 =
... (7 more times)
9 * 5 =

关键是所有的样本必须是不同的和样本

5 * 8 = 

8 * 5 = 

认为是一样的

我的想法是制作描述要相乘的数字对的类 Pair,覆盖它的 equals 方法,生成随机数,创建 Pair 并将 Pair 对象添加到 Set。

public class Pair {
private int first;
private int second;

public int getFirst() {
return first;
}

public int getSecond() {
return second;
}

public void setFirst(int first) {
this.first = first;
}

public void setSecond(int second) {
this.second = second;
}

public Pair() {}

public Pair(int first, int second) {
this.first = first;
this.second = second;
}

@Override
public boolean equals(Object o) {
if (o == null || o.getClass() != this.getClass())
return false;

Pair that = (Pair) o;
return (this.first == that.first && this.second == that.second) ||
(this.second == that.first && this.first == that.second);
}

@Override
public int hashCode() {
int result = 17;
int prime = 31;
result = result * prime + first;
result = result * prime + second;
return result;
}

@Override
public String toString() {
return first + " * " + second + " =";
}
}

public static Pair[] createTable(int count) {
Random random = new Random();
Set<Pair> set = new HashSet<Pair>();
while (set.size() < count) {
int first = random.nextInt(8) + 2;
int second = random.nextInt(8) + 2;
set.add(new Pair(first, second));
}
return set.toArray(new Pair[count]);
}

问题是方法 createTable() 返回的一些数组包含等价对例如在

[7 * 6 =, 5 * 6 =, 4 * 8 =, 4 * 9 =, 2 * 8 =, 9 * 2 =, 8 * 2 =, 6 * 3 =, 5 * 2 =, 4 * 2 =]

有些对 2 * 8 和 8 * 2 不应该存在

错在哪里?

最佳答案

您的hashCode() 方法有误。 hashCode() 必须 为两个相等的对象返回相等的值。根据您的 equals() 方法,5-7 对等于 7-5 对,但它们的 hashCode() 不相同。

要正确实现 hashCode(),您应该始终从最小的数字开始:

public int hashCode() {
int result = 17;
int prime = 31;

int lowest = first < second ? first : second;
int highest = first < second ? second : first;

result = result * prime + lowest;
result = result * prime + highest;
return result;
}

或者,更简单:

public int hashCode() {
int lowest = first < second ? first : second;
int highest = first < second ? second : first;
return Objects.hash(lowest, highest);
}

或者,更简单(感谢@user2336315):

public int hashCode() {
return Objects.hash(Math.min(first, second), Math.max(first, second));
}

关于java - 乘法表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24595294/

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