Skip to content

Instantly share code, notes, and snippets.

@dogbert17
Created November 5, 2016 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dogbert17/3069f8d880df27523aed42232d32d433 to your computer and use it in GitHub Desktop.
Save dogbert17/3069f8d880df27523aed42232d32d433 to your computer and use it in GitHub Desktop.
Probably not very optimal
# What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?
# real 6m17.384s
# user 6m16.172s
# sys 0m1.052
# This is Rakudo version 2016.09-105-g4abc28c built on MoarVM version 2016.09-13-g34c375a
use v6;
my $size = 1001;
my @mat[$size; $size];
init-array(0, $size - 1, $size * $size);
say sum-diagonals;
#say (0..$size - 1).map(-> $idx { @mat[$idx; $idx] + @mat[$idx; $size - 1 - $idx]}).sum - 1;
sub init-array($r, $c, $val) {
@mat[$r; $c] = $val;
if $c - 1 >= 0 && @mat[$r; $c - 1] !~~ Int && !($r - 1 >= 0 && @mat[$r - 1; $c] !~~ Int) { # left
init-array($r, $c - 1, $val - 1);
}
elsif $r + 1 < $size && @mat[$r + 1; $c] !~~ Int { # down
init-array($r + 1, $c, $val - 1);
}
elsif $c + 1 < $size && @mat[$r; $c + 1] !~~ Int { # right
init-array($r, $c + 1, $val - 1);
}
elsif $r - 1 >= 0 && @mat[$r - 1; $c] !~~ Int { # up
init-array($r - 1, $c, $val - 1);
}
}
sub sum-diagonals {
my $sum = 0;
for (0..$size - 1) -> $idx {
$sum += @mat[$idx; $idx] + @mat[$idx; $size - 1 - $idx];
}
$sum - 1; # don't count the '1' in the middle twice
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment