Code Monkey home page Code Monkey logo

Comments (3)

GenXiaoLe avatar GenXiaoLe commented on August 13, 2024
  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();

from daily.

lamelamb avatar lamelamb commented on August 13, 2024

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

from daily.

MMmaXingXing avatar MMmaXingXing commented on August 13, 2024

洗牌算法

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;
}

from daily.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.