hmdb
hmdb

Reputation: 323

Create a sorted list of random numbers which are partially shuffled

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

Answers (2)

sll
sll

Reputation: 62504

  1. Generates totalItemsCount random numbers
  2. Sort (built in List.Sort())
  3. Calculate numer of items to shuffle using percentToShuffle
  4. Shuffle N% of items using random indexes
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

CharlesB
CharlesB

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

Related Questions