How to generate a random number sequence that is non-repeating in visual basic .net ?

I am writing a matching program, and need 24 objects to randomly appear, each twice, across 48 spaces. I figured the best way for me to do this would be to assign the positions a number 1 through 48. but the problem is I can’t find a way to generate a random number sequence in visual basic 9 .net

I found many examples in visual basic .net but the conversion doesn’t work. If not some code, many some example programs that either use a random number sequence or randomly sets the position of objects.



  1. in the system.random namespace:

    Dim rnd As New Random
    Dim i As Integer
    For i = 1 To 10

    please note that random numbers aren’t “unique”, so you need to add something more to it. how about you fill your 48 spots with the objects … and then run a a loop (like 100 iterations) to exchange object positions by using two random generated indexes .. after that your field of 48 objects will be pretty random!

  2. You can do a simple shuffling algorithm, see Wikipedia.

    Personally the algorithm I like to implement is this: to populate a list with a list of items, then transfer them one by one randomly into another list.

    But hey, here’s the simplest general purpose shuffling algorithm, which I implemented in VB:

    Public Function Shuffle(Of T)(ByVal items As IEnumerable(Of T)) As IEnumerable(Of T)

    Dim x = items.ToArray()
    Dim rand As New Random()
    If items.Count <= 1 Then Return xFor i = 0 To items.Count - 2 Dim index = rand.Next(i + 1, items.Count) Dim tempItem = x(i) x(i) = x(index) x(index) = tempItem NextReturn x End Function

Leave a comment