gpt4 book ai didi

java - 每次输出不同的随机数

转载 作者:行者123 更新时间:2023-12-01 14:12:25 26 4
gpt4 key购买 nike

我正在编写一个 secret 圣诞老人程序,该程序打印出所有参与者的唯一 secret 圣诞老人,并且不会在相同输入上重复输出。

我的问题是:

  1. 程序在某些重新运行时生成相同的输出...
  2. 如果列表中存在多于或等于 3 个名称,程序将在首次运行后挂起。它仅打印几个条目的正确输出。例如3 个名字,它打印 2 个名字的 secret 圣诞老人并挂起!

代码如下。

    SecretSanta ss=new SecretSanta();
Scanner scn=new Scanner(System.in);

do
{
System.out.println("Add the participants name:-");
String name=scn.next().trim();
ss.names.add(name);
ss.santa.add(name);
System.out.println("Do u want to add more names?");
System.out.println(" 1-YES 2-NO");
choice=scn.nextInt();
}while(choice==1);

do
{
total_size=ss.santa.size();
System.out.println(total_size);
Collections.shuffle(ss.santa);
System.out.println(ss.names.size());
System.out.println("Below is the list of participants with their secret santas");
Iterator<?> itr=ss.names.iterator();

while(itr.hasNext())
{
String name=(String)itr.next();
String SecretName;
do
{
int rand=r.nextInt(total_size);
SecretName=ss.santa.get(rand);
}while(name.equals(SecretName));

System.out.println(name+" "+SecretName);
ss.santa.remove(SecretName);
total_size=ss.santa.size();
}
ss.santa.addAll(ss.names);
Collections.shuffle(ss.santa);
System.out.println("do you want to rerun??");
System.out.println(" 1-YES 2-NO");
choice=scn.nextInt();
}while(choice==1);

最佳答案

首先,您永远无法确定配置不会重复。 3 个元素只有 6 种排列,因此假设列表中有 3 个项目,则每 6 次重新运行(统计上)配置都会重复。

接下来,关于你的挂起。您要从列表中删除项目,然后要求程序在那里查找元素。想象一下这种情况:你们的名字是弗雷德、埃里克、迈克。选择是

Fred - Eric
Eric - Fred

因此,列表中只有迈克,圣诞老人列表中也只有迈克。看到问题了吗?没有办法选择圣诞老人。这可以通过几种方式解决。

最简单的方法是打乱名字,假设它们通过索引相对应,然后检查是否有人是圣诞老人。如果是的话,重新洗牌。这仍然存在提到的问题,但只是针对列表大小一(在这种情况下,问题显然无法解决)。

关于java - 每次输出不同的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18399695/

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