If they're sorted in advance and you have a constant number of lists, you should be able to do it in linear time (instead of the n lg n that using a hash provides). The basic technique is to think of the lists of queues. Now search through all of these queues and find the lowest item at the queue head. Print it. If there are any identical items, they will also be at the queue heads; remove all of these items. Now find the next lowest item, and repeat.

Update: This assumes you can get the lists sorted for free, or at least for cheaper than the n lg n it would take to process the hashes. If that's the case, here's some simple code that demonstrates the idea, using an object to make the idea clearer:

#!/usr/bin/perl use warnings; use strict; my @a1 = sort qw(foo bar blarn schmark floogle foo blarn); my @a2 = sort qw(flirp schnirp blarn floogle florn flimple flange); my @a3 = sort qw(bar bar floogle bar florn bar bar); my $sml = SortedMultiList->new(\@a1,\@a2,\@a3); my $last; while (defined(my $next = $sml->shift_lowest)) { print $next,"\n" if (!defined($last) or ($last ne $next)); $last = $next; } package SortedMultiList; sub new { my $class = shift; my $self = [@_]; bless $self, $class; } sub shift_lowest { my $self = shift; my($lowest_arr,$lowest); foreach my $a (@$self) { next unless (@$a); if (!defined($lowest) or ($a->[0] lt $lowest)) { $lowest_arr = $a; $lowest = $a->[0]; } } return $lowest_arr ? shift(@$lowest_arr) : undef; }

In reply to Re: better union of sets algorithm? by sgifford
in thread better union of sets algorithm? by perrin

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.