How do I randomize the order of a list?

I'm sort of familiar with programming topics, so I imagine I could figure out SOMETHING.

But let's say I have a list of things or names.. how do I randomize the order that they are in? Is there an easy way of doing it?


The easiest way to randomise a list is to add them to a new list, picking one at a time randomly.

An example with a stringlist:

initial_list = Split ("eggs;ham;cheese;milk;bananas;cyanide")
random_list = NewStringList()
for (i, 1, ListCount (initial_list)) {
  item = PickOneString (initial_list)
  list remove (initial_list, item)
  list add (random_list, item)
}
msg ("The random list is: " + Join (random_list, ", "))

If you're using an objectlist, you'd want PickOneObject rather than PickOneString.

You could also add new members right back to the end of the same list; but you'd want to change it so it doesn't pick a member that's already been shuffled. I think the code is a little harder to understand this way, but it's smaller and will work with all list types. If you're doing this quite often, it might be easier to put this script in a function named something like ShuffleList with a single parameter, list:

for (i, ListCount (list)-1, 1, -1) {
  item = ListItem (list, GetRandomInt (0, i))
  list remove (list, item)
  list add (list, item)
}

Then you can just do ShuffleList (some_list_variable) to shuffle the members of a list (this is an in-place operation - it changes the order of the members of a list, rather than returning a new list).


Oh hey, I need something like this for a Blackjack minigame I'm working on...


Log in to post a reply.

Support

Forums