Skip to content Skip to sidebar Skip to footer

Random Repeated Sequence In Javascript

I wrote this Matlab code to generate a vector of random [1 0] and [2 0]: nTrials = 8; Seq1 = [1 0]; % sequence 1 Seq2 = [2 0]; % sequence 2 a=repmat(Seq1,(nTrials/4),1); b=repma

Solution 1:

Sooo i just built a nice tiny documented function for you:

functionrandomRepeatSequence(sequences, times) {
    // times has to be a multiple of sequences.lengthif (times % sequences.length !== 0)
        returnconsole.log("times has to be a multiple of sequences.length");

    // Remap our sequence-array so we can store the count it has been usedvar seqmap = [];
    for (var seqid = 0; seqid < sequences.length; seqid++)
        // Push the current sequence n times; n = times/sequences.lengthfor (var idx = 0; idx < times/sequences.length; idx++)
            seqmap.push(sequences[seqid]);

    var resultmap = [];
    // Now just select and remove a random sequence from our seqmap, until it is emptywhile (!seqmap.length == 0) {
        // Select a random elementvar randomidx = Math.floor(Math.random()*seqmap.length);
        var currentElement = seqmap[randomidx];
        // remove the random element from seqmap...
        seqmap.splice(randomidx, 1);
        // .. and push it to the resultmap
        resultmap.push(currentElement);
    }

    // now our resultmap looks like [[1],[2],[3]]... just flatten it!var result = resultmap.reduce( function(a, b) {
        return a.concat(b);
    });

    return result;      
}

You can use it just like

console.log(randomRepeatSequence([[1,0], [2,0]], 4));

Or, better to understand:

var seqlist = [
    [1, 0],
    [2, 0]
]
randomRepeatSequence(seqlist, 4)

Please care, the times parameter just takes the amount of sequences that have to be used, not the length of the result. But you just have to calculate that in a easy step like

randomRepeatSequence(seqlist, 8/seqlist[0].length)

(giving 4, because seqlist[0].length = 2 and 8 / 2 is 4)


Original Answer

Your result is for example

vector = 20102010

I guess seq1 and seq2 should be contained equal times. I decided to use an easy-to-understand-approach, even through I can do shorter:

var trials = 8; // has to be evenvar seq1 = [1, 0];
var seq2 = [2, 0];

// "Build" a sequence listvar seqlist = [
    seq1, seq1,
    seq2, seq2
]

var list = []

for (var n = 0; n < trials/2; n++) {
    // search a random entryvar index = Math.floor(Math.random()*seqlist.length);
    var toUseSeq = seqlist[index];

    // delete the entry
    seqlist.splice(index, 1);

    list.push(toUseSeq);
}
// flatten result arrayvar result = list.reduce( function(a, b) {
    return a.concat(b);
});

console.log(result);

Executing this gaves me one of these console outputs:

[ 2, 0, 1, 0, 2, 0, 1, 0 ][ 2, 0, 1, 0, 2, 0, 1, 0 ][ 1, 0, 1, 0, 2, 0, 2, 0 ][ 1, 0, 2, 0, 1, 0, 2, 0 ]

Post a Comment for "Random Repeated Sequence In Javascript"