RogerBW's Blog

The Weekly Challenge 252: Unique and Special 21 January 2024

I’ve been doing the Weekly Challenges. The latest involved list filtering and sequence generation. (Note that this ends today.)

Task 1: Special Numbers

You are given an array of integers, @ints.

Write a script to find the sum of the squares of all special elements of the given array.

An element $int[i] of @ints is called special if i divides n, i.e. n % i == 0. Where n is the length of the given array. Also the array is 1-indexed for the task.

Well, there's a fairly obvious way to do this iteratively, as seen here in Raku:

sub specialnumbers(@a) {
    my $t = 0;
    for (0 .. @a.end) -> $i {
        if (@a.elems % ($i + 1) == 0) {
            $t += @a[$i] * @a[$i];
    return $t;

However, I prefer a purely functional approach. I wasn't able to wrangle Kotlin or Scala into doing this, though I think they can; but it was fairly straightforward in Rust:

fn specialnumbers(a: Vec<u32>) -> u32 {
        .filter(|(i, _n)| a.len() % (i + 1) == 0)
        .map(|(_i, n)| n * n)

and the equivalent in PostScript with my extensions:

/specialnumbers {
    0 dict begin
    dup /l exch length def
    { 0 get 1 add l exch mod 0 eq } filter
    { 1 get dup mul } map
    { add } reduce
} bind def

Task 2: Unique Sum Zero

You are given an integer, $n.

Write a script to find an array containing $n unique integers such that they add up to zero.

Obviously there are infinite possible solutions to this, but I chose a simple one

(1, 2, 3, ..., -sum(1..n-1))

with the last term calculated using the identity:

sum(1..n) = n * (n + 1) / 2

And therefore, in JavaScript:

function uniquesumzero(n) {
    if (n == 1) {
        return [0];
    let p = Array(n - 1).fill().map((element, index) => index + 1);
    p.push(-n * (n-1) / 2);
    return p;

Some other approaches might have been:

(1, -1, 2, -2, ... )

with a zero at the end if $n is odd; or

(1, 2, 4, 8, ... -(2^(n-1) - 1))

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.

Tags 1920s 1930s 1940s 1950s 1960s 1970s 1980s 1990s 2000s 2010s 3d printing action advent of code aeronautics aikakirja anecdote animation anime army astronomy audio audio tech aviation base commerce battletech beer boardgaming book of the week bookmonth chain of command children chris chronicle church of no redeeming virtues cold war comedy computing contemporary cornish smuggler cosmic encounter coup covid-19 crime cthulhu eternal cycling dead of winter doctor who documentary drama driving drone ecchi economics en garde espionage essen 2015 essen 2016 essen 2017 essen 2018 essen 2019 essen 2022 essen 2023 existential risk falklands war fandom fanfic fantasy feminism film firefly first world war flash point flight simulation food garmin drive gazebo genesys geocaching geodata gin gkp gurps gurps 101 gus harpoon historical history horror hugo 2014 hugo 2015 hugo 2016 hugo 2017 hugo 2018 hugo 2019 hugo 2020 hugo 2022 hugo-nebula reread in brief avoid instrumented life javascript julian simpson julie enfield kickstarter kotlin learn to play leaving earth linux liquor lovecraftiana lua mecha men with beards mpd museum music mystery naval noir non-fiction one for the brow opera parody paul temple perl perl weekly challenge photography podcast politics postscript powers prediction privacy project woolsack pyracantha python quantum rail raku ranting raspberry pi reading reading boardgames social real life restaurant reviews romance rpg a day rpgs ruby rust scala science fiction scythe second world war security shipwreck simutrans smartphone south atlantic war squaddies stationery steampunk stuarts suburbia superheroes suspense television the resistance the weekly challenge thirsty meeples thriller tin soldier torg toys trailers travel type 26 type 31 type 45 vietnam war war wargaming weather wives and sweethearts writing about writing x-wing young adult
Special All book reviews, All film reviews
Produced by aikakirja v0.1