2011-11-05 78 views
1

如何創建一個隨機整數列表(List<int>),幾乎是按順序排列的(大約隨機值的10%是亂序)?創建一個部分洗牌的隨機數排序列表

+5

你在問什麼?如何生成隨機數字?如何添加東西到列表?如何排序?這個網站不是「爲我寫代碼」的工具;你可以說得更詳細點嗎?你已經嘗試過什麼,確切的部分是造成問題? – tenfour

回答

5

我頭腦中的第一件事是創建一個隨機值列表,對它進行排序,並在隨機位置插入10%的未排序隨機值。

1
  1. 生成totalItemsCount隨機數
  2. 排序(建於List.Sort())
  3. 項目的計算NUMER使用使用隨機指標
項目 percentToShuffle
  • 洗牌N%洗牌
    List<int> items = new List<int>(); 
    Random randomizer = new Random(); 
    int percentToShuffle = 10; 
    int totalItemsCount = 50; 
    int minRandomNumber = 0; 
    int maxRandomNumber = totalItemsCount * 10; 
    int index = totalItemsCount; 
    while(index-- > 0) 
    { 
        // guarantee that all items are unique 
        int nextItem = randomizer.Next(minRandomNumber, maxRandomNumber);     
        while(items.IndexOf(nextItem) >= 0) 
        { 
         nextItem = randomizer.Next(minRandomNumber, maxRandomNumber);      
        } 
    
        items.Add(nextItem);    
    } 
    
    // sort 
    items.Sort(); 
    
    // shuffle 
    int numberToShuffle = totalItemsCount * percentToShuffle/100;    
    while (numberToShuffle-- > 0) 
    { 
        int swapIndex1 = randomizer.Next(0, totalItemsCount - 1); 
        int swapIndex2 = randomizer.Next(0, totalItemsCount - 1); 
        int swapTemp = items[swapIndex1]; 
        items[swapIndex1] = items[swapIndex2]; 
        items[swapIndex2] = swapTemp;  
    }