2013-08-23 119 views
0

我編寫了一個祕密的聖誕老人程序,打印出所有參與者的獨特祕密聖誕老人,並且不會在同一輸入上重複輸出。隨機數不同的輸出每次

我的問題是:

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

回答

1

首先,你永遠不能確定一個配置不會重複。只有6個排列的3個元素,所以每個第6次重新運行(統計)配置將重複,假設列表中有3個項目。

接下來,關於您的掛起。您正在從列表中刪除項目,然後讓程序在那裏找到一個元素。想象一下這種情況:你的名字是Fred,Eric,Mike。選擇是

Fred - Eric 
Eric - Fred 

因此,你只有邁克在名單上,只有邁克在聖誕老人名單。看到問題了嗎?沒有辦法選擇聖誕老人。這可以通過幾種方式解決。

最簡單的方法是洗牌,假設它們通過指數對應,並檢查是否有人是聖誕老人。如果是這樣,重新洗牌。這仍然有提到的問題,但只是列表大小之一(在這種情況下,問題明顯無法解決)。

+0

我不想在每次運行時輸出不同的輸出,但只在連續運行時輸出。添加以下代碼 而(itr.hasNext()) \t \t { \t \t \t字符串名稱=(字符串)itr.next(); \t \t \t \t String SecretName; \t \t \t做 \t \t \t { \t \t \t INT蘭特= r.nextInt(TOTAL_SIZE); \t \t \t SecretName = ss.santa.get(rand); \t \t \t \t \t \t} while(name.equals(SecretName)|| s.contains(SecretName)); \t \t \t s.add(SecretName); \t \t \t System.out。println(名稱+「」+ SecretName); \t \t \t \t } \t \t \t \t \t s.removeAll(ss.names); – nnm

0

程序在某些重新生成時會生成相同的輸出,因爲您使用的是隨機函數,並且該函數可以生成重複的數字(int rand = r.nextInt(total_size);)。