Weekly Challenge 244
Simon Green
Posted on November 26, 2023
Each week Mohammad S. Anwar sends out The Weekly Challenge, a chance for all of us to come up with solutions to two weekly tasks. My solutions are written in Python first, and then converted to Perl. It's a great way for us all to practice some coding.
Task 1: Count Smaller
Task
You are given an array of integers.
Write a script to calculate the number of integers smaller than the integer at each index.
My solution
This is a one-liner in Python
solution = [sum(1 for j in ints if j < i) for i in ints]
Breaking it down:
-
for i in ints
iterates through the supplied list, assigning each value to the variablei
. -
sum(1...)
will count the number of elements that satisfy the condition. -
for j in ints
creates an inner loop, assigning each value to the variable 'j'. - Finally
j < i
will only count the elements where the value in the inner loop is lower than the outer loop.
As Perl does not provide an easy way for double loops, I create a separate function to calculate the values less than a number, and then use the map function to iterate through each value.
sub less_than($i, $ints) {
return scalar( grep { $_ < $i } @$ints );
}
my @solution = map { less_than( $_, \@ints ) } @ints;
Examples
$ ./ch-1.py 8 1 2 2 3
4, 0, 1, 1, 3
$ ./ch-1.py 6 5 4 8
2, 1, 0, 3
$ ./ch-1.py 2 2 2
0, 0, 0
Task 2: Group Hero
Task
You are given an array of integers representing the strength.
Write a script to return the sum of the powers of all possible combinations; power is defined as the square of the largest number in a sequence, multiplied by the smallest.
My solution
For this task, I create a function called calculate_power
that returns the square of the largest number multiplied by the smallest number.
def calculate_power(numbers):
min_int = min(numbers)
max_int = max(numbers)
return max_int ** 2 * min_int
In the main function, I create a loop called length
which goes from 1 to the length of the supplied list. For each length
, I compute all combinations. Thankfully Python has a combination function in itertools.
for length in range(1, len(ints)+1):
power += sum(calculate_power(c) for c in combinations(ints, length))
Perl's combination function comes from the Algorithm::Combinatorics module.
foreach my $len ( 1 .. $#ints+1) {
my $iter = combinations(\@ints, $len);
while (my $c = $iter->next) {
$power += calculate_power($c);
}
}
Examples
$ ./ch-2.py 2 1 4
141
Posted on November 26, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.