prelude-ls
prelude-ls copied to clipboard
Added shuffle
I used the Fisher–Yates Shuffle.
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