#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11161855 use warnings; use List::AllUtils qw( min_by nsort_by ); $SIG{__WARN__} = sub { die @_ }; 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); use Data::Dump 'dd'; dd 'combined', $combined; 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 )], ); $combined= fancy_algorithm(@lists); use Data::Dump 'dd'; dd 'combined', $combined; sub fancy_algorithm { my (%names, @order); @names{ @$_ } = () for my @args = @_; use Data::Dump 'dd'; dd 'input', \@args; while( @args ) { my %names; my $see = 1; $names{$_} += $see++ for map @$_, @args; my @names = nsort_by { $names{$_} } sort +keys %names; my %score; for ( @args ) { my ($head, @rest) = @$_; $score{$head} -= 1e9; $score{$_} //= 0 for @rest; } my $pick = min_by { $score{$_} } @names; push @order, $pick; $_ = [ grep $pick ne $_, @$_ ] for @args; @args = grep @$_, @args; } return \@order; }

Outputs:

( "input", [ ["K", "B", "I", "S", "Y", "A", "Q"], ["B", "S", "N", "A"], ["Y", "N", "Q"], ], ) ("combined", ["K", "B", "I", "S", "Y", "N", "A", "Q"]) ( "input", [ ["X", "P", "Y"], ["X", "B", "Y", "N"], ["P", "B", "N"], ["X", "B", "P", "N"], ["X", "B", "P", "Y"], ["A", "Z"], ["A", "K", "L"], ], ) ("combined", ["X", "B", "P", "Y", "N", "A", "Z", "K", "L"])

In reply to Re: Merge lists of ordered strings into canonical ordering by tybalt89
in thread 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.