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

  • Remi Monedi

    March 14, 2020 at 9:05 am

    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.

  • Andrei Popa

    March 16, 2020 at 9:21 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.

  • Remi Monedi

    March 16, 2020 at 10:47 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?

  • Andrei Popa

    March 17, 2020 at 6:25 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.

  • Remi Monedi

    March 18, 2020 at 7:48 pm

    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

Log in to reply.

We use anonymous cookies to give you the best experience we can.
Our Privacy policy | GDPR Policy