selecting a unique element from a table

Hi,

I am coming up against a small issue I need advice on please.

I create a number of objects using a standard for loop, also add several properties that I have omitted for clarity and add them to a table as below:

followers = {} local function create() for i = 1, 10 do local follower = display.newCircle(0, 0, 5) followers[#followers + 1] = follower end end

I then  select several objects from the table at random,I also add some more properties, this is how I do that and everything is working fine.

local function selectObject() for i = 1, 5 do selected = followers[math.random(1, #followers)] selected:setFillColor(255, 0, 0) end end

The problem Iam having is that when I select the objects at random it will sometimes select the same object twice,( I guess it could select one object 5 times).

Also only 1 object( i guess the last chosen in the loop) only has the required properties I set on it.

So I guess I need to do the following :

Select objects that are not already chosen and make each object unique so it has the properties I give them.

Any help much appreciated.

Random numbers are just that - random. Sometimes the same number will come out twice. If you want a random generator which can’t produce the same number before all numbers have been chosen you need to remove the items being selected from the list of possibilities.

What @horacebury is referring to can be done with a technique known as shuffling.

See: https://coronalabs.com/blog/2014/09/30/tutorial-how-to-shuffle-table-items/

Rob

Hi Chaps,

yes I immediatley went to the card shuffling tutorial, I remembered I had done something similar before.

Indeed, shuffling the objects before they are chosen will give a different result each time without the randomness.

Anyway just to add I have it working nicely now.

Thanks for the pointers:)

Random numbers are just that - random. Sometimes the same number will come out twice. If you want a random generator which can’t produce the same number before all numbers have been chosen you need to remove the items being selected from the list of possibilities.

What @horacebury is referring to can be done with a technique known as shuffling.

See: https://coronalabs.com/blog/2014/09/30/tutorial-how-to-shuffle-table-items/

Rob

Hi Chaps,

yes I immediatley went to the card shuffling tutorial, I remembered I had done something similar before.

Indeed, shuffling the objects before they are chosen will give a different result each time without the randomness.

Anyway just to add I have it working nicely now.

Thanks for the pointers:)