Question Trouble with searching an array for an integer

macleodjb

Member
Joined
Jan 1, 2011
Messages
8
Programming Experience
Beginner
I am having trouble writing a loop that will check to see if a random number exists in an array and was looking to get some help.

Let me Elaborate

I have a function that returns a random (integer) number between a range called GetRandom()

I want to execute GetRandom() and then check to see if MyArray() contains the new number, if it does not contain the number then I want to add it to the array, if it does contain the array then i need to run GetRandom() again until it doesn't contain the number.

My brain is getting confused on how to determine whether to throw the number out or add it to the array. I'm sure this is a stupid simple problem but I'm stuck.

I appreciate the help. Thanks.
 
Array.IndexOf will return the index of a value in an array, or -1 if the value isn't in the array.

That said, there are better ways to do what you want. First, if you want to add items to a list one by one, you almost certainly shouldn't be using an array. Arrays are fixed-size and are tedious to resize. Collections are dynamically sizable so that's what you should be using. The obvious option is to use a List(Of Integer). It's basically a dynamic Integer array. You call Add and an item gets added. It also has a Contains method, which will tell you, True or False, whether the collection contains a value.

That said, there's a better way still. The HashSet(Of Integer) is like a List(Of Integer) but it won't accept duplicate values. You call Add and it returns True or False to indicate whether the value was added or not. Your code reduces to this:
VB.NET:
Dim number As Integer

Do
    number = GetRandom()
Loop Until myHashSet.Add(number)
 
Back
Top