SamuZai
DavidKahlVFX
DavidKahlVFX

patreon


Quicktip #13 Keep guessing with Do While

While playing with different ideas around the rubiks cube I stumpled on one problem that might happen in many different projects. So I am going to share it as a quicktip in case it helps anyone. Or just learn how the do while loop works. :-p

I created an array with all the possible moves the cube can use. With the rand function I grab one item from that option array to create my own random shuffle sequence to mix up the cube.

Works quite good but I noticed that sometimes I get a 2nd move that simply negates the previous one. Waste of time and energy so what to do. I could pick the next one in line but then I run in danger to leave the bounds of the array. And I did not want to create an array workaround again. 

This would be an even bigger problem if you have a more complex relation between the array elements. So why not simply take another random number with a different seed. 

And this is when the while loop comes in handy.  And in this case I used the do while loop. The only difference between the two is that do-while is always processed at least once.

In my case elements that are not allowed to go together are letters like "S" with a negated "-S" or the other way around. Whenever that is the case - I test that with the find function - the while condition " leave is not 1" is given by setting it to zero. Now I have to make sure that I actually change what I use to get a random value- Otherwise I would get the same result and place myself into a deadlock.

By increasing the variable shift I basicly change my seed and this keeps going until I find a better choice. Then I leave the loop.   

Whenever you have restictions for the randomly chosen elements this is one way to solve that issue.

Let me know if that was helpful.

Cheers

Dave

Quicktip #13 Keep guessing with Do While

More Creators