From: Kevin Compton Date: 2007-05-11T14:28:48+09:00 Subject: Re: how to remove dups from 2 lists? ------=_Part_163160_6391652.1178861326865 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline I'm also not real sure of what exactly you wanted but.. I assumed the following : def remove_dups_from_both_lists (list1, list2) list1_dup = list1.dup remove_dups_from_first_list list1, list2 remove_dups_from_first_list list2, list1_dup end def remove_dups_from_first_list(list_to_prune, list_with_dups) hash_with_occurrence_count = get_hash_with_occurrence_count list_to_prune decrement_count_for_dups(list_with_dups, hash_with_occurrence_count) get_remaining_item_list(list_to_prune, hash_with_occurrence_count) end def get_hash_with_occurrence_count(list) hsh = Hash.new { |h,k| h[k] = 0} list.each { |item| hsh[item] += 1 } hsh end def decrement_count_for_dups(list, other_list_as_hash) list.each { |item| other_list_as_hash[item] -= 1 } end def get_remaining_item_list(list, list_as_hash) list.each_with_index do |item, idx| if (list_as_hash[item] > 0) list_as_hash[item] -= 1 else list[idx] = nil end end list.compact end list1 = %w{one one two three four four five} list2 = %w{one three three four five five five} puts "before --- list1:#{list1}" puts "before --- list2:#{list2}" remove_dups_from_both_lists list1, list2 puts "after --- list1:#{list1}" puts "after --- list2:#{list2}" On 5/10/07, 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 > ------=_Part_163160_6391652.1178861326865--