dimanche 25 avril 2021

Shuffle an Array is giving the same value in Javascript

I'm making a generator of random arrays shuffling one initial array multiple times.

SHUFFLE FUNCTION

const shuffle =(array) => {
    let currentIndex = array.length, temporaryValue, randomIndex;
    while (0 !== currentIndex) {
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }
    return array;
}

GENERATE CHROMOSOMES(This function generates an array of arrays that are randomized from an initial one "sequence")

const generateChromosomes = (numberOfChromosomes) =>{
    const result = [];
    const sequence = ["2", "3", "4"];

    for(let i = 1; i < numberOfChromosomes; i++){
        result.push(shuffle(sequence))
    }

    return(result);
}

I do not know why, each time when I run it, I don't get different arrays. I get 50 times the same one. When I re-run the code, it gives me 50 times another one.




Aucun commentaire:

Enregistrer un commentaire