Random Number Validation

Kris Jacyna

Member
Joined
Feb 12, 2007
Messages
20
Programming Experience
Beginner
Hey everybody, I'm new to the forum.
I am currently learning Visual Basic and I just have a quick question

What is the simplist way to generate random numbers (22 I need) but make sure the same number is not generated more then once?

Thank you in advance to anyone who could help me

Kris.
 
You could make an usedNumbers() array where you add the numbers you have picked. Then whenever it should generate a new random number that is not used you can go through the array (of maybe use "list of integer") to see if the randomly picked number has been used before, if it has the generate a new number

VB.NET:
private usedNumbers as list (of integer) = new list (of integer)
 
private function getUnusedNumber() as integer
  dim usedNumber as integer
  dim randomNumber as integer
  dim isUsed as boolean = true 
  while isUsed = true
    isUsed = false
    randomNumber = ' Find a random number by calling the function rnd() or something like that
    for each usedNumber in usedNumbers ' Goes through all numbers that has already been used
      if randomNumber = usedNumber
        isUsed = true ' If randomNumber is the same as one of the usedNumbers it will go through the loop one more time
        exit for  
      next
  end while

  usedNumbers.add(randomNumber)
  return randomNumber
end function
... or something like that. I haven't tested if the code actually works, but hopefully you can see what I'm trying to say with it
 
If it's not very many numbers you could enter them into an array and randomize that (with some swapping routine), then just pick from that one by one.

Or same filling a collection with the range, then pick random elements while removing them from collection.
 
Back
Top