My answers will also be on github.
Task One
Given a list of integers, write a script to print 1 if there are THREE consecutive odds in the given array, otherwise print 0.
Task Two
In a list of altitudes, return the first widest valley.
Solution to Task One
On this I return 0 if there aren't three neighboring odds, otherwise pass through to check that they are consecutive.
use v5.30.0;
my @array1 = (1,5,3,6);
my @array2 = (2,6,3,5);
my @array3 = (1,2,3,4);
my @array4 = (2,3,5,7);
my @test = (\@array1, \@array2,\@array3,\@array4);
sub are_three_odds {
my @list = @_;
my @ind;
for (0 .. $#list - 2) {
push @ind, $_ if ( ($list[$_] % 2 == 1) && ($list[$_ + 1] % 2 == 1) && ($list[$_ + 2] % 2 == 1) );
}
return 0 unless (@ind);
foreach (@ind) {
my @set = ($list[$_],$list[$_+1],$list[$_+2]);
@set = sort {$a <=> $b} @set;
if ( ($set[2] - $set[1]) == ($set[1] - $set[0])) {
return 1;
}
}
return 0;
}
for (0 .. $#test) {
my @array = @{$test[$_]};
say "Input: (".join(",",@array).")";
say "Output: " . are_three_odds(@array);
}
Solution to Task Two
This I was able to manage with a few flags and one pass of the array. Once we stop increasing, the valley is over. Push all valleys to a collection then return the longest.
use v5.30.0;
my @array1 = (1, 5, 5, 2, 8);
my @array2 = (2,6,8,5);
my @array3 = (9,8,13,13,2,2,15,17);
my @array4 = (2,1,2,1,3);
my @array5 = (1,3,3,2,1,2,3,3,2);
my @test = (\@array1,\@array2,\@array3,\@array4,\@array5);
for my $ref (@test) {
my @array = @$ref;
my @valley; # push an array ref to each valley here.
my $begin_index = 0;
my $incr_flag = 0; # flag after descent is complete.
for (0 .. $#array - 1) {
if ($incr_flag) {
if ( $array[$_ + 1] < $array[$_] ) {
push @valley, [ @array[$begin_index .. $_] ];
$begin_index = $_;
for my $i (1 .. $_) { # check if it was level
if ( $array[$_] == $array[$_ - $i] ) {
$begin_index--;
} else {
last;
}
}
$incr_flag = 0;
}
} else {
if ( $array[$_ + 1] > $array[$_] ) {
$incr_flag = 1;
}
}
}
push @valley, [ @array[$begin_index .. $#array] ];
my $max = 0;
my $ind;
for (0 .. $#valley) {
if (scalar @{$valley[$_]} > $max) {
$max = scalar @{$valley[$_]};
$ind = $_;
}
}
say "Input: @array";
say "Output: @{$valley[$ind]}";
say "-" x 10;
}
Top comments (0)