1
如何創建一個隨機整數列表(List<int>
),幾乎是按順序排列的(大約隨機值的10%是亂序)?創建一個部分洗牌的隨機數排序列表
如何創建一個隨機整數列表(List<int>
),幾乎是按順序排列的(大約隨機值的10%是亂序)?創建一個部分洗牌的隨機數排序列表
我頭腦中的第一件事是創建一個隨機值列表,對它進行排序,並在隨機位置插入10%的未排序隨機值。
totalItemsCount
隨機數percentToShuffle
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;
}
你在問什麼?如何生成隨機數字?如何添加東西到列表?如何排序?這個網站不是「爲我寫代碼」的工具;你可以說得更詳細點嗎?你已經嘗試過什麼,確切的部分是造成問題? – tenfour