locked
Random Number Generator - Excluding possible values

    Question

  • I need to generate a random number between 1 and 9, which I can very easily do.  However, during the course of the program, I will need to begin excluding numbers from that range.  For example, if BooleanVariable2 = True: generate a random number between 1 and 9 excluding 2. I also need to aggregate the numbers to exclude.  That is, I need to check 9 different boolean variables and if 1 is true, exclude 1; if 2 is true, exclude 2, if 1 and 2 are true, exclude 1 and 2, etc.  First, how do I exclude numbers from a random number generator within a range?  Second, how do I keep track of those numbers that are to be excluded?

    Thanks in advance for your help!

    Monday, October 25, 2010 1:32 AM

Answers

  • Are you using VB 2008 or VB 2010?

    If so, then you could do something like this.

        ' Generate the random numbers
        Dim rnd As New System.Random()
        Dim numbers = Enumerable.Range(1, 9). _
         OrderBy(Function() rnd.Next).ToList
        ' Display the result
        numbers.ForEach(Sub(x) Debug.Write(x & ", "))
        Debug.WriteLine("")
    
        ' Define the set of exclusions
        Dim exclusions As New List(Of Integer)
        exclusions.Add(1)
    
        ' Exclude the excluded numbers
        Dim remainingNumbers = numbers.Except(exclusions).ToList
        ' Display the result
        remainingNumbers.ForEach(Sub(x) Debug.Write(x & ", "))
        Debug.WriteLine("")
    

    Hope this helps.


    www.insteptech.com ; msmvps.com/blogs/deborahk
    We are volunteers and ask only that if we are able to help you, that you mark our reply as your answer. THANKS!
    Monday, October 25, 2010 3:14 AM

All replies

  • Place the numbers you want to choose from into a list.  Use Random.Next(List.Count) to select the index of an item in the list.
    Monday, October 25, 2010 2:55 AM
  • Are you using VB 2008 or VB 2010?

    If so, then you could do something like this.

        ' Generate the random numbers
        Dim rnd As New System.Random()
        Dim numbers = Enumerable.Range(1, 9). _
         OrderBy(Function() rnd.Next).ToList
        ' Display the result
        numbers.ForEach(Sub(x) Debug.Write(x & ", "))
        Debug.WriteLine("")
    
        ' Define the set of exclusions
        Dim exclusions As New List(Of Integer)
        exclusions.Add(1)
    
        ' Exclude the excluded numbers
        Dim remainingNumbers = numbers.Except(exclusions).ToList
        ' Display the result
        remainingNumbers.ForEach(Sub(x) Debug.Write(x & ", "))
        Debug.WriteLine("")
    

    Hope this helps.


    www.insteptech.com ; msmvps.com/blogs/deborahk
    We are volunteers and ask only that if we are able to help you, that you mark our reply as your answer. THANKS!
    Monday, October 25, 2010 3:14 AM