// ======================== 洗牌 (Shuffle) 示例 ========================
// 定义一副“扑克牌”数组(仅示例,A~K)
const cards = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"];
 
// -------------------- 方法 1: 随机排序(不推荐) --------------------
// 下面这行代码会随机打乱数组顺序,但随机分布不完全均匀
// 因为 sort() 并不是为随机设计的
// cards.sort(() => Math.random() - 0.5);
 
// -------------------- 方法 2: Fisher–Yates 洗牌算法(推荐) --------------------
// 这个算法可以确保每个元素被交换的概率是均等的
// 所以结果是公平随机的
shuffle(cards);
 
// 打印打乱后的数组
console.log(cards);
 
 
// ======================== 定义洗牌函数 ========================
function shuffle(array){
 
  // 从数组最后一个元素开始,向前遍历
  // i 表示当前要交换的位置
  for(let i = array.length - 1; i > 0; i--){
 
    // 随机生成一个索引 random (0 ≤ random ≤ i)
    const random = Math.floor(Math.random() * (i + 1));
 
    // 使用解构赋值 [a, b] = [b, a] 来交换两个元素的位置
    [array[i], array[random]] = [array[random], array[i]];
 
    // 👇 展开解释:
    // 临时存储法等价于:
    // let temp = array[i];
    // array[i] = array[random];
    // array[random] = temp;
  }
}