in reply to Limit the size of a hash
Similar to Random_Walk version (Re: Limit the size of a hash), but without sort.
Here, we keep five elements.
If necessary, we calculate the index of the lowest element (min of highest).
If score of the new element is better than "min of highest", "min of highest" is replaced by new element.
use strict; use warnings; my $keep = 5; #init my @highest = map scalar<DATA>,1..$keep; #fisrt lines my @scores = map +(split)[-1],@highest; #score is last element (-1) of + each line my $indexofmin = 0; my $updated = 1; #### while(my $line=<DATA>) { my $score = (split/ /,$line)[-1]; if ($updated) { for my $i (0..$#scores) { $indexofmin = $i if $scores[$i]<$scores[$indexofmin]; } } if ($score>$scores[$indexofmin]) { $highest[$indexofmin]=$line; $scores[$indexofmin]=$score; $updated = 1; } else { $updated = 0; } } print @highest; __DATA__ 0 5 3 7 0.97 1 5 4 8 0.18 1 5 4 8 0.21 1 5 4 8 0.22 1 5 4 8 0.52 1 5 4 8 0.16 1 5 4 8 0.18 1 5 4 8 0.72 1 5 4 8 0.32 1 5 4 8 0.17 1 5 4 8 0.52 1 5 4 8 0.92 6 8 4 6 0.54
|
|---|