【问题标题】:random number different output every time每次随机数不同的输出
【发布时间】:2013-08-23 09:44:12
【问题描述】:

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

我的问题是:

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

代码如下。

    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);

【问题讨论】:

    标签: java random unique


    【解决方案1】:

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

    接下来,关于你的挂起。您正在从列表中删除项目,然后要求程序在那里找到一个元素。想象一下这种情况:你的名字是 Fred、Eric、Mike。选择是

    Fred - Eric
    Eric - Fred
    

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

    最简单的方法是打乱名称,假设它们通过索引对应,并检查是否有人为自己做圣诞老人。如果是这样,重新洗牌。这仍然存在上述问题,但仅针对列表大小为 1(在这种情况下问题显然无法解决)。

    【讨论】:

    • 我不希望每次运行都有不同的输出,而只希望连续运行。我添加了以下代码 while(itr.hasNext()) { String name=(String)itr.next();字符串秘密名称;做{ int rand=r.nextInt(total_size); SecretName=ss.santa.get(rand); }while(name.equals(SecretName) || s.contains(SecretName)); s.add(SecretName); System.out.println(name+" "+SecretName); } s.removeAll(ss.names);
    【解决方案2】:

    该程序在某些重新运行时会生成相同的输出,因为您使用的是随机函数并且该函数会产生重复的数字 (int rand=r.nextInt(total_size);)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-10
      • 1970-01-01
      • 2015-01-03
      • 1970-01-01
      • 2020-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多