#Redo an iteration of a loop?

1 messages · Page 1 of 1 (latest)

cedar flicker
#

I think this is what it is at least, basically, I have an For Loop that instantiate some objects at certain coordinates at random, to avoid the objects overlapping, I have the coordinates for each new one in an array, on which I check during the loop.

What I want to do is: If the coordinates of this iteration matches with one already in the array, it redo that iteration with a new coordinate.

I'm using > if array_name.has(object_name.position):

So, is there a good way to repeat this iteration only?

valid glen
#

Perhaps a nested while-loop?

for e in ...:
    position = random_stuff(...)
    while array_name.has(position):
        position = random_stuff(...)
```OR

for e in ...:
while true:
position = random_stuff(...)
if not array_name.has(position):
break

#

Also in situations with collisions in random numbers, sometimes there is a way to avoid the collisions to begin with

For example, if you want to pick to different numbers from 1 to 6 you can do something like:

var possible_values: Array[int] = [1, 2, 3, 4, 5, 6]
possible_values.shuffle()
var val_1 = possible_values[0]
var val_2 = possible_values[1]
```This guarantees that the numbers are different and also runs without any unpredictable loops
cedar flicker
#

I'll try the first two options, as the third one is not really what I'm doing, but thanks anyway.
I'll return after testing to say if it worked or not

cedar flicker
#

@valid glen Well, with a bit of code shenanigans, it worked! So thank you very much

valid glen
#

Good to hear! Happy to help

quaint thicket
#

You could just peek at the next index before it increments.

Let myarr = array [1, 2, 3];

For i in 0..myarr.len() {
//do stuff
if myarr[i +1] == 2 { i++; }
}

If that doesnt help you could finish building the array, then search it for coordinates that are the same, remove them, regenerate random coordinates depending on how many you removed. Would avoid O(n^2)

cedar flicker
quaint thicket
#

Sorry, pseudo code on mobile.

len() being the length of the array and i++ is incrementing the index by 1.

So at index 1 we check if the next index of the array (we peek at it) has value 2, which is true. Then we increment the index variable by 1 "manually".

The index is now at two even though were still in the same scope. When the function exits, it also increments the index by 1, putting us at 3. Skipping over 2.

Though after reading your q again I dont think it will really help. The second option would be better.

Unless gdscript offers a method on dictionaries that checks if a key already exists before inserting a new one. That could be another alternative.