Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Sort list by position of items in another list

by drclaw (Acolyte)
on Feb 19, 2022 at 04:16 UTC ( #11141485=note: print w/replies, xml ) Need Help??


in reply to Sort list by position of items in another list

Hi,

What about inverting the search? You already know the order of the characters. Match them as many times as possible against the input string as a regex with each character as an alternative (ie input "QRKPNB" becomes /Q|R|K|P|N|B/ )?

These couple of lines generate the regex based on the input and match the sorted list against it. The joined matches become the (sorted) output string:

my $PCHR="KQRBNP"; my $w1="QRKPNB"; my $w2=join "", $PCHR=~/@{[join "|",split "",$w1]}/g; print "$w1 -> $w2\n";

Hope it might be of use or interest to your application

Ruben

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11141485]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (2)
As of 2023-02-01 06:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?