in reply to better union of sets algorithm?

I think that you might try something like this:

  1. Modify the keys such that they store both the real key and the set they come from, something like "$key|$set" might work. The values used for $set should be something like "A", "B" etc.. IE, sortable.
  2. Sort the keys from the sets together. (If the lists are already sorted skip this set and just use a merge instead of a scan in the following step.)
  3. Scan the set. If there are duplicate keys from the same set they will be together. Ignore one of them. Count the dupe keys with different set values (they will be inorder, you only need to worry about dupes). If the number of keys is the same as the number of sets then you have a union.

Whether this is faster will probably come down to data size. For really high volumes a hash approach wont work as it wont be sufficient memory efficient. (Remember a hash will normally have the same number of buckets as the next power of two larger than the number of keys in the hash.) For integers I would use BrowserUk's approach, for strings I would probably use a hash unless the data volume was really high (or i could be guaranteed the data was already in sorted form) and then i would go with something like the above.

---
demerphq

Replies are listed 'Best First'.
Re^2: better union of sets algorithm?
by perrin (Chancellor) on Mar 11, 2005 at 15:09 UTC
    Thanks, but I think you're talking about an intersection, not a union. I want to get a unique list of all items that are in any set.

      Oh, yeah, i did mean intersection. Union is even easier. Use the same procedure and ignore duplicate lines that are adjacent. This means you never have more than two lines in memory at once.

      ---
      demerphq

        The items being sorted on are strings. It seems to me like merging them and sorting them together before scanning to remove dupes would make this slower than the hash approach, especially since I may have to go to disk if the combined size is a couple of million entries or so. I guess I should really bench it.
      so, for example (to clarify):

      my @a = qw( 1 2 3 3 2 ); my @b = qw( 1 4 5 5 4 ); my @c = qw( 1 6 7 7 6 );


      should give back
      1 2 3 4 5 6 7


      right? basically you could make one big list and find the uniques from that?
      --------------
      It's sad that a family can be torn apart by such a such a simple thing as a pack of wild dogs
        That's right, except the lists are sets, i.e. they have no dupes internally, and they are already individually sorted.