I'm doing a java program using random numbers.
I would like to avoid that each generated number, besides unique, is different from its index in array - for instance, the first number in array is not number 1, the second is not number 2, the third not number 3, and so one.
Can someone help ?
Thatīs my relevant code :
boolean isRepeated = false;
int [] rNums = new int [t1];
for (int x = 0 ; x < t1 ; x++)
{
do
{
isRepeated = false;
rNums [x] = (int) ((Math.random () * t1) + 1);
for (int y = 0 ; y < x ; y++)
{
if (rNums [x] == rNums [y])
{
isRepeated = true;
break;
}
}
}
while (isRepeated);
12-03-2005, 01:35 PM
evlich
Java arrays are indexed starting at 0, so is it that you don't want the first element in an array to be 0 or you don't want it to be 1?
You could just do something like this:
Code:
public static int randNotNum(int max, int num) {
do {
int res = (int) ((Math.random () * max) + 1);
if( res != num ) return res;
} while( true );
}
Then just make calls and pass in the maximum number and the number that you don't want to get back.