Skip to content

Instantly share code, notes, and snippets.

@samaaron
Created December 20, 2009 10:45
Show Gist options
  • Save samaaron/260436 to your computer and use it in GitHub Desktop.
Save samaaron/260436 to your computer and use it in GitHub Desktop.
List random = method(
"returns a random element from the list",
[System randomNumber % length])
List pick = method(
"picks a random element from the list. If a quantity is specified it returns a list of that size picked randomly which is a subset of the original list. If the specified quantity is greater than the length of the list, the returned list will be padded with nils.",
quantity nil,
if(quantity,
result = list()
notPicked = self mimic
quantity times(
randomIndex = System randomNumber % (notPicked length)
result << notPicked removeAt!(randomIndex))
result,
random))
List choose = method(
"chooses a random element from the list. If a quantity is specified it returns a list of that size chosen randomly which may contain duplicates.",
quantity nil,
if(quantity,
result = list()
quantity times(result << random),
random))
List shuffle = method(
"return a new list containing the same elements as the original list with their positions distributed randomly.",
pick(length))
List shuffle! = method(
"shuffles the list by randomly distributing the position of its elements",
notPicked = self mimic
notPicked length times(index,
randomIndex = System randomNumber % (notPicked length)
[index] = notPicked removeAt!(randomIndex))
self)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment