I want to generate random numbers within a range and the generated numbers should not collide within some range.
i used following code but im getting Stackoverflow error.. Any better solution?
static int [] xPositions=new int[10];
int WIDTH=700
public static void main(String args[])throws IOException
{
if(generateRandomXPositions(10)){
for(int i=0;i<10;i++){
System.out.println(" Random Numbers "+i+" :"+xPositions[i]);
}
}
}
private static boolean generateRandomXPositions(int n) {
for(int i=0;i<10;i++){
int temp=((int)0 + (int)(Math.random() * ((WIDTH - 0) + 1)));
for(int j=0;j<xPositions.length;j++){
if(xPositions[j]>temp-50 && xPositions[j]<temp+50){ // IF GENERATED NUMBER IS IN THIS RANGE IT SHOULD REGENERATE THE NUMBERS
generateRandomXPositions(10);
}
}
xPositions[i]=temp;
}
return true;
}
I know problem is here
if(xPositions[j]>temp-50 && xPositions[j]<temp+50).
Below one works fine
`if(xPositions[j]==temp)`.
But I need that random numbers should follow that range! .
Many are wondering about the exit condition of recursive loop. But I believe if random number is not in that range, then there is no point of entering in to the recursive loop.
UPDATE 1:
And I believe compiler is tired to find the number between this range! Now I found that it is impossible fit 10 images having width of 100px each in to the 700px width container without colliding X positions!
Please see the image below. Lets imagine i want to place this boxes randomly without colliding... how can i do that?
if(xPositions[j]>temp && xPositions[j]<temp)
will always evaluate tofalse
. – S.L. Barth Oct 3 at 9:45xPositions
? I think your program would have better performance if you used this line:for(int j=i+1 ;j<xPositions.length;j++)
- but I'm not sure if it has the same semantics. – S.L. Barth Oct 3 at 10:04