[英]Find the index of the last non-zero element in each row of a given matrix?
[英]An elegant way of returning the index of the last non-zero element in Perl?
我發現自己想要找到數組中最后一個非零元素的索引。 所以,給定:
my @array = (0,0,5,9,0,0,0,7,0,3,0,0);
my $indexLastNonZero = insertElegantMethodHere(@array);
# expect $indexLastNonZero to be equal to 9;
我這樣做了:
for my $i (0 .. $#array) {
$indexLastNonZero = $i if $array[$i] != 0;
};
我工作,但不知怎的,我不禁覺得必須有一個超級優雅(更聰明?更好?更高效?)在perl中這樣做的方式。 我查看了List :: Utils,但沒有找到一個很好的方法,並希望非核心模塊獨立的方法。
有什么想法嗎?
干杯
使用List :: MoreUtils執行此類任務:
use warnings;
use strict;
use List::MoreUtils;
my @array = (0,0,5,9,0,0,0,7,0,3,0,0);
print List::MoreUtils::lastidx { $_ } @array
my @array = (0,0,5,9,0,0,0,7,0,3,0,0);
my ($indexLastNonZero) = grep $array[$_], reverse 0 .. $#array;
從數組的末尾開始並向后工作,直到找到非零元素:
my @array = (0,0,5,9,0,0,0,7,0,3,0,0);
my $i = $#array;
$i-- while $i >= 0 && $array[$i] == 0;
print "The last non-zero element is at index $i\n";
$i >= 0
測試用於防止所有元素都為零的邊緣情況。 在這種情況下, $i
的結果值為-1。
您可以使用核心中的List::Util
:
use strict;
use warnings;
use List::Util qw(first);
my @array = (0,0,5,9,0,0,0,7,0,3,0,0);
my $index = @array;
first { $index-- && $_ } reverse @array;
print "Last index that is non-zero: $index\n";
破壞性方法所以首先獲取數組的副本:
my @array2 = @array;
while (!pop @array2) {} # Remove up to and including the last non-zero
print scalar @array2; # Size of remaining elements is index of last non-zero
sub last_true {
pop and return scalar @_ while @_;
undef;
}
my $index = last_true(@foo);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.