dimanche 9 janvier 2022

Shuffle array of N letters and take M of them

I have an X array of objects "letter":"frequency" and i'm trying to build a new Y array from the previous one made of frequency-times letters (for each present in X ary). Then my purpose is to shuffle Y ary and take just the z-first elements from that. n is an argument passed to the function

const letters = rows.map((e) => ({ letter: e.letter, frequency: e.frequency }));
            let freqLetters = [];
            for (let letter in letters) {
                for (let i = 0; i <= letter.frequency * 100; i++) {
                    freqLetters.push(letter);
                }
            };

            shuffleArray(freqLetters);
            freqLetters.slice(0, n);

            resolve(freqLetters);

Why this algorithm doesn't work? Shuffle function is:

function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
}



Aucun commentaire:

Enregistrer un commentaire