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

第七天:Fisher–Yates Shuffle #9

Open
sofish opened this issue Apr 22, 2016 · 1 comment
Open

第七天:Fisher–Yates Shuffle #9

sofish opened this issue Apr 22, 2016 · 1 comment
Milestone

Comments

@sofish
Copy link
Owner

sofish commented Apr 22, 2016

最近有时差,昨天的任务今天来写 👎 。

昨天写了前天的任务「如何分组」。大家都会需要用到「洗牌」,而关于如何洗有多种算法,其中有一个简洁高效的算法就是 Fisher-Yates Shuffle https://bost.ocks.org/mike/shuffle/ ( 文章和演示都非常棒 )。

在「如何分组」里我写了一个思路,里面有一种重要的点是不断从原来的数组踢除数值,这会导致数组本身重排,而这是 Fisher-Yates 要避免的问题,他采用的是交换的方法来避免重排,如下中文注释。

function shuffle(array) {
  var m = array.length, t, i;

  // While there remain elements to shuffle…
  while (m) {

    // Pick a remaining element…
    i = Math.floor(Math.random() * m--);

    // And swap it with the current element.
    t = array[m];  // 缓存当前的第 m 位
    array[m] = array[i]; // 随机 m 之前某位放进 m
    array[i] = t; // 第随机位换成 m 位的值(后续还会被取到)
  }

  return array;
}

感慨,算法总是逼死我们这些文科生。

@sofish sofish added this to the Daily Post milestone Apr 22, 2016
@sofish sofish closed this as completed Apr 22, 2016
@sofish sofish reopened this Apr 22, 2016
@lishengzxc
Copy link

splice()是有点慢的,有次遇到做动画的时候,需要频繁去从数组里面删除一项,发现很慢(就是因为慢导致了问题,如果在前面一次splice还没完成立马又splice就出问题了),就用object模仿一个数组,直接用delete就好了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants