Reputation: 323
How can I create a list of random integers (List<int>
) that is almost in order (about a random 10% of the values out of order)?
Upvotes: 1
Views: 690
Reputation: 62504
totalItemsCount
random numberspercentToShuffle
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;
}
Upvotes: 1
Reputation: 90316
First thing out of my head is to create a list of random values, sort it, and insert 10% of random values, unsorted, at random positions.
Upvotes: 5