Selecting equal number of objects using math.random function

I was making a small app where I used math.random to select from numbers 1 to 4. Say, I call math.random 12 times, I want to pick numbers randomly, but I want to make sure that all of them are picked 3 times each, that is equal number of times. If that is not possible atleast they should be picked 2 times each in this case. I have been working on this for two days using different permutations and combinations but its not working.

One solution I found was that to give 4*3*2*1= 24 combinations. Like if the number 2 is selected 4 times then math.random should select from 1,3,4 and so on we cover for all the 24 combintions. But this is not a good solution as it is very lengthy and complicated, and if the numbers are 5, then the combinations go up to 120. Please help me with this. [import]uid: 183447 topic_id: 34281 reply_id: 334281[/import]

This is easy. Make a table:

numbers = {1,1,1,2,2,2,3,3,3,4,4,4}  

Then shuffle the table.

local function shuffle(t)  
 local rand = math.random   
 assert(t, "table.shuffle() expected a table, got nil")  
 local iterations = #t  
 local j  
  
 for i = iterations, 2, -1 do  
 j = rand(i)  
 t[i], t[j] = t[j], t[i]  
 end  
end  
  
shuffle(numbers)  
  

Now you can just iterate over the table, i.e. for i = 1, #numbers do… and you will get each number 3 times and in a random order.
[import]uid: 199310 topic_id: 34281 reply_id: 136311[/import]

This is easy. Make a table:

numbers = {1,1,1,2,2,2,3,3,3,4,4,4}  

Then shuffle the table.

local function shuffle(t)  
 local rand = math.random   
 assert(t, "table.shuffle() expected a table, got nil")  
 local iterations = #t  
 local j  
  
 for i = iterations, 2, -1 do  
 j = rand(i)  
 t[i], t[j] = t[j], t[i]  
 end  
end  
  
shuffle(numbers)  
  

Now you can just iterate over the table, i.e. for i = 1, #numbers do… and you will get each number 3 times and in a random order.
[import]uid: 199310 topic_id: 34281 reply_id: 136311[/import]