Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

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

by tybalt89 (Parson)
on Sep 18, 2019 at 02:45 UTC ( #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 (Archbishop) 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
Node Status?
node history
Node Type: note [id://11106329]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (7)
As of 2019-12-11 16:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?