Fisher Yates在coffeescript中洗牌

时间:2012-10-17 07:16:28

标签: javascript coffeescript shuffle

假设Math.random()产生0到1之间均匀分布的随机数,这是Fischer Yates shuffle的正确实现吗?我正在寻找一个非常随机,均匀的分布,其中可以指定输入数组(arr)中的混洗元素的数量(required)。

shuffle = (arr, required)->
  rnd = (int) ->
    r = Math.random() * int
    Math.round r

  len = arr.length-1

  for i in [len..1]
    random = rnd(i)
    temp = arr[random]
    arr[random] = arr[i]
    arr[i] = temp
    break if i < len - (required - 2)

  return arr

1 个答案:

答案 0 :(得分:1)

一些事情:

  • 而不是Math.round(),请尝试Math.floor();在你的 实现Math.round()给出第一个元素(在索引0处) 并且最后一个元素比其他元素少 (.5 / len vs. 1 / len)。请注意,在第一次迭代中,您为arr.length - 1元素输入arr.length
  • 如果你要required 变量,你也可以选择它,因为它默认为数组的长度:shuffle = (arr, required=arr.length)
  • 即使您只是拖拽了最后一个元素,也会返回整个数组。请考虑返回arr[arr.length - required ..]
  • 如果required不在[0,arr.length]
  • 范围内,该怎么办?

将所有这些放在一起(并增加一些天赋):

    shuffle = (arr, required=arr.length) ->
      randInt = (n) -> Math.floor n * Math.random()
      required = arr.length if required > arr.length
      return arr[randInt(arr.length)] if required <= 1

      for i in [arr.length - 1 .. arr.length - required]
        index = randInt(i+1)
        # Exchange the last unshuffled element with the 
        # selected element; reduces algorithm to O(n) time
        [arr[index], arr[i]] = [arr[i], arr[index]]

      # returns only the slice that we shuffled
      arr[arr.length - required ..]

    # Let's test how evenly distributed it really is
    counter = [0,0,0,0,0,0]
    permutations = ["1,2,3","1,3,2","2,1,3","2,3,1","3,2,1","3,1,2"]
    for i in [1..12000]
      x = shuffle([1,2,3])
      counter[permutations.indexOf("#{x}")] += 1

    alert counter