Filling an Array Randomly

  • Thread starter Thread starter rowe_newsgroups
  • Start date Start date
R

rowe_newsgroups

How can I fill an array randomly so it contains a certian range of numbers
(1 - 100 for example) ? My Goal is to generate a set of numbers in random
order.

Dim rand As New Random(DateTime.Now.Millisecond)
Dim numbers(99) As Integer
For i As Integer = 0 To UBound(numbers)
numbers(i) = rand.Next(1, 100)
Next

By the way, you should try to find the answers for yourself before you
post a question. Try searching the archives at
http://groups.google.com/group/microsoft.public.dotnet.languages.vb/topics?lnk=sg&hl=en
before you post, with a little searching you could probably figure out
what to do.

Thanks,

Seth Rowe
 
Use the randomize statement on application startup to set a ramdomizer seed.

use RND to generate a random number.

I usually make a helper function for this

public shared function GetRandom(lowerBound as integer, upperBound as
integer) as integer

return int((upperBound-lowerBound)*rnd +lowerbound)

end function


If you want to fill the array randomly with random numbers, you willl need
to size your array first.

sub Test()
dim myNumbers() as integer
dim myUnusedSlots Arraylist
dim iIndex as intger, iTarget as integer
dim iSample as integer

redim myNumbers(99) 'set the size to 100 elements

for i as integer = 1 to 100
myUnusedSlots.add(i)
next i

do until myUnusedSlots.Count =0

'Pick as random unused slot in the array to use
iIndex = CommonClass.GetRandom(myUnusedSlots.Count, 0)

'Get the item's index for the array
iTarget = myUnusedSlots.item(iIndex)

'Set the value to some random number
myNumbers(iTarget) = GetRandom(1,100)

'Remove the slot from the unused stack.
myUnusedSlots.RemoveAt(iIndex)

loop

end Sub
 
By the way, you should try to find the answers for yourself before you
post a question. Try searching the archives athttp://groups.google.com/group/microsoft.public.dotnet.languages.vb/t...
before you post, with a little searching you could probably figure out
what to do.

Oops, quite a few of the recent posts were by a "John", but they
appear to be from a different domain than what you just posted from.
So if you're a different John than that one, and you research
questions prior to posting, please don't take offense at me saying
that ;-)

Thanks,

Seth Rowe
 
How can I fill an array randomly so it contains a certian range of numbers
(1 - 100 for example) ? My Goal is to generate a set of numbers in random
order.

Well, you could write a loop that generates the random numbers and
populates the array
 
How can I fill an array randomly so it contains a certian range of numbers
(1 - 100 for example) ? My Goal is to generate a set of numbers in random
order.
 
Back
Top