我正在创建一个彩票类来生成5个独特的彩票号码(没有使用过的数字的重复)。我无法找到并从阵列中删除任何重复。我错过了什么?
public class Lottery {
private int lotteryNumber[] = new int[5];
public Lottery() {
Random myRan = new Random();
for (int i = 0; i < lotteryNumber.length; i++) {
lotteryNumber[i] = myRan.nextInt(9) + 1;
for (int j = i + 1; j < lotteryNumber.length; j++) {
if ((lotteryNumber[i] == (lotteryNumber[j])) && (i != j)) {
System.out.println("Duplicate Element is : " + lotteryNumber[i]);
i--;
}
}
System.out.println(lotteryNumber[i]);
}
}
}
尽管付出了努力,它还是继续打印出重复的内容。提前感谢您的帮助
答案 0 :(得分:2)
我会使用LinkedHashSet<Integer>
生成所需的位数(然后您可以将其转换为数组并保留原始顺序)。像,
final int len = 5;
Random rand = new Random();
Set<Integer> set = new LinkedHashSet<>(len);
while (set.size() < len) {
set.add(rand.nextInt(10));
}
Integer[] arr = set.toArray(new Integer[len]);
System.out.println(Arrays.toString(arr));
或随机播放10位数字并取前5位数字。像
这样的东西Integer[] digits = new Integer[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Collections.shuffle(Arrays.asList(digits));
Integer[] lottery = Arrays.copyOf(digits, 5);
System.out.println(Arrays.toString(lottery));
答案 1 :(得分:2)
您也可以考虑使用HashSet来完成此任务:
public class Lottery {
private Collection<Integer> lotteryNumbers = new HashSet<>();
public Lottery() {
Random rand = new Random();
while (lotteryNumbers.size() < 5) {
this.lotteryNumbers.add(rand.nextInt(9) + 1);
}
}
public Collection getNumbers() {
return this.lotteryNumbers;
}
public Integer[] getNumbersAsArray() {
return this.lotteryNumbers.toArray();
}
}
答案 2 :(得分:1)
尝试对您的代码进行一次小修改......
import java.util.*;
import java.io.*;
public class Lottery {
private int lotteryNumber[] = new int[5];
public Lottery() {
Random myRan = new Random();
for (int i = 0; i < lotteryNumber.length; i++)
{
lotteryNumber[i] = myRan.nextInt(9)+1;
for (int j = 0; j < i; j++)
{
if( (lotteryNumber[i] == (lotteryNumber[j])) && (i != j) )
{
i=0;
}
}
}
System.out.println("final values are");
for(int i = 0; i < lotteryNumber.length; i++){
System.out.println(lotteryNumber[i]);
}
}
}
答案 3 :(得分:0)
使用Set
存储已见过的数字,如下所示:
final Random rnd = new Random(System.currentTimeMillis());
final Set<Integer> seenNumbers = new HashSet<>();
int index = 0;
int number;
while (index < 5) {
number = rnd.nextInt(9) + 1;
if (seenNumbers.add(number))
lotteryNumbers[index++] = number;
}
即使这样,你也会遇到这个问题,这可能需要很长时间。你的初始设定大小是10,你随机选择5个。当然,你最终会得到一个结果,但这可能需要很长时间才能实现。但是,我不知道它背后的数学。
答案 4 :(得分:0)
在这种情况下,您可以使用LinkedHashSet
:
(因此LinkedHashSet不会保留重复值)
public static <T> T[] removeDuplicates(T[] arr) {
return (T[]) new LinkedHashSet<T>(Arrays.asList(arr)).toArray();
}
然后您可以删除重复项:
removeDuplicates(new Integer[] { 3,6,7,7,3 })
输出:
// [3,6,7]