How to return a sorted list's index in Perl?

后端 未结 2 1947
醉话见心
醉话见心 2021-01-16 21:30

Say, I have a list:

@abc = (5,7,6,2,7,1);

I have to obtain a sorted list as well as a sorted list index. So the output will be:

         


        
相关标签:
2条回答
  • 2021-01-16 22:14

    If you want to sort the indexes, you'll need to generate them

    0..$#unsorted
    

    Then you sort them like anything else

    my @sorted_indexes = sort { $unsorted[$b] <=> $unsorted[$a] } 0..$#unsorted;
    

    Grabbing the sorted values can be done using a slice.

    my @sorted_values = @unsorted[ @sorted_indexes ];
    
    0 讨论(0)
  • 2021-01-16 22:15

    This is my solution:

    use strict;
    use warnings;
    
    my @abc = (5,7,6,2,7,1);
    my $i = 0;
    
    #Create an array of hashes (with value and index)
    my @temp_abc = map { {value=>$_, index=>$i++} } @abc;
    
    #Sort by the value of each hash
    my @sorted_temp_abc = sort { $b->{value} <=> $a->{value} } @temp_abc; 
    
    #extract the values to array @sorted_list
    my @sorted_list = map { $_->{value} } @sorted_temp_abc;
    
    #extract the values to array @sorted_list_index
    my @sorted_list_index = map { $_->{index} } @sorted_temp_abc;
    
    print "@sorted_list\n";        #<-- prints: 7 7 6 5 2 1
    print "@sorted_list_index\n";  #<-- prints: 1 4 2 0 3 5
    
    0 讨论(0)
提交回复
热议问题