PRyanRay has asked for the wisdom of the Perl Monks concerning the following question:
Hello, Monks!
I am attempting to "bucketize" binary lists. The basic idea is if I have a list like this:
my @array = (["A","B"],["C","D"],["A","C"],["E","F"],["F","G"]);I would like to (using hases or arrays) bucket letters that are associated. In this example, I would like to have an object like this:
my @array1 = ([A,B,C,D],[E,F,G]);I have not had much luck. I have some code that is close but it is very clumsy and cumbersome. Here is the "meat" of my code that is attempting to do this. The variables $req1 and $req2 are the letters in the above example, and, yes, I know it is not correct, that is why I am here:
#!usr/bin/perl use strict; use warnings; my %buckets; my @array2 = (["A","B"],["C","D"],["A","C"],["E","F"],["F","G"]); my $count = 0; foreach(@array2){ my $req1 = $array2[$count][0]; my $req2 = $array2[$count][1]; my $j = 0; foreach my $key (keys %buckets){ if($key =~ /$req1/i){ $buckets{$key} .= $req2; $j++; last; } elsif($key =~ /$req2/i){ $buckets{$key} .= $req1; $j++; last; } elsif($buckets{$key} =~ /$req1/i){ $buckets{$key} .= $req2; $j++; last; } elsif($buckets{$key} =~ /$req2/i){ $buckets{$key} .= $req1; $j++; last; } } if($j == 0){$buckets{$req1} = $req2;} $count++; } foreach(keys %buckets){print $_,$buckets{$_},"\n";}
Am I missing something simple here? Any help would be appreciated.
The output from this is the following:
ABC
CD
EFG
See the problem is how to do the retroactive updating if a new hash entry was made.