<!-- <h1>Fisher–Yates shuffle 洗牌算法</h1>
<p style="max-width:650px">
  简单来说 Fisher–Yates shuffle 算法是一个用来将一个有限集合生成一个随机排列的算法。这个算法生成的随机排列是等概率的。同时这个算法非常高效。
</p> -->
<div class="row">

  <div class="wrap"></div>
  <div class="info">
    <p>
      当前随机数为:<span class="randomIndex"></span>
    </p>
    <p>
      待交换的位置为:<span class="index">19</span>
    </p>
    <p>
      (第一个位置记为 0,最后一个位置为 19)
    </p>

  </div>
</div>
.wrap {
  width: 330px;
  height: 250px;
  position: relative;
  float: left;
}

.bar {
  position: absolute;
  bottom: 0;
  margin: 5px;
  width: 10px;
  /*height: 100px;*/
  background-color: rgb(73, 82, 131);
  transition: 1s ease;
}

.info {
  float: left;
  margin-top: 120px;
}
    /**
     * Fisher–Yates shuffle
     */
    Array.prototype.shuffle = function() {

      var input = this;

      setTimeout(function() {

        (function() {
          var arr = input,
            len = arr.length;

          (function doProcess() {
            if (len--) {
              /* do something with arr[len] */
              // debugger
              var randomIndex = Math.floor(Math.random() * (len + 1));

              document.querySelector('.randomIndex').innerHTML = randomIndex;
              document.querySelector('.index').innerHTML = len;

              var itemAtIndex = input[randomIndex];

              input[randomIndex] = input[len];
              input[len] = itemAtIndex;

              exchange(randomIndex, len);

              // console.log(len);
              setTimeout(doProcess, 1500);
            }
          })();
        })();
      }, 1500);
      return input;
    };

    var arr = [
      1,
      2,
      3,
      4,
      5,
      6,
      7,
      8,
      9,
      10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
    ];

    render(arr);

    arr.shuffle()

    /**
     * 渲染
     */
    function render(arr) {
      var wrap = document.querySelector('.wrap');
      for (var i = 0; i < arr.length; i++) {
        wrap.insertAdjacentHTML('beforeend', '<div class="bar" style="height:' + arr[i] * 12 + 'px;left:' + i * 15 + 'px" pos="' + i + '"></div>');
      }
    }

    /**
     * 交换
     */
    function exchange(i, j) {

      console.log(i, j);
      var iDiv = document.querySelector('.wrap [pos="' + i + '"]');
      var jDiv = document.querySelector('.wrap [pos="' + j + '"]');

      var iLeft = iDiv.style.left;
      var jLeft = jDiv.style.left;

      iDiv.style.left = jLeft;
      jDiv.style.left = iLeft;

      iDiv.setAttribute('pos', j);
      jDiv.setAttribute('pos', i);
    }

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.