Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: How to make buckets of like data

by roboticus (Canon)
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

PRyanRay:

That was amusing.

$ cat groupify_a.pl #!/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 groupify_a.pl { 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...

...roboticus

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


Comment on Re: How to make buckets of like data
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (3)
As of 2014-10-26 06:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (151 votes), past polls