[英]Generate 5 sets of 6 random numbers within range 1-49, by making sure there aren’t any duplicates in each set?
I am making a program that will generate 5 sets of 6 random numbers to be used in the lottery however at the moment when the sets of numbers are printed they contain duplicates. 我正在制作一个程序,该程序将生成5组6个随机数供彩票使用,但是在打印一组数时,它们包含重复项。 How can I make it so every number in each set is unique? 我怎样才能使每个集合中的每个数字都是唯一的? (Note each set should be ordered in ascending order from lowest to highest) (请注意,每组应按从低到高的升序排列)
import java.util.Arrays;
public class tasksTest {
public static void main(String[] args) {
System.out.println("Your lottery numbers are:");
for(int i=1; i<6; i++){
int[]lotteryNumbers = new int[6];
for(int ii = 0; ii < lotteryNumbers.length; ii++){
lotteryNumbers[ii] = (int)(Math.random()*49 + 1);
}
Arrays.sort(lotteryNumbers);
System.out.println(Arrays.toString(lotteryNumbers));
}
}
}
Create an ArrayList
with the numbers 1-49. 用数字1-49创建一个ArrayList
。 Shuffle it with Collections.shuffle()
. 用Collections.shuffle()
对其进行洗牌 。 Iterate through in groups of 6 to create the 5 unique sets, guaranteed to have no overlap. 以6组为一组进行迭代,以创建5个唯一的集合,确保没有重叠。 Sort each set individually. 分别对每个集合排序。 Done. 做完了
You can use sets: 您可以使用集:
Set<Integer> allNumbers = new HashSet<>();
for (int i = 1; i < 6; i++)
{
Set<Integer> set = new HashSet<>();
while (set.size() < 6)
{
int random = (int) (Math.random() * 49 + 1);
if (allNumbers.add(random))
{
set.add(random);
}
}
Integer[] array = set.toArray(new Integer[] {});
Arrays.sort(array);
System.out.println(Arrays.toString(array));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.