Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

สับเปลี่ยนลำดับอาร์เรย์แบบสุ่ม (Shuffle) - JavaScript

อาร์เรย์: ['a', 'b', 'c', 'd', 'e', 'f', 'g']

สับเปลี่ยน in-place ด้วยการสุ่มตำแหน่งและย้าย

ตัวอย่างโค้ด

const letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const unorderArray = arr => {
  let i, pos, temp;
  for (i = 0; i < 100; i++) {
    pos = Math.random() * arr.length | 0;
    temp = arr[pos];
    arr.splice(pos, 1);
    arr.push(temp);
  }
};
unorderArray(letters);
console.log(letters);

ผลลัพธ์

[ 'b', 'e', 'c', 'a', 'g', 'f', 'd' ]

คำอธิบาย: ทำ 100 รอบ สุ่ม index pos นำ element ตัวนั้นออก (splice) ใส่ท้าย (push) - เป็นวิธี shuffle แบบ naive

แนะนำ Fisher-Yates (Knuth) Shuffle: for (let i = arr.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [arr[i], arr[j]] = [arr[j], arr[i]]; } เป็น unbiased และ O(n)