RabbitFarm
2025-06-12
Consecutive Search for Discount Prices
The examples used here are from the weekly challenge problem statement and demonstrate the working solution.
Part 1: Consecutive One
You are given a binary array containing only 0 or/and 1. Write a script to find out the maximum consecutive 1 in the given array.
The core of the solution is contained in a main loop. The resulting code can be contained in a single file.
We’ll use a recursive procedure, which we’ll call from a subroutine which sets up some variables. We’ll pass scalar references to a recursive subroutine. When the recursion completes the $max_consecutive variable will hold the final answer.
Now, let’s define our recursion. We’ll terminate the recursion when we’ve exhausted the input array.
-
sub consecutive_one_r{
my($i, $consecutive, $max_consecutive) = @_;
my $x;
unless(@{$i} == 0){
$x = pop @{$i};
if($x == 0){
$$max_consecutive = $$consecutive if $$consecutive > $$max_consecutive;
$$consecutive = 0;
}
if($x == 1){
$$consecutive++;
}
consecutive_one_r($i, $consecutive, $max_consecutive);
}
elsif(@{$i} == 1){
$x = pop @{$i};
if($x == 0){
$$max_consecutive = $$consecutive if $$consecutive > $$max_consecutive;
}
if($x == 1){
$$consecutive++;
$$max_consecutive = $$consecutive if $$consecutive > $$max_consecutive;
}
consecutive_one_r($i, $consecutive, $max_consecutive);
}
}
◇
Just to make sure things work as expected we’ll define a few short tests. The double chop is just a lazy way to make sure there aren’t any trailing commas in the output.
-
MAIN:{
say consecutive_one(0, 1, 1, 0, 1, 1, 1);
say consecutive_one(0, 0, 0, 0);
say consecutive_one(1, 0, 1, 0, 1, 1);
}
◇
-
Fragment referenced in 1.
Sample Run
$ perl perl/ch-1.pl 3 0 2
Part 2: Final Price
You are given an array of item prices. Write a script to find out the final price of each items in the given array. There is a special discount scheme going on. If there’s an item with a lower or equal price later in the list, you get a discount equal to that later price (the first one you find in order).
Hey, let’s use recursion again for this too!
The main section is just some basic tests.
-
MAIN:{
say join q/, /, calculate_lowest_prices 8, 4, 6, 2, 3;
say join q/, /, calculate_lowest_prices 1, 2, 3, 4, 5;
say join q/, /, calculate_lowest_prices 7, 1, 1, 5;
}
◇
-
Fragment referenced in 5.
First, let’s introduce a recursive subroutine that scans ahead and finds the next lowest price in the list. As in part one we’ll use a scalar reference.
With that subroutine defined we can use it to solve the main task at hand.
Sample Run
$ perl perl/ch-2.pl 4, 2, 4, 2, 3 1, 2, 3, 4, 5 6, 0, 1, 5
References
posted at: 22:13 by: Adam Russell | path: /perl | permanent link to this entry