“Mélanger un tableau” Réponses codées

javascript remanie un tableau

const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random());

console.log(shuffleArray([1, 2, 3, 4]));
// Result: [ 1, 4, 3, 2 ]
Rashid Siddique

JavaScript mélange au hasard

function randomArrayShuffle(array) {
  var 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;
}
var alphabet=["a","b","c","d","e"];
randomArrayShuffle(alphabet); 
//alphabet is now shuffled randomly = ["d", "c", "b", "e", "a"]


Grepper

tableau de tri aléatoire javascript

// O(n)
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]];
    }
}
garzj

Comment mélanger un tableau javascript

/**
 * Shuffles array in place.
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = round(random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

shuffle(array);
Timmber

Arraie de mélanger javascript

/**
 * Shuffles array in place.
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}


/**
 * Shuffles array in place. ES6 version
 * @param {Array} a items An array containing the items.
 */
function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);
Blue Bear

mélanger un tableau

let array = [1, 2, 3, 4, 5];

for(let i = array.length - 1; i >= 1; i--) {
   let j = Math.floor(Math.random() * (i + 1)); // 0 <= j <= i
   let temp = array[j];
   array[j] = array[i];
   array[i] = temp;
}
console.log(array);
Prickly Plover

Réponses similaires à “Mélanger un tableau”

Questions similaires à “Mélanger un tableau”

Plus de réponses similaires à “Mélanger un tableau” dans JavaScript

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code