Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第二十七题:用洗牌算法实现一个打乱数组的方法 #27

Open
Ray-56 opened this issue Sep 16, 2019 · 3 comments
Open

第二十七题:用洗牌算法实现一个打乱数组的方法 #27

Ray-56 opened this issue Sep 16, 2019 · 3 comments
Labels
JavaScript 解释型编程语言

Comments

@Ray-56
Copy link
Owner

Ray-56 commented Sep 16, 2019

用洗牌算法实现一个打乱数组的方法

@Ray-56 Ray-56 added the JavaScript 解释型编程语言 label Sep 16, 2019
@GenXiaoLe
Copy link
Collaborator

  Array. prototype.shuffle = function() {
    var _self = this;

    for (var i = _self.length - 1; i >= 0; i--) {
      var random = Math.floor(Math.random() * (i + 1));
      var randomItem = _self[random];

      _self[random] = _self[i];
      _self[i] = randomItem;
    }

    return _self;
  }

  [1, 2, 3, 4,  5, 6].shuffle();

@lamelamb
Copy link

核心是实现一个伪随机数,最容易想到Math.random ,当然也可以利用数学常用的方法,比如对 -1 取随机的数进行 幂运算,然后和0 比较
有了随机数,就可以对数组操作了,当然每次后都要将渠道的值从原来的数组删掉,同时随机数的范围减去一,为了不对原数组造成印象,所以在最开始之前要拷贝原数组,操作副本

@MMmaXingXing
Copy link

洗牌算法

Fisher-Yates洗牌算法也被称为高纳德置乱算法,作用就是生成一个有限集合的随机排序。

代码实现

var arr = [];

for (let i = 0; i < 10; i++) {
    arr[i] = i + 1;
}

for (let i = arr.length - 1; i > 0; i--) {
    let rand = Math.round(Math.random() * i);

    let temp = arr[i];
    arr[i] = arr[rand];
    arr[rand] = temp;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript 解释型编程语言
Projects
None yet
Development

No branches or pull requests

4 participants