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

后端 未结 2 1948
醉话见心
醉话见心 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: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
    

提交回复
热议问题