我正在编写一个秘密圣诞老人程序,打印出所有参与者的独特秘密圣诞老人,并且不会在同一输入上重复输出。
我的问题是:
代码如下。
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);
答案 0 :(得分:1)
首先,您永远无法确定配置是否重复。只有6个3个元素的排列,所以每次重新运行(统计上)配置会重复,假设列表中有3个项目。
接下来,关于你的挂起。您正在从列表中删除项目,然后要求程序在那里找到一个元素。想象一下这种情况:你的名字是Fred,Eric,Mike。选择是
Fred - Eric
Eric - Fred
因此,您只能获得列表中的迈克,并且只能获得圣诞老人列表中的迈克。看到问题了吗?没有办法选择圣诞老人。这可以通过几种方式解决。
最简单的方法是洗牌,假设它们与索引相对应,并检查是否有人为他自己。如果是这样,重新洗牌。这仍然有上述问题,但只是列表大小一(在这种情况下,问题显然无法解决)。
答案 1 :(得分:0)
该程序在某些重新运行中生成相同的输出,因为您正在使用随机函数,并且该函数可以生成重复的数字( int rand = r.nextInt(total_size); )。