Question random number generator with limits

ucp8

Active member
Joined
Feb 9, 2009
Messages
28
Programming Experience
3-5
Hi,

Does anyone know how to generate a list of numbers, from 1 to 10 in a random fashion but with no numbers repeating. For example, every time the code is run, it will return an array of numbers, each different, only using numbers from one to ten?

This may sound confusing, so i will try and explain what I am trying to do with it. I have a form that displays 10 questions and each time a user moves to a new question, i want to display a new picture. the pictures will be named "picture1" through "picture10". I want the order that the pictures are displayed to be different every time.

Can anyone help me with this?
 
VB.NET:
Dim rNumber As New Random
Dim UsedList As New List(Of Byte)
Dim Num As Byte
While True
  Num = rNumber.Next(0, 9)
  If Not UsedList.Contains(Num) Then
    UsedList.Add(Num)
    If UsedList.Count = 10 Then
      Exit While
    End If
  End If
End While

Then just use "UsedList" as your order of numbers.
There may be some better way of doing it, but I'm not sure.
Also... This is untested, but looks correct to me.
 
You simply generate the full list of numbers first, then you randomly select one of them, removing it from the list as you do:
VB.NET:
Dim availableNumbers As New List(Of Integer)

For i As Integer = 1 To 10
    availableNumbers.Add(i)
Next

Dim selectedNumbers As New List(Of Integer)
Dim rng As New Random
Dim index As Integer

While availableNumbers.Count > 0
    index = rng.Next(0, availableNumbers.Count)
    selectedNumbers.Add(availableNumbers(index))
    availableNumbers.RemoveAt(index)
End While
That way you don't end up generating lots more random numbers than you actually need.
 
Use the Shuffle Sort algorithm. Here it is in a Console app:

Sub Main()
Dim entry As String, mix, temp As Integer
Dim rndarray(10) As Integer
Dim randnum As New Random()
For x As Integer = 1 To 10
rndarray(x) = x
Next x
Console.WriteLine("Shuffle Sort - Random numbers without duplicates")
Console.WriteLine("Enter to repeat, any other key to stop." & vbCrLf)
Do
For x As Integer = 1 To 10
mix = randnum.Next(1, 10)
temp = rndarray(mix)
rndarray(mix) = rndarray(x)
rndarray(x) = temp
Next x
For x As Integer = 1 To 10
Console.Write(rndarray(x) & " ")
Next x
Console.WriteLine(vbCrLf)
entry = Console.ReadKey(True).KeyChar
Loop While entry = Chr(13)
End Sub
 
Back
Top