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.


In reply to How to make buckets of like data by PRyanRay

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.