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.

9
  • What makes 10, 10 different from 6, 6? Commented Mar 14, 2013 at 16:09
  • Thanks for the reply. For this particular code I want the lowest multiples to be picked out *only. Commented Mar 14, 2013 at 16:14
  • Well that's some critical information to the problem, don't you think? ;) ... Is hand sorted by numbers? Commented Mar 14, 2013 at 16:16
  • Yes, hand is sorted from lowest to high by number Commented Mar 14, 2013 at 16:18
  • You should add that to the question Commented Mar 14, 2013 at 16:20

1 Answer 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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a bunch! You've been a great help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.