tags:

views:

270

answers:

2

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...

A: 

randomly choose an index from 0 to length-1 from your array.

Jreeter
+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
Thanks man that's a real help....
joe capi
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
I'd go with "Hard to Maintain"
pst
@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