Hi Monks,
I need to sort an array ascending or descending does not matter. then choose the top and bottom 10 percent of data, replace them with A (for tops) and replace them by B (for lows). The remaining replace by "-". The put the data back to their original order.Something like the following. The 10 percent is hypothetical can be any percentage.
@array = (2 ,4, 3, 8, 9, 12, 13, 20, 18, 7 )
@sortedarray = (20, 18, 13, 12, 9, 8, 7, 4, 3, 2)
After replacement (A, A, -, -, -, -, -, -, -, -, B, B)
@finalarray = (B, -, B, -, -, -, -, A, A , -)
I know how to sort by index like the following code but I am just wondering if you can help me to learn how to the replacement. May be map function is the way to go.
#! perl -slw
use strict;
my @array = (2 ,4, 3, 8, 9, 12, 13, 20, 18, 7 );
my @orderedIndeces = sort{
$array[ $b ] <=> $array[ $a ]
} 0 .. $#array;
my $n = scalar @array;
my $twentyperc = $n * 0.2;
for my $i (0..$#orderedIndeces){
if ( $i < $twentyperc) {
$array[$orderedIndeces[$i]] = "A";
print "$array[$orderedIndeces[$i]]\t";
}
elsif ($i >= $n-$twentyperc){
$array[$orderedIndeces[$i]] = "B";
print "$array[$orderedIndeces[$i]]\t";
}
else{
$array[$orderedIndeces[$i]] = "-";
print "$array[$orderedIndeces[$i]]\t";
}
print "\n";
}