I’ve been doing the Weekly
Challenges. The
latest
involved inspecting integer elements and making iterative things less
so. (Note that this ends today.)
Task 1: Unique Sum
You are given an array of integers.
Write a script to find out the sum of unique elements in the given array.
Fairly straightforward: convert the list into a hash with values equal
to the count of elements. Raku has a Bag structure that's good for
this, and Rust has the Counter crate that I've been using a great deal
lately. Ruby, Kotlin and Python have hashes with defaults. Perl has
autovivification, which is almost as good but rather less flexible.
(Which just leaves Javascript, Lua and PostScript where I have to
write it out the long way.)
Then take all the entries where count = 1, and sum them. Perl:
sub uniquesum($a) {
my %c;
map {$c{$_}++} @{$a};
return sum0(grep {$c{$_} == 1} keys %c);
}
I like the explicitness of thw two stages in the Rust version.
fn uniquesum(a: Vec<u32>) -> u32 {
Break down the list into a Counter.
let c = a.into_iter().collect::<Counter<u32>>();
Filter the object for count = 1, then output the values.
c.iter().filter(|(_k, v)| **v == 1usize).map(|(k, _v)| k).sum()
}
Task 2: Empty Array
You are given an array of integers in which all elements are unique.
Write a script to perform the following operations until the array is empty and return the total count of operations.
If the first element is the smallest then remove it otherwise move it to the end.
Well.
I mean, I could do that. With a ring buffer or something.
Or I could say, well, we're basically counting the number of passes it
takes to get the lowest value in the list to the front of the list,
aren't we? So let's just work that out based on where it is in the
list. And iterate for each number.
(There may be inputs for which this approach doesn't work. But it was
fun to write.)
In Lua (where for once the 1-based list indices are actually useful):
function emptyarray(a0)
local t = 0
local a = a0
while #a > 0 do
Find the minimum value.
local mn = math.min(table.unpack(a))
Locate the minimum in the list.
for i, v in ipairs(a) do
if v == mn then
Remove it and count the number of "operations" needed to get here.
table.remove(a, i)
t = t + i
break
end
end
end
return t
end
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.