0

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

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
joe capi
  • 3
  • 1
  • 2
  • 3
    Take a look at this: http://stackoverflow.com/questions/1218155/random-number-but-dont-repeat/1222514#1222514 – opello Oct 28 '09 at 00:26

2 Answers2

3

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
  • 687,336
  • 108
  • 737
  • 1,005
  • 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 Oct 28 '09 at 01:17
  • I'd go with "Hard to Maintain" –  Oct 28 '09 at 04:32
  • @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 Oct 28 '09 at 08:05
0

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

jr3
  • 915
  • 3
  • 14
  • 28