ADOBE AFTER EFFECTS: Forum Expressions Tutorials Creative Cloud

Random expression with exceptions

COW Forums : Adobe After Effects Expressions

<< PREVIOUS   •   FAQ   •   VIEW ALL   •   PRINT   •   NEXT >>
Remi Monedi
Random expression with exceptions
on Mar 14, 2020 at 9:05:38 am
Last Edited By Remi Monedi on Mar 14, 2020 at 4:54:02 pm

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.


Return to posts index

Andrei Popa
Re: Random expression with exceptions
on Mar 16, 2020 at 9:21:41 am

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.


Return to posts index

Remi Monedi
Re: Random expression with exceptions
on Mar 16, 2020 at 10:47:28 pm

Hi Andrei,

Thank you for the answer!

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?


Return to posts index


Andrei Popa
Re: Random expression with exceptions
on Mar 17, 2020 at 6:25:37 pm

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.


Return to posts index

Remi Monedi
Re: Random expression with exceptions
on Mar 18, 2020 at 7:48:13 pm

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


Return to posts index

<< PREVIOUS   •   VIEW ALL   •   PRINT   •   NEXT >>
© 2020 CreativeCOW.net All Rights Reserved
[TOP]