I’ve been doing the Weekly
Challenges. The
latest
involved sequence searching and another nested sort. (Note that this
ends today.)
Task 1: Arithmetic Triplets
You are given an array (3 or more members) of integers in increasing
order and a positive integer.
Write a script to find out the number of unique Arithmetic Triplets
satisfying the following rules:
a) i < j < k
b) nums[j] - nums[i] == diff
c) nums[k] - nums[j] == diff
My approach is a straightforward one: turn the input numbers into a
set, then for each number n
search the set for (n + diff)
and
(n + diff × 2)
. (This may break in interesting ways if numbers are
duplicated, but the problem statement leaves this undefined.)
Challenge 239 task 2 has a similar "filter a list and return the count
of results" approach.
Perl:
sub arithmetictriplets($a, $diff) {
my %vs = map {$_ => 1} @{$a};
return grep {(exists $vs{$_+$diff}) && (exists $vs{$_+$diff*2})} @{$a};
}
I rather like the PostScript approach too. (All right, it does rely on
my library code for filter
and toset
.)
/arithmetictriplets {
0 dict begin
/diff exch def
/nums exch def
/ns nums toset def
nums { diff add dup ns exch known
exch diff add ns exch known
and } filter length
end
} bind def
Task 2: Prime Order
You are given an array of unique positive integers greater than 2.
Write a script to sort them in ascending order of the count of their
prime factors, tie-breaking by ascending value.
It's been a while since I got out the prime factoring code—Challenge
169 task 2 in fact. The multi-key sort is as seen in Challenge 238
task 2. Given those existing top and bottom layers, the new code is
relatively straightforward. (I won't include the primality code here,
though I converted it afresh for Scala.)
JavaScript:
function primefactorcount(n) {
return Array.of(...primefactor(n).values()).reduce((x, y) => x + y, 0);
}
function primeorder(ints) {
let b = ints;
let c = new Map;
for (let n of ints) {
c.set(n, primefactorcount(n));
}
b.sort(function(aa, bb) {
if (c.get(aa) == c.get(bb)) {
return aa - bb;
} else {
return c.get(aa) - c.get(bb);
}
});
return b;
}
For some of the languages I added an integer square root function
simply to keep floating point out of the execution path. It's not
time-critical in these functions, being called just once in
genprimes
and once in primefactor
, but I don't like using floats
where I don't have to. It's all fairly straightforard anyway, using a
modified chop search, so here's the Rust:
fn isqrt(s: usize) -> usize {
if s <= 1 {
return s;
}
let mut x0 = s / 2;
let mut x1 = (x0 + s / x0) / 2;
while x1 < x0 {
x0 = x1;
x1 = (x0 + s / x0) / 2;
}
return x0;
}
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.