Brain teaser alert! This is more tricky than you would expect.

I'm looking for an algorithm that can take lists of strings that are in a user-declared logical order, and merge those lists in the way that preserves the most of those logical orderings.

Example:

use Test2::V0; use v5.40; my @list1= qw( K B I S Y A Q ); my @list2= qw( B S N A ); my @list3= qw( Y N Q ); my $combined= fancy_algorithm(\@list1, \@list2, \@list3); is( $combined, [qw( K B I S Y N A Q )] );
For bonus points, it should return a stable output when there are ambiguities (such as if there is no list which establishes the order between two elements), and if the input disagrees with itself it should select the ordering that occurs more frequently.
use Test2::V0; use v5.40; my @lists= ( [qw( X P Y )], [qw( X B Y N )], [qw( P B N )], [qw( X B P N )], [qw( X B P Y )], [qw( A Z )], [qw( A K L )], ); my $combined= fancy_algorithm(@lists); is( $combined, [qw( X B P Y N A Z K L )] );

Why is it relevant? because on more than one occasion I've wanted to export user data with the columns in the "natural order", but I'm combining multiple independent data sets and for each dataset the user has chosen the column names according to some ordering that makes sense to them but which the system has no knowledge of. I have a solution that "mostly works", but I keep finding edge cases where it breaks. I'm curious if there is a complete solution to the problem.

Edit: ...and hopefully more efficient than just running every permutation of output looking for the one with the highest score. Sometimes there are a lot of columns and that could be bad.


In reply to Merge lists of ordered strings into canonical ordering by NERDVANA

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.