PDA

View Full Version : Problem Searching Array for String


macleodjb
01-11-2011, 06:07 PM
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.

Old Pedant
01-11-2011, 11:53 PM
Ummm...no, you are *NOT* "Searching Array for String". You are searching an array for a *NUMBER*. Why would you think that a random integer number would be a string? You even *said* it's a "random (integer) number"!!

So:

function addRandomNumberToArray( theArray, low, high )
{
while ( true ) /* loop forever */
{
var r = low + Math.floor( Math.random() * ( high - low + 1 ) );
var found = false;
for ( var i = 0; i < theArray.length; ++i )
{
if ( theArray[i] == r )
{
found = true; // oops...number is already in the array
break; // might as well break out of the loop
}
}
if ( ! found ) /* if the number was *NOT* already in the array... */
{
theArray.push( r ); // put it onto the end of the array
return; // done! added a random integer...only way out of the loop
}
} // end of infinite while loop
}

Old Pedant
01-12-2011, 12:01 AM
DOH ON ME! Sorry! I forgot we were in the ASP forum.

I *ASSUME* that you meant you need the answer in VBScript code???

Randomize ' only do this once per ASP page!!!!!

Sub addRandomNumberToArray( ByRef theArray, low, high )
Dim r, found, i
Do While True ' loop forever
r = low + INT( RND() * ( high - low + 1 ) );
found = False
For i = 0 To UBound(theArray)
If theArray(i) = r Then
found = true ' oops...number is already in the array
Exit For ' might as well break out of the loop
End If
Next
If Not found Then ' if the number was *NOT* already in the array...
ReDim Preserve theArray( UBound(theArray) + 1 )
theArray( UBound(theArray) ) = r ' put it onto the end of the resized array
Exit Sub ' added a random integer...only way out of the loop
End If
Loop ' end of infinite while loop
End Sub

Hopefully this also shows you that, except for the fact that JS will automatically resize the array when you "push()" a new element onto it, there's no real difference between the languages other than superficial syntax changes.

macleodjb
01-14-2011, 01:59 AM
I dont know what to say. Other than you are an amazing coder. Thanks again.