I’ve been doing the Weekly
Challenges. The
latest
involved list and hash hunting. (Note that this ends today.)
Task 1: Target Index
You are given an array of integers, @ints and a target element $k
.
Write a script to return the list of indices in the sorted array
where the element is same as the given target element.
This is pretty close to being a one-liner in most languages. Even in
PostScript it's not huge (with some of my extensions):
/targetindex {
0 dict begin
/k exch def
quicksort
enumerate.array
{ 1 get k eq } filter
{ 0 get } map
end
} bind def
and in Rust it's quite straightforward:
fn targetindex(a0: Vec<u32>, k: u32) -> Vec<usize> {
let mut a = a0;
a.sort();
a.iter()
.enumerate()
.filter(|(_i, v)| **v == k)
.map(|(i, _v)| i)
.collect::<Vec<_>>()
}
Task 2: Merge Item
You are given two 2-D array of positive integers, $items1 and
$items2 where element is pair of (item_id, item_quantity).
Write a script to return the merged items.
These arrays are in effect hashes with the possibility of duplicate
keys, which makes it obvious how to store the merged values. Perl:
sub mergeitems($aa, $bb) {
my %c;
foreach my $v ($aa, $bb) {
foreach my $w (@{$v}) {
Add each value to its corresponding key in the output hash.
$c{$w->[0]} += $w->[1];
}
}
Then rebuild the array structure based on sorted keys.
return [map {[$_, $c{$_}]} sort {$a <=> $b} keys %c];
}
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.