Selecting a random state

Hello,

I am humbly asking for programming help regarding the random activation of states, I have a controller containing 10 states. I want to add code to my “triggerenter” script that will activate one of these 10 states at random every time the trigger zone is entered. The states are named “state1” to “state10” inside a controller named “OnStates”. Here<s what I have so far (just the random generator and an audio file):

const C2_wav = symbol.nodes.C2_wav;
var orbState = Math.ceil(Math.random() *9);

parent.on(“triggerenter”, (e) => {

C2_wav.start();

});

Thank you for any kind of help :slight_smile:

1 Like

Are you looking to just pick one of the 10 each time or random each time less the last set (if 10 was picked it would not be picked 10 agen till all the rest where picked)

Steve

Hi,
one very easy solution should be to use a switch statement:

// create your random number...   
switch( your_random_number ) {
    case  0 :
        state1.activate();
        break;
    case  1 :
        ...

    default:
        break;
}

Cheers,

1 Like

Hi Steve,

Thank you so much for your reply. In fact, I would just need it to pick 1 in 10 each time, without removing the picked number from the pool.

1 Like

Hi jvouillon

Thank you very much for this; I’ll try it right away and let you know how it goes!

Cheers

1 Like

The Switch statement works great! I was trying to replace the number in the state name by a variable, but that was impossible (state(var)).activate

Thank you jvouillon!

Steve, if you have the time, I’d very much be interested in knowing how I could remove the picked random number from the pool.

Thanks all for the help!
Tom

2 Likes

Perhaps Steve will have something simpler :grin:

But a way, is to keep track of the picked number with an array of booleans.

The idea is to use the picked value as an index to set the corresponding item to true.

The random function must be set inside a while loop which checks if the item at the picked number is true (true = repeat the random, false = exit).

When exiting the loop, set the array item to true (array[number_picked] == true;).

Last thing, you need also a counter to keep track of the picked numbers, in order to reset the items array to false when all the numbers have been picked.

Cheers,

Like @jvouillon said you use an array but I found some code that moves the first one to the end and mixes up the array. https://bost.ocks.org/mike/shuffle/
I used the code at the bottom of the page.
Here is a cut down and non working ( you have to add things to it) zpp file to look at.
Random State help.zpp (3.8 KB)

Steve

Thanks Stevve, I’ll take a look at it when I get home!

1 Like