Drawing two random elements of a table getting duplicate

Hi, so I just made a voting system. The system chooses two random elements of a given table, then returns those to use for voting. Although, I just noticed it returned two of the same element…

Very confused as to why, I think my code looks decent. Any help appreciated, thanks.

 function Replicate_Table(tab)
    local x = {}
     for i,v in pairs(tab) do
	    x[i] = i
      end
      return x
 end

 function Get_Two_Elements(tab)
    local e1,e2
    local indexes = Replicate_Table(tab)
    local index = generator:NextInteger(1, #indexes)
    e1 = tab[index]
    table.remove(indexes, index)
    e2 = tab[generator:NextInteger(1, #indexes)]
    return {e1, e2}
end
1 Like

You’re doing e2 = tab[...] but removing from indexes.

1 Like

I’m confused. I have it so it selects an available index from the newly created indexes table, and then after it sets e1 to the corresponding index of the tab variable, I’ll remove the selected index from the indexes table and then select another random available index from it, and set e2 to that.

 function Replicate_Table(tab)
    local x = {}
     for i,v in pairs(tab) do
	    x[i] = i
      end
      return x
 end

 function Get_Two_Elements(tab)
    local e1,e2
    local indexes = Replicate_Table(tab)
    local index = generator:NextInteger(1, #indexes)
    e1 = tab[index]
    table.remove(indexes, index)
    e2 = indexes[generator:NextInteger(1, #indexes)] --> you're removing index from indexes, but used tab here
    return {e1, e2}
end
1 Like

Thank you, although the indexes table simply holds all the indexes of tab. (just numbers.)

So I use the selected index from the indexes table to get the actual data from tab.

If it selects index 1 and you remove it from table, the length is still possible to be 1.

1 Like

Ahh I see what you’re saying now.

I’ll try to explain this using an example.

Suppose #indexes = 5 and index = 3, by chance.
When you remove indexes[3], your next random number does not ensure 3 will not be chosen again.
Now you have #indexes = 4, so index could be anything from 1 to 4, including 3.

Although this is by chance, it may be the reason you are experiencing repetitive results.

3 Likes