3

Is it possible to create a random number from a selection of numbers in c#.

For example I have an array of numbers from 1-90 and once a number has been called a propery of that number changes. I therefore only want to generate the numbers where that property has not changed. This will therefore only randomly call the numbers between 1 and 90 one.

I have done this using a loop but just wanted a quiker and cleaner method if possible.

My current code is:

    public object GenerateNumber()
    {
        bool alreadyCalled = false;
        while (!alreadyCalled)
        {
           Random randomNumber = new Random(System.DateTime.Now.Millisecond);
            int RandomNumberCalled = randomNumber.Next(1, 91);             


            if (Numbers.ToList().Find(x => x.Number == RandomNumberCalled).IsCalled != null)
            {    

             // change number to is called and do other things. 

            }
        }
        return false;
    }
1
  • 5
    A side note: You'd do well to move "Random randomNumber = new Random" outside your loop, then call "randomNumber.Next" many times within the loop. Also just use "new Random()" instead of passing in a seed. More detail on why this is good practice is at msdn.microsoft.com/en-us/library/system.random.aspx
    – teedyay
    Commented Oct 12, 2010 at 13:48

4 Answers 4

10

You should use List and remove selected items, then decrement upper border. Or better solution is to copy array and shuffle it then sequential access will give you random numbers. Or use Knuth shuffling (check comment).

2
  • A C# version of that (most excellent) shuffling algorithm appears halfway down this page, with a discussion on why it's good: codinghorror.com/blog/2007/12/the-danger-of-naivete.html
    – teedyay
    Commented Oct 12, 2010 at 13:51
  • 2
    If you want a faster algorithm, Knuth Shuffling can be done in O(1) time per variable, by only shuffling one value at a time, as it is requested.
    – Brian
    Commented Oct 12, 2010 at 14:00
6

It will become increasingly "harder" to find an unused value the more iterations you perform, as eventually the probability of finding an already used value will approach 100%. There are alternatives. One such possibility is to randomly sort your source array before trying to extract any numbers, and then you just peel them off sequentially.

0
list<int> myNumbers=GetNumbers();
Random r=new Random();
while (myNumbers.Count()>0)
{
  int index=r.Next(myNumbers.Count());
  ReportSelectedNumber(myNumbers[index]);
  myNumbers.RemoveAt(index);
}

Make sure that you have GetNumbers() that will return you the list you want your numbers to be selected from, and ReportSelectedNumber() for doing something with recently selected number.

5
  • I think this is close to what but i am still having issues. If i have a list of numbers 1,2,3,4,5 and the number called is 2 then your example will show 1,2,3,4 however i want the random number to then search between 1,3,4,5. Hope this is clear enough :-)
    – Bruie
    Commented Oct 18, 2010 at 16:08
  • well, i am reading your comment, my code, your comment, my code again, and i am sure that it will display the numbers just like you want them. so, if at first index turns out to be 1, number 2 will be selected and removed from the list. then, random number will be chosen from 0-3, inclusive, and list will read 1,3,4,5. next random will remove and print out one from that list, ... and so on... Commented Oct 18, 2010 at 17:19
  • you are simulating lotto of some kind here? Commented Oct 18, 2010 at 17:20
  • yes thats right :-) I realised my mistake - i was using the index as the number lol. - thank you for your help here it now works perfectly.
    – Bruie
    Commented Oct 19, 2010 at 9:08
  • NP, you can always repay me with checkmark besides my answer :) Commented Oct 19, 2010 at 9:14
0

Things to note

  1. Using Random(...) in a loop will cause repeats when the seed is the same. In your example, the same millisecond will be hit often.

  2. Random numbers repeat. Over a large number of iterations, you would expect the distribution to be fairly even for each number in the range but for any given randomly generated number, it cannot have any knowledge of the previously generated numbers.

To answer your question where you really want a shuffled list of numbers, you should be able to adapt this into your code:

var randomOrderInts = Enumerable.Range(1, 91).OrderBy(x => Guid.NewGuid());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.