RabbitFarm
2023-11-19
Reverse Pairs on the Floor
The examples used here are from the weekly challenge problem statement and demonstrate the working solution.
Part 1
You are given an array of integers. Write a script to return the number of reverse pairs in the given array.
Solution
use v5.38;
sub reverse_pairs{
my @integers = @_;
my @reverse_pairs;
do{
my $i = $_;
do{
my $j = $_;
push @reverse_pairs, [$i, $j] if $integers[$i] > $integers[$j] + $integers[$j];
} for $i + 1 .. @integers - 1;
} for 0 .. @integers - 1;
return 0 + @reverse_pairs;
}
MAIN:{
say reverse_pairs 1, 3, 2, 3, 1;
say reverse_pairs 2, 4, 3, 5, 1;
}
Sample Run
$ perl perl/ch-1.pl
2
3
Notes
A reverse pair is a pair (i, j) where:
a) 0 <= i < j < nums.length
and
b) nums[i] > 2 * nums[j].
I've been on a bit of a recursion kick recently, but I didn't have the appetite for it this week. A nested loop and we're done!
Part 2
You are given an array of positive integers (>=1). Write a script to return the floor sum.
Solution
use v5.38;
use POSIX;
sub floor_sum{
my @integers = @_;
my $floor_sum;
do{
my $i = $_;
do{
my $j = $_;
$floor_sum += floor($integers[$i] / $integers[$j]);
} for 0 .. @integers - 1;
} for 0 .. @integers - 1;
return $floor_sum;
}
MAIN:{
say floor_sum 2, 5, 9;
say floor_sum 7, 7, 7, 7, 7, 7, 7;
}
Sample Run
$ perl perl/ch-2.pl
10
49
Notes
See above comment about not being as recursive this week!
References
posted at: 17:18 by: Adam Russell | path: /perl | permanent link to this entry