in reply to More efficient way to get uniq list elements from list of lists

Use a hash:

use Data::Dumper; use strict; use warnings; sub edges2vertices { my %vertices; for my $i ( 0 .. $#_ ) { $vertices{$_[$i][$_]} = 1 for (0 .. $#{$_[$i]}); } return sort keys %vertices; } my @E = ([1,2], [1,3], [2,3,7,8], [2,4], [3,4]); my @nv= edges2vertices(@E); print Dumper(\@nv);
  • Comment on Re: More efficient way to get uniq list elements from list of lists
  • Download Code

Replies are listed 'Best First'.
Re^2: More efficient way to get uniq list elements from list of lists
by simonm (Vicar) on Nov 11, 2004 at 08:20 UTC
    Or more compactly:
    sub edges2vertices { sort keys %{ { map { $_ => undef } map @$_, @_ } } }
      This is not only more compact, it's also a different, slower algorithm. See the benchmarked examples in my other post

      --
      Snazzy tagline here
        This is not only more compact, it's also a different, slower algorithm

        To my eye it looks like the same algorithm as pg's solution, just rolled up into a single statement; what strikes you as different about it?

        And running your benchmark script with a few additions indicates that it's actually faster than any of the alternatives you had included:

        ewijaya              37879/s
        ewijaya_longrand     38610/s
        pg_longrand          96154/s
        pg                  100000/s
        aighearach          103093/s
        aighearach_longrand 105263/s
        scooterm            107527/s
        scooterm_longrand   114943/s
        simonm              117647/s
        simonm_longrand     126582/s
        simonm2             131579/s
        simonm2_longrand    144928/s
        

        I'm not sure why the results differ from those you showed; FWIW, I'm running 5.6.0 on darwin.

        Here're the two subs I tested:

        sub simonm { sort keys %{ { map { $_ => undef } map @$_, @_ } } } sub simonm2 { my ( %unique ); @unique{ map @$_, @_ } = (); sort keys %unique }