Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Random Number Chooser programming exercise

Venny Tank
Greenhorn
Posts: 7
Hi, guys

Write a method that returns a random number between 1 and 54, excluding the numbers passed in the argument.
The method header is specified as follows:

The code I've wrote:

The end result for the random generated number should be a value different from the numbers in the array.
In this code I've managed to generate new random if the generated number is equal to one of the numbers in the array, but can't figure out how to test the new value again.
Could you point me the right direction to find my mistake?

Thanks a lot

Manoj Kumar Jain
Ranch Hand
Posts: 198
as I can see in your logic it has a bug. when

will check that the random no. generated is not equal to the current item in the array numbers[i] and onwards but what about the previous items ??. It doesn't consider the case in which it can be equal to the previous item in the list that is already checked.

for example take the case that you first generated the random no. as 22 in the for loop and then you generated the no. 10 in the while loop

Manoj Kumar Jain
Ranch Hand
Posts: 198
I will suggest you to use list and use its contains() method to check if the no. generated should be excluded, if it says yes then generate new no. and check again else you have the no.

Campbell Ritchie
Sheriff
Posts: 50733
83
Random numbers do not support any relationship between themselves. If you are constrained not to use the same number twice, that is not random numbers. I think it is called random selection from a shrinking population.

Venny Tank
Greenhorn
Posts: 7
Manoj Kumar Jain wrote:as I can see in your logic it has a bug. when

will check that the random no. generated is not equal to the current item in the array numbers[i] and onwards but what about the previous items ??. It doesn't consider the case in which it can be equal to the previous item in the list that is already checked.

for example take the case that you first generated the random no. as 22 in the for loop and then you generated the no. 10 in the while loop

I'm still on single dimensional arrays chapter of the book that I'm learning from and can't use any more advanced techniques than that.
Is there any way I can check the random number against previous items?

fred rosenberger
lowercase baba
Bartender
Posts: 12234
36
you would have to keep a list of which ones you found, and each time you want a new one, make sure it isn't already in your list. If it is, you have to select again

Note that the more numbers you select, the slower it will become as you may have to re-try more and more often.

Alternatively, you could move them around...i.e. each time you pick a value, move it to the end of the array, and then next time select a value from 0 to (n-1)...