码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript实现shuffle数组洗牌操作示例

时间:2019-02-18 18:49:07      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:png   ==   tab   result   org   div   w3c   需要   验证   

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JavaScript shuffle数组洗牌</title>
<body>
<script>
function createArray(max) {
  const arr = [];
  for(let i = 0; i < max; i++) {
    arr.push(i);
  }
  return arr;
}
function shuffleSort(arr) {
  arr.sort(()=> {
    //返回值大于0,表示需要交换;小于等于0表示不需要交换
    return Math.random() > .5 ? -1 : 1;
  });
  return arr;
}
function shuffleSwap(arr) {
  if(arr.length == 1) return arr;
  //正向思路
//  for(let i = 0, n = arr.length; i < arr.length - 1; i++, n--) {
//    let j = i + Math.floor(Math.random() * n);
  //逆向思路
  let i = arr.length;
  while(--i > 1) {
    //Math.floor 和 parseInt 和 >>>0 和 ~~ 效果一样都是取整
    let j = Math.floor(Math.random() * (i+1));
    /*
    //原始写法
    let tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
    */
    //es6的写法
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  return arr;
}
function wrap(fn, max) {
  const startTime = new Date().getTime();
  const arr = createArray(max);
  const result = fn(arr);
  const endTime = new Date().getTime();
  const cost = endTime - startTime;
  console.log(arr);
  console.log("cost : " + cost);
}
wrap(shuffleSort, 1000);
wrap(shuffleSwap, 1000);//试验证明这种方法比第一种效率高多了
</script>
</body>
</html>

这里使用在线HTML/CSS/JavaScript代码运行工具http://tools.jb51.net/code/HtmlJsRun测试上述代码,可得如下运行结果:

技术图片

JavaScript实现shuffle数组洗牌操作示例

标签:png   ==   tab   result   org   div   w3c   需要   验证   

原文地址:https://www.cnblogs.com/raineliflor/p/10397070.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!