jeudi 9 juillet 2020

Whats the trick in javascript Array.findIndex

I was trying to simulate random by probabilities, and found something interesting with Array.findIndex

const probabilities = [0.1, 0.2, 0.3];
const thresholds = probabilities.reduce((r, p, i) => r.concat((r[i - 1] || 0) + p), []);

const f1 = () => thresholds.findIndex(x => x > Math.random());
const f2 = () => {
    const r = Math.random();
    for (let i = 0; i < thresholds.length; i++)
        if (r < thresholds[i])
            return i;
    return -1;
};

const run = (f) => Array.from(Array(1000000), f).reduce((r, x) => Object.assign(r, { [x]: 1 + (r[x] || 0) }), {});

run(f1);
run(f2);

The output results were like

{ "0": 100210, "1": 269763, "2": 377463, "-1": 252564 }
{ "0": 99381,  "1": 199927, "2": 300408, "-1": 400284 }

Apparently the Array.findIndex paired with Math.random was not working as I supposed.




Aucun commentaire:

Enregistrer un commentaire