Public
Authored by Khia Johnson

Pseudorandomization code snippet for JavaScript

Some toy arrays to illustrate this:

var fillers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] //...etc
var targets = ['A', 'B', 'C', 'D', 'E'] //...etc

Generate a pseudo-randomized set of indexes for final array. Conditions for pseudo-randomizing are set inside the loop. Currently it requires a burn in of 5 items, and a minimum of one filler between targets.

var max = fillers.length + targets.length;
var indices = [];
while (indices.length < targets.length) {
    var n = Math.floor(Math.random() * max);
    if (n > 5 && !indices.includes(n) && !indices.includes(n+1) && !indices.includes(n-1)) {
        indices.push(n);
    }
}

Sort the indicies into ascending order, and add the targets in at the specified indices:

indices.sort(function (a, b) {
    return a - b
});

var stimuli = fillers;
var i;
for (i = 0; i < ins.length; i++) {
    var fs = targets.pop();
    stimuli.splice(ins[i], 0, fs);
}

This might output something like: [1, 2, 3, 4, 5, 6, 7, 'A', 8, 'B', 9, 10, 11, 'C', 12, 13, 'D', 14, 15, 16, 17, 18, 19, 20, 'E']

code.js 625 Bytes
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment