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

Added shuffle #102

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open

Added shuffle #102

wants to merge 2 commits into from

Conversation

morningrat2
Copy link

@morningrat2 morningrat2 changed the title Add shuffle Added shuffle Feb 29, 2016
@anko
Copy link

anko commented Mar 1, 2016

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

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

Successfully merging this pull request may close these issues.

2 participants