Is there a way in javascript to scramble numbers where the outcome is consistent?

282 Views Asked by At

So I need to be able to scramble numbers around but have the outcome always be consistent. Meaning, if I scrambled 1234 and it gave me something like 2143, if I ran the scramble function again it would result in 2143 again.

Is anyone aware of a way to do this?

1

There are 1 best solutions below

0
georg On

One simple solution would be to treat numbers as character arrays and shuffle them using a seedable random generator, e.g. an LCG, using the number itself as a seed.

function scramble(n) {
    let rnd = n;

    let a = 1103515245,
        c = 12345,
        m = 1 << 30;

    let s = [...String(n)];

    for (let i = s.length - 1; i > 0; i--) {
        rnd = (rnd * a + c) % m;

        let r = rnd % i;
        let t = s[i];
        s[i] = s[r];
        s[r] = t;
    }

    return Number(s.join(''));
}


for (let n = 1234; n < 1284; n++) {
    let h = scramble(n)
    console.log(n, h)
}

References: