tags:

views:

548

answers:

3

Hi,

I would like to generate a random number less than 50, but once that number has been generated I would like it so that it cannot be generated again.

Thanks for the help!

+7  A: 

Put the numbers 1-49 in a sortable collection, then sort it in random order; pop each one out of the collection as needed.

onupdatecascade
Erm. "Sort in random order" is a contradiction in terms.
Stephen C
True, my bad :-). Re-order at random?
onupdatecascade
The words your looking for are: "Place the numbers 1 through 50 in a collection, *shuffle*, then pop each out one at a time."
GMan
Bingo. (Pun intended.) +1 for Mitch for the real answer
onupdatecascade
+11  A: 

Please see: Fisher–Yates shuffle:

public static void shuffle (int[] array) 
{
    Random rng = new Random();       // i.e., java.util.Random.
    int n = array.length;            // The number of items left to shuffle (loop invariant).
    while (n > 1) 
    {
        n--;                         // n is now the last pertinent index
        int k = rng.nextInt(n + 1);  // 0 <= k <= n.
        int tmp = array[k];
        array[k] = array[n];
        array[n] = tmp;
    }
}
Mitch Wheat
BTW, this question has been asked several times before...
Mitch Wheat
Thanks, I've been playing with it for the past 15 minutes but cannot seem to figure out how to call it. I'm a bit new with vb.
+2  A: 

Seeing as the question was tagged VB/VB.Net... this is a VB implementation of Mitch's answer.

Public Class Utils

   Public Shared Sub ShuffleArray(ByVal items() As Integer)

      Dim ptr As Integer
      Dim alt As Integer
      Dim tmp As Integer
      Dim rnd As New Random()

      ptr = items.Length

      Do While ptr > 1
         ptr -= 1
         alt = rnd.Next(ptr - 1)
         tmp = items(alt)
         items(alt) = items(ptr)
         items(ptr) = tmp
      Loop

   End Sub

End Class
Bill