Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: How to make buckets of like data

by roboticus (Chancellor)
on Feb 05, 2013 at 23:40 UTC ( #1017303=note: print w/replies, xml ) Need Help??

in reply to How to make buckets of like data


That was amusing.

$ cat #!/usr/bin/perl use strict; use warnings; my %Grps; # Build the groups while (<DATA>) { my ($l,$r) = split /\s*,?\s+/, $_; last unless defined $r; my $gl = $Grps{$l}; my $gr = $Grps{$r}; if (defined $gl) { if (defined $gr) { if ($gr != $gl) { # Merge two groups my %new_gr = map { $_=>0 } @$gr, @$gl; my $new_gr = [ sort keys %new_gr ]; $Grps{$_} = $new_gr for @$new_gr; } } else { # Add $r existing group push @{$Grps{$r}=$gl},$r; } } elsif (defined $gr) { # Add $l to existing group push @{$Grps{$l}=$gr},$l; } else { # Create new group my $new_gr = [ $l, $r ]; $Grps{$_} = $new_gr for @$new_gr; } } #...and print them for my $K (keys %Grps) { next unless @{$Grps{$K}}>0; print "{ ", join(", ", splice @{$Grps{$K}}), " }\n"; } __DATA__ A, B C, D A, C E, F F, G $ perl { E, F, G } { A, B, C, D }

I did a similar version using hashes, but I think this one is a little better. (Perhaps I could've said it better as "the hash one was a little uglier".)

Update: I prefer Browser's version because it has better notation. I prefer the concept of mine, but can't figure out how to make the notation as nice as his...


When your only tool is a hammer, all problems look like your thumb.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1017303]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (13)
As of 2016-10-28 17:05 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (386 votes). Check out past polls.