|
-
Feb 27th, 2010, 08:00 AM
#1
Thread Starter
Lively Member
Get Random value with no duplicate
hi... i use this code in which i want different value of i (no duplicate). . but this code return some duplicate value of i...
----------------------------
Dim r As New Random
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
dim i as Integer
For i = 1 To 5
MsgBox(r.Next(0, 5))
Next
End Sub
'----------------------
-
Feb 27th, 2010, 08:08 AM
#2
Re: Get Random value with no duplicate
Of course it will produce duplicates - the random class generates random numbers, nothing more.
If you want to prevent duplicates you need some method of keeping track of whether a number has already been selected. In simple cases you may just want to declare an array of booleans with the upper limit = the upper limit of your random range, and then every time you pick your random number check that element in the array to see if its set to true, if it is then pick again, if not use that number and set the corresponding element of the array to true so it can't get picked again.
-
Feb 27th, 2010, 01:37 PM
#3
Re: Get Random value with no duplicate
An easier way is to fill a list or array with the numbers you want to select a random number from. Then, you select an element from that list at random. Once you selected it, you remove that element from the list, and then it cannot be selected a second time.
To select a random element from a list, simply generate a random index (between 0 and the upper bound of the list), and extract the value of the list at that index.
-
Feb 27th, 2010, 07:35 PM
#4
Re: Get Random value with no duplicate
Follow the Codebank link in my signature and check my two threads on this topic. There is one on Unique Random Selections and one on Randomising a List. Which technique you choose depends on the specifics of the project.
-
Aug 25th, 2010, 08:58 AM
#5
New Member
Re: Get Random value with no duplicate
Use HashSet (Of T) instead of arraylist.
HashSet(Of T) keeps out duplicated values.
-
Aug 25th, 2010, 09:06 AM
#6
Re: Get Random value with no duplicate
 Originally Posted by junnybol
Use HashSet (Of T) instead of arraylist.
HashSet(Of T) keeps out duplicated values. 
A HashSet will prevent you adding duplicates to the collection but it doesn't prevent you from generating duplicate values and trying to add them. You could keep generating numbers if Add returns False but that's rather inefficient, especially as the number of possible values increases. If you can ensure that you never generate a duplicate then whether you use a HashSet or List or whatever isn't really relevant.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|