Advertisement
musifter

AoC 2023 day 13 (Perl)

Dec 13th, 2023 (edited)
890
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 2.05 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use feature  qw(say);
  7.  
  8. $/ = '';  # Paragraph mode
  9.  
  10. my @Grids = map { y/.#/01/; my @g = split /\n/; [map {[split //]} @g] } <>;
  11.  
  12. sub print_grid($)  { my $g = shift; say "\t", join( '', @$_ ) foreach ($g->@*); }
  13.  
  14. sub as_num(@)      { oct("0b" . join('', @_)) }
  15. sub one_bit_set($) { my $n = shift; return (($n & ($n - 1)) == 0) }
  16.  
  17. sub clean_reflect {
  18.     my @cols = @_;
  19.  
  20.     my $i;
  21.     my @stack = ($cols[0]);
  22.     for ($i = 1; $i < @cols; $i++) {
  23.         if ($cols[$i] == $stack[-1]) {
  24.             pop( @stack );
  25.         } else {
  26.             push( @stack, $cols[$i] );
  27.         }
  28.  
  29.         return (($i + 1) / 2) if (!@stack);
  30.     }
  31.  
  32.     return (0);
  33. }
  34.  
  35. sub smudge_reflect {
  36.     my @cols = @_;
  37.  
  38.     my $size = @cols;
  39.  
  40.     my @stack = shift( @cols );
  41.     my @pops  = shift( @cols );
  42.     for (my $j = 0; $j < int($size / 2); $j++) {
  43.  
  44.         my $foo = 0;
  45.         for (my $i = 0; $i < @stack; $i++) {
  46.             next if ($stack[$i] == $pops[$i]);
  47.             $foo += (one_bit_set( $stack[$i] ^ $pops[$i] )) ? 1 : 2;
  48.         }
  49.  
  50.         return ($j + 1) if ($foo == 1);
  51.  
  52.         push( @stack, pop( @pops ) );
  53.         unshift( @pops, shift( @cols ) );
  54.         unshift( @pops, shift( @cols ) );
  55.     }
  56.  
  57.     return (0);
  58. }
  59.  
  60. sub test_reflect {
  61.     my ($func, @cols) = @_;
  62.  
  63.     my $reflect = &$func( @cols );
  64.     if (!$reflect) {
  65.         $reflect = &$func( reverse @cols );
  66.         $reflect = @cols - $reflect  if ($reflect);
  67.     }
  68.  
  69.     return ($reflect);
  70. }
  71.  
  72. my $part1 = 0;
  73. my $part2 = 0;
  74.  
  75. foreach my $grid (@Grids) {
  76.     my @rows = map { &as_num(@$_) } $grid->@*;
  77.  
  78.     $part1 += 100 * &test_reflect( \&clean_reflect,  @rows );
  79.     $part2 += 100 * &test_reflect( \&smudge_reflect, @rows );
  80.  
  81.     my @cols;
  82.     foreach my $x (0 .. $grid->[0]->$#*) {
  83.         push( @cols, &as_num(map {$grid->[$_][$x]} (0 .. $grid->$#*)) );
  84.     }
  85.  
  86.     $part1 += &test_reflect( \&clean_reflect,  @cols );
  87.     $part2 += &test_reflect( \&smudge_reflect, @cols );
  88. }
  89.  
  90. say "Part 1: $part1";
  91. say "Part 2: $part2";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement