> On May 10, 2007, at 10:18 PM, Mike Steiner wrote:
> 
>> I'm trying to write some code that removes all elements from 2 lists that
>> are in both lists. However, I don't want any duplicates from each list
>> deleted also (which is what the array "-" operator does). The code I have
>> now doesn't handle restarting the current iteration for both loops when a
>> match is found and deleted in both loops. Here's the code:
>>
>> def RemoveDupsFromLists ( list1 , list2 )
>>    list1.each_index do | i |
>>        list2.each_index do | j |
>>            if list1[i] == list2[j]
>>                list1.delete_at ( i )
>>                list2.delete_at ( j )
>>            end
>>        end
>>    end
>>    return [ list1 , list2 ]
>> end
>>
>> What's weird is that doing this is easy in C (my first language), but
>> difficult in Ruby. Everything else I've seen has been MUCH easier in 
>> Ruby.
>>
>> Mike Steiner

Or is it something like this?

Here only common elements of both lists are deleted from left to right, but if a 
list contains more elements, e.g. "a" than the other, only the number of "a"s 
that are in the other list will be deleted from the one, which has more "a"s (I 
don't know how to describe it - the code should explain ist):

a = %w{a b a a c a b c d e f e a}
b = %w{a b a c d c d c c g h g c}
puts '--- before ---'
p a
p b
ah = a.inject(Hash.new(0)){|h,w|h[w]+=1;h}
bh = b.inject(Hash.new(0)){|h,w|h[w]+=1;h}
abh = (ah.keys & bh.keys).inject({}){|h,w|h[w]=[ah[w], bh[w]].min;h}
[a, b].each{|arr|abh.each{|k,v|v.times{arr.delete_at(arr.index(k)) if 
arr.include?(k)}}}
puts '--- after ---'
p a
p b

Output:

--- before ---
["a", "b", "a", "a", "c", "a", "b", "c", "d", "e", "f", "e", "a"]
["a", "b", "a", "c", "d", "c", "d", "c", "c", "g", "h", "g", "c"]
--- after ---
["a", "a", "b", "e", "f", "e", "a"]
["d", "c", "c", "g", "h", "g", "c"]

Wolfgang N?dasi-Donner