5 Replies Latest reply on Nov 14, 2007 7:27 PM by Blindgator

# list shuffle

I have a list with names of cards that I am using in a game that I was making and was wondering if there was any way to randomly shuffle the list so that each time it would be in a differant order?

Thanks for the help
Brian
• ###### 1. Re: list shuffle
on ShuffleList var_list
repeat with n = 1 to var_list.count
n_random = random( var_list.count )
if ( n = n_random ) then
next repeat
end if
item1 = var_list[n]
var_list[n] = var_list[n_random]
var_list[n_random] = item1
end repeat
end
• ###### 2. Re: list shuffle
Thanks for the quick response but could someone please explain to me everything that the script he posted is doing. Being new to director I dont quite understand all of it and would appreciate the help.
Thanks
• ###### 3. Re: list shuffle
it loops thru the whole list.
With every item in the list it takes a random other index and switches tose values

1. A
2. B
3. C
4. D
5. E

take a random other position in list, say index 4 (D). Swap them so now the list looks like this

1.D
2.B
3.C
4.A
5.E

Now take index 2 (B) and swap it with a random other position say 3 (C)

1.D
2.C
3.B
4.A
5.E

keep on looping this way until you have swapped all items.

you can also do it like this
make two lists
orgList = [A,B,C,D,E]
resultList = []

--repeat while there are items left in the original list
repeat while orgList.count > 0
fromPos = random(orgList.count)
toPos = random(resultList.count)
orgList.deleteAt(fromPos)
end repeat

now resultList is a shuffeled version of orgList
• ###### 4. Re: list shuffle
on ShuffleList var_list
-- process with n = 1 to end of list
repeat with n = 1 to var_list.count
-- get random list position
n_random = random( var_list.count )
-- check if same as current index n
if ( n = n_random ) then
-- skip if same
next repeat
end if
-- store current value
item1 = var_list[n]
-- set to value from random position
var_list[n] = var_list[n_random]
-- set random position to stored value
var_list[n_random] = item1
end repeat
-- no need to return value because original list is already changed
end
• ###### 5. Re: list shuffle
Got it working. Really appreciated the help
Muchas Gracias