Random element list

Hi everyone,

I need your help (again :stuck_out_tongue: ).

In my game, I want to respawn 12 different items from an array of 100 elements every 24 hours.

I make the countdown and the array, about spawning I do something like this:

for i=1,12 do

 randomItem=math.random(1,100)

end

This works fine, the main problem is the duplicate value of randomItem, I need 12 differents elements so I need 12 different value for my randomItem

Any advice will be appreciate, thank you so much :slight_smile:

you can try

for i=1,12 do

 

math.randomseed(system.getTimer()+i)

 randomItem=math.random(1,100)

 

end

 

It may help

you can memorize randomItems generated

local randomItem local randomItems = {} for i=1, 12 do repeat randomItem = math.random(1, 100) until randomItems[randomItem] == nil randomItems[randomItem] = randomItem end

By this way, randomItems are all unique.

If you need randomItem one by one (you do something with it), you can destroy randomItems table after the for loop. If you need all your randomItems at once, you get them in randomItems table.

shuffle the table, then take first 12

Thanks everyone for your answer, I followed coruscans71’ advice and it works perfectly for my purpose.

Thank you =)

you can try

for i=1,12 do

 

math.randomseed(system.getTimer()+i)

 randomItem=math.random(1,100)

 

end

 

It may help

you can memorize randomItems generated

local randomItem local randomItems = {} for i=1, 12 do repeat randomItem = math.random(1, 100) until randomItems[randomItem] == nil randomItems[randomItem] = randomItem end

By this way, randomItems are all unique.

If you need randomItem one by one (you do something with it), you can destroy randomItems table after the for loop. If you need all your randomItems at once, you get them in randomItems table.

shuffle the table, then take first 12

Thanks everyone for your answer, I followed coruscans71’ advice and it works perfectly for my purpose.

Thank you =)