# Creative Communities of the World Forums

The peer to peer support community for media production professionals.

Forums Adobe After Effects Expressions Random expression with exceptions

• # Random expression with exceptions

• I didn’t find my answer on the web nor here so I’m asking directly :
I’d like to make a random expression which goes from 1 to 10 for instance but with exceptions like 2, 4 and 6. These exceptions could be changing so this is why I’m not doing a random expression based only on the other numbers.

I tried to achieve it using if/else statements :
If random number = exception 1 add 1 to it
but first it’s quite messy and there are many flaws especially with several exceptions.

Are you aware of a more efficient way?

Have a great weekend

UPDATE : I found the “while” statement could be, theoretically, the solution by looping the random expression until it gives a correct value, but when I use in AE, AE turns veryyy slow or even doesn’t calculate it due to a Timeout while waiting for the engine.

• I think this will work

exceptions = [2,4,6];
randomSeed=time*thisComp.frameDuration;
result=Math.round(Math.random(10));
while(exceptions.indexOf(result)!=-1){
randomSeed+=Math.round(Math.random(100));
result=Math.round(Math.random(10));
}
result

Andrei
My Envato portfolio.

• Hi Andrei,

I tried to give your expression a shot in AE but I have several error messages :
– first “Math.random()” is not a function. I replaced them by simply “random()”
– “exceptions.indexOf” is undefined and since I’m not sure what this line is for I don’t know how to fix it. Any idea?

• Do you have After Effects 2019 or later? If yes, go to Project Settings>Expressions and set the Expression Engine to Javascript.

If you do not wish to change your Expression Engine to Javascript(I suggest you do), you can use this expression:

` function include(arr, obj) { for (var i = 0; i < arr.length; i++) { if (arr[i] == obj) return true; } }`

`exceptions = [2,4,6]; randomSeed=time*thisComp.frameDuration; result=Math.round(random(10)); while(include(exceptions,result)){ randomSeed+=Math.round(random(100)); result=Math.round(random(10)); } result `

Andrei
My Envato portfolio.

• This works great!
Thanks for giving me the “no Javascript engine” version since I work on an older version of AE.

Viewing 1 - 5 of 5 posts