数组顺序随机打乱

78 阅读1分钟
  const shuffleOptions = (options: string[], seed: number) => {
    // 对于相同的种子,每次调用 `seededRandom` 都会生成相同的伪随机数序列。
    const rng = seededRandom(seed);
    // 进行数组顺序打乱
    const indexedArray = options?.map((value, index) => ({ value, index }));
    for (let i = indexedArray.length - 1; i > 0; i--) {
      const j = Math.floor(rng * (i + 1));
      [indexedArray[i], indexedArray[j]] = [indexedArray[j], indexedArray[i]];
    }
    const shuffledArray = indexedArray.map((item) => item.value);

    return shuffledArray;
  };