Skip to content

Instantly share code, notes, and snippets.

@adamcrussell
Created September 20, 2020 03:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamcrussell/e64a27355e8a2724dff993844fd4e2da to your computer and use it in GitHub Desktop.
Save adamcrussell/e64a27355e8a2724dff993844fd4e2da to your computer and use it in GitHub Desktop.
Perl Weekly Challenge 078
use strict;
use warnings;
##
# You are given an array @A containing distinct integers.
# Write a script to find all leader elements in the array @A.
# Print (0) if none found.
##
use boolean;
sub is_leader{
my(@a) = @_;
my $l = shift @a;
for my $x (@a){
return false if $x > $l;
}
return true;
}
sub find_leaders{
my(@a) = @_;
my @leaders;
for my $i (0 .. @a - 1){
push @leaders, $a[$i] if !$a[$i + 1] || is_leader(@a[$i .. @a - 1]);
}
return @leaders;
}
MAIN:{
my @A;
@A = (9, 10, 7, 5, 6, 1);
print "\@A = (" . join(",", @A) . ")\n";
print "Leaders = (" . join(",", find_leaders(@A)) . ")\n";
@A = (3, 4, 5);
print "\@A = (" . join(",", @A) . ")\n";
print "Leaders = (" . join(",", find_leaders(@A)) . ")\n";
}
use strict;
use warnings;
##
# You are given array @A containing positive numbers
# and @B containing one or more indices from the array @A.
# Write a script to left rotate @A so that the number at
# the first index of @B becomes the first element in the
# array. Similary, left rotate @A again so that the number
# at the second index of @B becomes the first element in
# the array.
##
sub rotate{
my($a, $r) = @_;
my @rotated;
for(0 .. ($r - 1)){
my $temp = shift @{$a};
push @{$a}, $temp;
}
return $a;
}
MAIN:{
my(@A, @B);
@A = (10, 20, 30, 40, 50);
@B = (3, 4);
my @rotations;
for my $b (@B){
my @temp = @A;
push @rotations, rotate(\@temp, $b);
}
print "\@A = (" . join(",", @A) . ")\n";
print "\@B = (" . join(",", @B) . ")\n";
print "Rotations:\n";
for my $rotation (@rotations){
print "\t[" . join(",", @{$rotation}) . "]\n";
}
@rotations = ();
@A = (7, 4, 2, 6, 3);
@B = (1, 3, 4);
for my $b (@B){
my @temp = @A;
push @rotations, rotate(\@temp, $b);
}
print "\@A = (" . join(",", @A) . ")\n";
print "\@B = (" . join(",", @B) . ")\n";
print "Rotations:\n";
for my $rotation (@rotations){
print "\t[" . join(",", @{$rotation}) . "]\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment