I have an array of integers like these; dim x as integer()={10,9,4,7,6,8,3}. Now I want to pick a random number from it,how can I do this in visual basic?Thanks in advance...
+1
A:
First you need a random generator:
Dim rnd As New Random()
Then you pick a random number that represents an index into the array:
Dim index As Integer = rnd.Next(0, x.Length)
Then you get the value from the array:
Dim value As Integer = x(index)
Or the two last as a single statement:
Dim value As Integer = x(rnd.Next(0, x.Length))
Now, if you also want to remove the number that you picked from the array, you shouldn't use an array in the first place. You should use a List(Of Integer)
as that is designed to be dynamic in size.
Guffa
2009-10-28 00:33:55
Thanks man that's a real help....
joe capi
2009-10-28 01:13:22
Or, for the less verbose among us, can you use "dim value as integer = x(new random().next(0,x.length))" or is that considered too Java-ish for VB'ers? :-)
paxdiablo
2009-10-28 01:17:02
I'd go with "Hard to Maintain"
pst
2009-10-28 04:32:24
@paxdiablo: I avoided creating the Random object in the same statement because then it looks like you should create one for every random number that you want. If you pick numbers in a loop that would be bad, as the random generator is seeded using the system timer, so you would get the same random numbers over and over.
Guffa
2009-10-28 08:05:08