Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

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

by rsFalse (Friar)
on Sep 17, 2019 at 08:36 UTC ( #11106282=note: print w/replies, xml ) Need Help??


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

Hello, ozboomer,

Your method (same method, but with or without subroutine) is clear and good. But if you have large data, it is too slow, because time complexity of the method is N*M. For every element from subset (M) you check all elements from list (N). For better time complexity you can use hashes (search: perldata).

#!/usr/bin/perl use warnings; use strict; use Data::Dumper; my @array = ( "APPLE", "ORANGE", "PEACH", # Use this for the O +RDER "GRAPE", "BANANA", "PINEAPPLE" ); my @subset = ( "PINEAPPLE", "GRAPE", "ORANGE", "APPLE" ); # A requir +ed subset but NOT # in the required order my @results = (); # The subset with it +s elements in the # same order as the 're +ference' array # ---- Method 2: Using hash my %indexes; my $index = 0; map { $indexes{ $_ } = $index; $index ++; } @array; printf " Index of element '$_' is: %d\n", $indexes{ $_ } for @subset; my @tmp = (); foreach my $check ( @subset ){ my( $index ) = $indexes{ $check }; push( @tmp, $index ); } my @index_list = sort {$a <=> $b} @tmp; # Sort the index values numer +ically @results = @array[@index_list]; # Slice the index items out of ' +@array' print "Method 2 (uses hash):\n"; print Dumper(@results); print "\n";
OUTPUT:
Index of element 'PINEAPPLE' is: 5 Index of element 'GRAPE' is: 3 Index of element 'ORANGE' is: 1 Index of element 'APPLE' is: 0 Method 2 (uses hash): $VAR1 = 'APPLE'; $VAR2 = 'ORANGE'; $VAR3 = 'GRAPE'; $VAR4 = 'PINEAPPLE';

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2019-11-12 14:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Strict and warnings: which comes first?



    Results (66 votes). Check out past polls.

    Notices?