Go Down

Topic: For loop, try again (Read 510 times) previous topic - next topic

stoopkid

Im using a for loop to change an amount of items in an array. But it is changing them randomly, and I cant have to change the same one twice, so i need a dynamic way to keep from choosing the same number twice since I dont know how many of them will be changed at a time. Luckily I can easily see if it has already been changed by seeing if it equals 1. So i need to know how to "try again", or in other words, add another loop to a for loop.

Code: [Select]

for(int x = 1;x<=NumberToChange;x++){        //For how many items need to be changed
tempVal = random(0, arraySize)               //tempVal = a random items number
if (myArray[tempVal] == 1){                  //if the array item is already set to 1:
                                             //TRY AGAIN
}
else{                                        //if the array item is NOT already set to 1:
myArray[tempVal] = 1;                        //set the array items to 1
}
}


where it says //TRY AGAIN i need to tell it to attempt that loop again. Can i simply use x--?

thanks

PaulS

Inside the for loop, you need a while loop.

Code: [Select]
for(int x = 1;x<=NumberToChange;x++)
{
   boolean stillNeedToChange = true;
   while(stillNeedToChange)
   {
      tempVal = random(0, arraySize);   //tempVal = a random item's index
      if (myArray[tempVal] == 0)
      {
         myArray[tempVal] = 1;
         stillNeedToChange = false;
      }
   }
}


Go Up