I’ve been doing the Weekly
Challenges. The
latest
involved list manipulation and bit flipping. (Note that this is
open until 28 May 2023.)
Task 1: Maximum Product
You are given a list of 3 or more integers.
Write a script to find the 3 integers whose product is the maximum
and return it.
The simple version of this would just be to take the three highest.
But that would be dull. Thus example 4, in which some of the integers
are negative.
I end up sorting the list and then taking four combined slices of it
to get the products. Raku:
sub maximumproduct(@lst) {
my @l = sort {$^a <=> $^b}, @lst;
my $b = @l.elems;
my @t;
i
is the number of integers to take from the left side (lowest values).
for (0..3) -> $i {
my $p = 1;
Multiply by each of those:
if ($i > 0) {
for (0..$i-1) -> $j {
$p *= @l[$j];
}
}
Then by 3 - i
numbers from the right side (highest values).
if ($i < 3) {
for ($b-3+$i..$b-1) -> $j {
$p *= @l[$j];
}
}
Store that result.
@t.push($p);
}
And return the highest one we got.
return max(@t);
}
Task 2: Matrix Score
You are given a m x n binary matrix i.e. having only 1 and 0.
You are allowed to make as many moves as you want to get the highest score.
A move can be either toggling each value in a row or column.
To get the score, convert the each row binary to dec and return the
sum.
Like last week's problem, this doesn't need to be an exhaustive
search. Given the choice in a sequence of (1, ...)
or (0, ...)
,
the (1, ...)
will always produce a larger value, whatever the state
of any digits after it.
Therefore every row must start with a 1; then for columns other than
the first, the majority of digits should be 1.
Rust:
fn matrixscore(matrix0: Vec<Vec<u8>>) -> u32 {
let mut matrix = matrix0;
Check the first digit of each row. If it's a 0, flip the row.
for i in 0..matrix.len() {
if matrix[i][0] == 0 {
for j in 0..matrix[i].len() {
matrix[i][j] = 1 - matrix[i][j];
}
}
}
Now for each column after the first,
let t = matrix.len() / 2;
for i in 1..matrix[0].len() {
count the zeroes,
let mut c = 0;
for j in 0..matrix.len() {
if matrix[j][i] == 0 {
c += 1;
}
}
and if they're more than half the entries, flip the column.
if c > t {
for j in 0..matrix.len() {
matrix[j][i] = 1 - matrix[j][i];
}
}
}
Then read out the results, converting each row to a number.
let mut tot = 0;
for m in matrix {
let mut p = 0;
for n in m {
p *= 2;
if n == 1 {
p += 1;
}
}
tot += p;
}
tot
}
Turns out matrix
is a keyword in PostScript…
Full code on
github.
Comments on this post are now closed. If you have particular grounds for adding a late comment, comment on a more recent post quoting the URL of this one.