From: Rob Biedenharn Date: 2007-05-11T12:10:33+09:00 Subject: Re: how to remove dups from 2 lists? 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 Having some examples might help, but is something like this what you're after? >> a = %w[ a a a b b c ] => ["a", "a", "a", "b", "b", "c"] >> b = %w[ b c c c d ] => ["b", "c", "c", "c", "d"] >> a + b => ["a", "a", "a", "b", "b", "c", "b", "c", "c", "c", "d"] >> a | b => ["a", "b", "c", "d"] >> a - b => ["a", "a", "a"] >> a & b => ["b", "c"] >> a - (a & b) => ["a", "a", "a"] >> b - (a & b) => ["d"] In particular, which do you expect from RemoveDupsFromLists( a, b )? What I have for the last two expressions above: => [ ["a", "a", "a"], ["d"] ] Or: => [ ["a", "a", "a", "b"], ["c", "c", "d"] ] because it works like canceling terms in a fraction: ["a", "a", "a", "b", "b", "c"] ----------------------------------------------- ["b", "c", "c", "c", "d"] Basically, write a test: require 'test/unit' class RemoveDupsTest < Test::Unit::TestCase def test_simple list1 = ["a", "a", "a", "b", "b", "c"] list2 = ["b", "c", "c", "c", "d"] expects = [ [__,__], [__,__] ] #<=== fill me it! assert_equals expects, RemoveDupsFromLists(list1, list2) end end Then you'll know what you want (and so will we!) and you'll be sure when you get it working. -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com