mercredi 18 août 2021

How can I move elements from one array to another pseudo-randomly using a hash?

Picture two different arrays:

let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let newArr = [];

What I'm trying to achieve is moving elements from arr to newArr via a pseudo-random loop, that attempts to mimic the functionality of Math.random(), except that the only randomness should go against a fixed, hash number.

I was trying something like this, but no luck so far:

const madeUpHash = "827354819373"
const floatIndex = "0."
const f = parseFloat(floatIndex + madeUpHash);

let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let newArr = [];

for (let i = 0; i < arr.length; i++) {
  let ranNum = (f/i); // this points towards 0, meaning the next Math.Floor will eventually always retrieve index 0
    let rand = Math.floor(ranNum * arr.length);
    newArr.push(...arr.splice(rand, 1))
}

Not only does this not work, it's also pretty horrible.
Is there any reliable way to achieve this? My other idea would be to loop through the individual digits of the hash (after transforming them into an array) and create a random number such as ranNum = i/madeUpHash[i] but that would break as soon as i >= madeUpHash[i] since it would return a positive integer bigger than one.

Any ideas? Thank you.




Aucun commentaire:

Enregistrer un commentaire