Creative Communities of the World Forums

The peer to peer support community for media production professionals.

Activity Forums Adobe After Effects Expressions Randomize numbers without having the same value occuring twice?

  • Randomize numbers without having the same value occuring twice?

    Posted by Mikael Holmström on June 28, 2021 at 1:57 pm

    Hi,

    Let’s say I have ten layers of text. By an expression I’d like to assign text of sourceText a value between 1 and 10. I want them to be randomly ordered, but never to occur twice within my 10 text later. So, the result could look something like this (layer by layer):

    [5, 3, 1, 8, 2, 9, 4, 7, 6]

    But never, for instance:

    [5, 3, 1, 1, 2, 9, 4, 7, 6]

    Is there a way to accomplish this?

    Andrei Popa replied 5 years, 1 month ago 2 Members · 1 Reply
  • 1 Reply
  • Andrei Popa

    June 28, 2021 at 3:12 pm

    You can make a master layer, and add this expression to text

    function shuffle(array) {
    var currentIndex = array.length, randomIndex;
    // While there remain elements to shuffle...
    while (0 !== currentIndex) {
    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;
    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
    array[randomIndex], array[currentIndex]];
    }
    return array;
    }
    var arr = [1,2,3,4,5,6,7,8,9,10];
    "["+shuffle(arr).join(",")+"]"

    Then, to each layer add this expression. Assign firstIndex as the index of your first text layer.

    firstIndex = 2;

    val = eval(thisComp.layer("Master layer").text.sourceText)[index-firstIndex];

    val

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