📚
note
Blog
  • Initial page
  • JS-notes
    • 使用浏览器书签执行js代码
    • JSON.stringify的小技巧
    • Fisher–Yates shuffle洗牌算法
    • 打印页面
  • Web-notes
    • 在网页中引入在线字体
  • Uniapp-notes
    • swiper-item高度自适应
    • 微信小程序的图片预览兼容性处理
  • VUE-notes
    • vue-note
    • vue3-note
  • VPS-notes
    • CentOs7笔记
    • ssh小记
    • Ubuntu笔记
    • vps安全相关
    • [Google Drive笔记](VPS-notes/Google Drive笔记.md)
  • TypeScript-notes
    • ts热编译项目
    • TypeScript笔记
    • js项目转ts
  • Python-notes
    • Python爬虫笔记
    • Python笔记
  • PHP-notes
    • php笔记
    • php+redis
    • php-codeIgniter
    • php抽奖算法
    • Laravel笔记
  • Mobile-notes
    • 移动端常用样式及兼容相关
  • Linux-notes
    • linux常用指令
  • Game-notes
    • Minecraft-server
  • TelegramBot-notes
    • tg-bot小记
  • Windows-notes
    • window-note
    • node-note
    • WSL-note
  • RaspberryPi-notes
    • RaspberryPi-note
    • 其他玩法
    • Openwrt
    • Ubuntu安装指南
  • Phone-notes
    • ZenFone6-note
  • Cocos-notes
    • Cocos-note
  • Network-notes
    • 单线复用
  • Other-notes
    • 国际化地域标识码
Powered by GitBook
On this page

Was this helpful?

  1. JS-notes

Fisher–Yates shuffle洗牌算法

Last updated 2 years ago

Was this helpful?

引用地址:

它给出了 1 到 N 的数字的的随机排列,具体步骤如下:

  1. 写下从 1 到 N 的数字

  2. 取一个从 1 到剩下的数字(包括这个数字)的随机数 k

  3. 从低位开始,得到第 k 个数字(这个数字还没有被取出),把它写在独立的一个列表的最后一位

  4. 重复第 2 步,直到所有的数字都被取出

  5. 第 3 步写出的这个序列,现在就是原始数字的随机排列

已经证明如果第 2 步取出的数字是真随机的,那么最后得到的排序一定也是。

/**
 * Fisher–Yates shuffle
 */
Array.prototype.shuffle = function() {
    var input = this;

    for (var i = input.length-1; i >=0; i--) {

        var randomIndex = Math.floor(Math.random()*(i+1));
        var itemAtIndex = input[randomIndex];

        input[randomIndex] = input[i];
        input[i] = itemAtIndex;
    }
    return input;
}
Fisher–Yates shuffle 洗牌算法