Go Down

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

#### stoopkid

##### Feb 26, 2011, 01:07 pm
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 changedtempVal = random(0, arraySize)               //tempVal = a random items numberif (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

#1
##### Feb 26, 2011, 01:39 pm
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;      }   }}`

#### stoopkid

#2
##### Feb 26, 2011, 01:41 pm
perfect, thank you

Go Up

Please enter a valid email to subscribe