I'm not sure about your requirements. I wrote a solution that produces
[1,2,3]
[3,4,7]
[3,6,9]
This seems more consistent with your stated requirements than your example results. 4 & 8 are equally common -- they appear twice in the arrays. 4 occurs before 8 in $b, thus the elements appear in $b's order of insertion.
At any rate, my algorithm was:
- Traverse all the arrays, counting how many of each element appear.
- Sort the results in order of ascending frequency and assign it to @frequency.
- Take the last of these (i.e. most frequent, or tied for most frequent, and thus common to all) and assign it to $common.
- Die with an error message if $common < the number of arrays -- there wasn't really an element common to all.
- Start building the results for each array:
- First, assign $common.
- Then, for each element in @frequency, test if that element is present in the current array. If it is, assign it to the results for this array. Do this X-1 times (assigning $common took care of one element.)
- Sort this array's results.
- Push an arrayref for this array's results on your final results array.
Updated: my unstated assumption in the above was that that code would be in a subroutine to be called like so:
my ($a_, $b_, $c_) = mutually_exclusive($X, $a, $b, $c);
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.