Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: How to Order an Array's Elements to Match Another Array's Element Order

by tybalt89 (Monsignor)
on Sep 18, 2019 at 02:45 UTC ( [id://11106329]=note: print w/replies, xml ) Need Help??


in reply to How to Order an Array's Elements to Match Another Array's Element Order

Here's something completely different - it doesn't use a sort !

#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11106277 use warnings; my @array = ( "APPLE", "ORANGE", "PEACH", # Use this for the O +RDER "GRAPE", "BANANA", "PINEAPPLE" ); my @subset = ( "PINEAPPLE", "GRAPE", "APPLE" ); # A required subset +but NOT # in the required order my %order; @order{ @array } = 0 .. $#array; my @results; @results[ @order{ @subset } ] = @subset; @results = grep defined, @results; print "results: @results\n";

Just kidding, this is called a distribution sort.

  • Comment on Re: How to Order an Array's Elements to Match Another Array's Element Order
  • Download Code

Replies are listed 'Best First'.
Re^2: How to Order an Array's Elements to Match Another Array's Element Order
by LanX (Saint) on Sep 18, 2019 at 10:22 UTC

    >

    my @array = ( "APPLE", "ORANGE", "PEACH", # Use this for the +ORDER "GRAPE", "BANANA", "PINEAPPLE" );

    shouldn't this be completely ordered ?

    BANANA < GRAPE < ORANGE

    UPDATE

    never mind, I should've read the OP first! :-)

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-04-24 20:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found