2015-11-09 26 views
0

當每個值在隨機位置上至少出現一次時,我需要從值(準備好的集合)中獲取數據集。從集合中的隨機值中獲取優雅的數據集

運行以下代碼後,此條件有時只滿足。 怎樣才能改善世代?

private static Random rand = new Random(); 
    private static int N = 5; 

    public static void main(String[] args){ 
     List<String> indexList = new ArrayList<>(); 
     indexList.add("aaa"); 
     indexList.add("bbb"); 
     indexList.add("ccc"); 
     indexList.add("ddd"); 


     List<String> generatedDataList = new ArrayList<String>(); 

     for (int i=0; i<=5; i++) { 
      String generatedIndex = getRandomValue(indexList); 
      System.out.println("Step " + i+ ": " + generatedIndex); 
      generatedDataList.add(generatedIndex); 
     } 

     } 


    static String getRandomValue(List<String> list){ 
      return list.get(rand.nextInt(list.size())); 
    } 
+0

你的意思是你想打亂清單嗎? –

回答

1

如果你想一切辦法來至少出現一次,最好的方法是用鼠標右鍵在添加的所有字符串開始,然後只添加兩個隨機String s,最後將這個列表洗牌。

List<String> generatedDataList = new ArrayList<String>(indexList); 
for (int i = 0; i < 2; i++)  
    generatedDataList.add(getRandomValue(indexList)); 
Collections.shuffle(generatedDataList); 
1

您可以通過使用Collections.shuffle方法,容易洗牌indexList

Collections.shuffle(indexList)