如何创建一个几乎有序的随机整数列表(List<int>
)(大约随机10%的值无序)?
答案 0 :(得分:5)
我头脑中的第一件事就是创建一个随机值列表,对其进行排序,并在随机位置插入10%随机值,未排序。
答案 1 :(得分:1)
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;
}