gpt4 book ai didi

perl - 不能持续到循环 block 之外

转载 作者:行者123 更新时间:2023-12-05 08:44:00 30 4
gpt4 key购买 nike

我正在努力解决一个问题

Rahul 正在玩一个非常有趣的游戏。他有 N 个圆盘(每个圆盘的半径相等)。每个磁盘都有一个不同的数字,从 1 到 N 与之相关联。磁盘一个接一个地放在一堆中。

Rahul 想从上到下对这堆磁盘进行升序排序。但是他有一个非常非常特别的方法来做到这一点。他一步只能从一堆盘子中选择一个盘子,并且只能把它放在最上面。

Rahul 想以尽可能少的步骤对他的一堆磁盘进行排序。所以帮助拉胡尔这样做。因此,不必显示实际步骤,只需回答对堆进行排序的可能步骤的最少数量,以便 Rahul 可以检查他的工作是对还是错。

我正在写的代码是

sub get_order { 
my (@input1)= @_;
my @input2 = @input1;

my $count = 0;
sub recursive {
my $max = 0;
last if ( $#input2 == -1 ) ;
foreach ( 0 .. $#input2) {
$max = $max > $input2[$_] ? $max : $input2[$_];
print " maximum is $max \n";
}
if ( $max == $input2[$max-1] ) {
$abc = 0;
} else {
$count++;
#push @input2, $max;
}
# deleting that particular array index from the array
my %hash = map {
$_ => "1"
} @input2;
delete $hash{$max};
print %hash;
print "\n";
@input2 = keys %hash;
print "***@input2 \n";
&recursive();
}
&recursive();
print "value is $count \n";
return $count;

}

get_order(3,1,2);

我在 test.txt 第 8 行收到错误 Can't "last"outside a loop block。

最佳答案

forforeachwhileuntil 或裸 block 之外,您不能使用 lastnextredo

相反,您可以从函数中返回

return if ( $#input2 == -1 ) ;

关于perl - 不能持续到循环 block 之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19052551/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com