Skip to content

Instantly share code, notes, and snippets.

@skids
Created February 23, 2016 15:06
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 skids/aca87c6b6fb065a3c244 to your computer and use it in GitHub Desktop.
Save skids/aca87c6b6fb065a3c244 to your computer and use it in GitHub Desktop.
reddit daily programmer perl 6 solution within striking distance of bonus.
$ time perl6 -e 'my %sw := SetHash.new; my $size = 5000000; for (0..^$size).pick xx 200000 -> $s is copy, $e is copy { ($s,$e) = $e, $s if $e < $s; %sw{+$s} +^= 1; %sw{+$e + 1} +^= 1 if $e < $size - 1; }; my $accum; my $o = 0; for %sw.keys.sort.rotor(2 => -1) -> ($s, $e) { $o +^= 1; $accum += $e - $s if $o; LAST { $accum += $size - $e unless $o }}; $accum.say'
2495015
real 1m25.943s
user 1m25.832s
sys 0m0.076s
# Just need two orders of magnitude improvement :-)
# Algorithm note: decompose each run of switch throws into throwing all the switches right (inclusive) of the leftmost switch,
# then throwing all the switches right (exclusive) of the rightmost switch. To count those you don't need to keep track of
# every switch state, just where the flips happenned (double flips cancel out). You can do this in an array still, but
# if there are a sparse number of flips compared to switches, a hash seems to be faster -- problem being you have to sort
# the locations afterwards.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment