I’ve been doing the Weekly
Challenges. The
latest
involved list parsing and combinations. (Note that this closes today.)
Task 1: Third Highest
You are given an array of integers.
Write a script to find out the Third Highest if found otherwise return the maximum.
My approach here is to get the distinct values in the input list,
reverse sort it, and then pull either the third entry (if it exists)
or the first. (The problem doesn't specify what's to be done with an
empty list; I choose to return zero.)
Perl:
sub thirdhighest($l) {
my @v = reverse sort keys %{{map {$_ => 1} @{$l}}};
if (scalar @v == 0) {
return 0;
} elsif (scalar @v <= 2) {
return $v[0];
} else {
return $v[2];
}
}
I think the most elegant code here is in Rust (for which I was going
to use a HashSet, but it turns out that dedup()
is a thing for
vectors).
fn thirdhighest(l: Vec<i32>) -> i32 {
let mut v = l.clone();
v.sort();
v.dedup();
v.reverse();
match v.len() {
0 => 0,
1..=2 => v[0],
_ => v[2],
}
}
Task 2: Maximum XOR
You are given an array of integers.
Write a script to find the highest value obtained by XORing any two
distinct members of the array.
So it's time to dust off the combinations generator, last seen in 203
task 1. Some languages have this readily available; others don't.
Python:
from itertools import combinations
def maximumxor(l):
m = []
for c in combinations(l, 2):
m.append(c[0] ^ c[1])
return max(m)
I finally got round to implementing Knuth's lexicographic combination
algorithm [TAoCP volume 4 § 7.2.1.3] in PostScript, complete with its
slightly odd ordering, and that's now in the library for future use.
(The library itself has moved to
Codeberg as
part of my general disentanglement from github at least for my own
projects.)
PostScript:
/combinations {
4 dict begin
/k exch def
/arr exch def
/c [
0 1 k 1 sub { } for
arr length
0
] def
[
{
[
k 1 sub -1 0 {
c exch get arr exch get
} for
]
/j 0 def
{
c j get 1 add c j 1 add get ne {
exit
} if
c j j put
/j j 1 add def
} loop
j k ge {
exit
} if
c j c j get 1 add put
} loop
]
end
} bind def
/maximumxor {
[ exch
2 combinations {
dup 0 get exch 1 get xor
} forall
] listmax
} bind def
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.