0

I have code that compares the entries of two tables against one another and places those entries with identical values into a third table:

for i = 1, #hand do
    for j = i+1, #hand do
        if( hand[i].number == hand[j].number ) then
            if not done[i] then
                done[i] = true;
                table.insert(cards, hand[i]);
            end
            if not done[j] then
                done[j] = true;
                table.insert(cards, hand[j]);
            end
        end
    end
end

The problem I'm having is that it will add at least one other entry that isn't identical. I've checked the prints and one thing I've noticed is that in at least one instance the additional entry it added was a separate multiple. I.e, if the values being checked were 6,6,10,10 I'd expect the first 2 entries to be inserted into the third table, not the final two. How can I set this code up to prevent this from happening in the future? Thanks.

EDIT: done is a local table being created just outside of the for loop. The intention of this code is to find only the lowest multiples in table 'hand' every time, where 'hand' is sorted by number lowest to highest.

4

1 に答える 1

3
for i = 1, #hand - 1 do
  if hand[i].number == hand[i+1].number then
     local j = i
     while hand[i].number == hand[j].number do
        if not done[j] then
           done[j] = true
           table.insert(cards, hand[j])
        end
        j = j + 1
     end
     break
  end
end
于 2013-03-14T16:29:00.193 に答える