Advertisement
mscha

AoC 2016 day 15

Dec 16th, 2016
383
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 6 1.32 KB | None | 0 0
  1. #!/usr/bin/env perl6
  2.  
  3. use v6.c;
  4.  
  5. sub dragon-data(Str $seed, Int $length)
  6. {
  7.     my $data = $seed;
  8.     while $data.chars < $length {
  9.         $data ~= '0' ~ $data.flip.trans('0'=>'1', '1'=>'0');
  10.     }
  11.     return $data.substr(0, $length);
  12. }
  13.  
  14. sub checksum-orig(Str $data)
  15. {
  16.     # Too slow for part 2
  17.     if $data.chars %% 2 {
  18.         return checksum($data.comb(/../).map({ $_ eq any('00','11') ?? '1' !! '0' }).join);
  19.     }
  20.     else {
  21.         return $data;
  22.     }
  23. }
  24.  
  25. sub checksum(Str $data)
  26. {
  27.     # We can consolidate the checksum process: instead of looking at 2 chars, we can look at any
  28.     # 2^n chars: if an even number of digits is 1, then 1, else 0.
  29.     my $pow-two = 1;
  30.     $pow-two *= 2 while $data.chars %% ($pow-two * 2);
  31.     say "$pow-two | $data.chars()";
  32.     if $pow-two > 1 {
  33.         return $data.comb.rotor($pow-two).map({ ([+] $_) %% 2 ?? '1' !! '0' }).join;
  34.     }
  35.     else {
  36.         return $data;
  37.     }
  38. }
  39.  
  40. #| Fill disk with data seeded from input file
  41. multi sub MAIN(IO() $inputfile where *.f, :$size=272)
  42. {
  43.     my ($seed) = $inputfile.words;
  44.     MAIN($seed, :$size);
  45. }
  46.  
  47. #| Fill disk with data seeded from command line
  48. multi sub MAIN(Str $seed where !*.IO.f, :$size=272)
  49. {
  50.     my $data = dragon-data($seed, $size);
  51.     say "Data: $data.chars() bits";
  52.     say 'Checksum: ', checksum($data);
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement