prelude-ls icon indicating copy to clipboard operation
prelude-ls copied to clipboard

Added shuffle

Open morningrat2 opened this issue 8 years ago • 1 comments

I used the Fisher–Yates Shuffle.

morningrat2 avatar Feb 29 '16 01:02 morningrat2

That modifies the input list:

a = [ 1 to 10 ]
console.log shuffle a  # => shuffled list
console.log a          # => shuffled list also

Other functions in the prelude preserve the input (e.g. sort), so it would be confusing.

How about this?

shuffle = (xs) ->
  # In a random order, insert the element at each index of the input list
  # into the output list.
  output = []
  indexes = [ 0 til xs.length ]
  while indexes.length
    i = indexes.splice((Math.floor Math.random! * indexes.length), 1).0
    output.push xs[i]
  output

a = [ 1 to 10 ]
console.log shuffle a  # => shuffled list
console.log a          # => ordered list

anko avatar Mar 01 '16 00:03 anko