Skip to content

Instantly share code, notes, and snippets.

@dogbert17
Created April 16, 2016 17:17
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/c510cc424c37450c7678db8624acc66d to your computer and use it in GitHub Desktop.
Save dogbert17/c510cc424c37450c7678db8624acc66d to your computer and use it in GitHub Desktop.
Causes problems when run with the --profile option
# What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?
# real 10m52.262s
# user 10m37.848s
# sys 0m1.068s
# This is Rakudo version 2016.03-76-gb3b24bf built on MoarVM version 2016.03-84-g4afd7b6
use v6;
my $size = 5;
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];
}
return $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