Randomize a List problem
|
09-14-2020, 07:32 PM
(This post was last modified: 09-15-2020 01:56 AM by Albert Chan.)
Post: #3
|
|||
|
|||
RE: Randomize a List problem
Random shuffling must produce all permutations with equal probabilities.
We pick a random element from the list, and moved out of the way Do this repeatedly, like this. (we can skip the 1 element list case) Code: function shuffle(lst) 1st loop, random element is swapped to lst[n], and never touched again. 2nd loop, random element is swapped to lst[n-1] ... lua> pat = setmetatable({}, {__index = function(a,i) return 0 end}) lua> for i=1,120000 do : lst = {'1','2','3'} : shuffle(lst) : x = table.concat(lst,'') : pat[x] = pat[x] + 1 : end lua> table.foreach(pat, print) 321 20104 312 19844 132 20026 123 20096 231 19890 213 20040 |
|||
« Next Oldest | Next Newest »
|
User(s) browsing this thread: 1 Guest(s)