We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I want to generate sets of coordinates consisting of X and Y, but I want every set to be different. Everytime I restart the program the sets are different to the last time I ran the program but all sets have the same X and the same Y.
void setStars()
{
int randX = 10, randY = 10; // the random X and Y coordinates will be saved in here
boolean genNew = true; // determines, if we need to regenerate the set of coordiantes
for (int i = 0; i < starsCount; i++) // starsCount is the number of sets I want
{
while (genNew) // while the generated X and Y matches an other set
{
randX = (int)random(10, windowWidth-10); // generate the set
randY = (int)random(10, windowHeight-10);
genNew = false;
for (int j = 0; j < starsX.size(); j++)
{
if (randX == starsX.get(j) && randY == starsY.get(j)) // if the generated X and Y matches a set
{
genNew = true; // Generate a new set (basically continue the while loop)
break;
}
}
}
starsX.add(randX); // add the generated random X and Y to the ArrayLists
starsY.add(randY);
}
}
I hope that you will help me solve this problem.
regards, TPRammus
EDIT: Thank you all! Now I see my error. I fixed it by adding "genNew = true;" to the beginning of my for(i)-loop.
Answers
genNew is the problem. your while runs the first time (genNew = true on line 4), but never again (gets set to false on line 12)
set it to false inside the for(i) loop. remove line 12. change the condition to
while ( ! genNew )
(untested. runnable examples are always better)
When the break at line 18 is executed it will exit the innermost loop, in other words the loop in lines 13-20 so the break will take you to line 23 so the duplicate star position will still be added to the list. You need to make sure genNew is false before doing lines 23 and 24. So changing lines 23 and 4 to
should solve the problem (Not tested)
I found your logic a bit confusing so here is my version