From 1f0c8ef911dca0ee6643ce544fc786306a07ee14 Mon Sep 17 00:00:00 2001 From: Yanick Champoux Date: Thu, 14 Dec 2017 13:58:00 -0500 Subject: [PATCH] day14 --- 14/1.pl | 14 ++++++++++++++ 14/2.pl | 36 ++++++++++++++++++++++++++++++++++++ 14/hash.pm | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 84 insertions(+) create mode 100644 14/1.pl create mode 100644 14/2.pl create mode 100644 14/hash.pm diff --git a/14/1.pl b/14/1.pl new file mode 100644 index 0000000..db13a4a --- /dev/null +++ b/14/1.pl @@ -0,0 +1,14 @@ +use 5.20.0; + +use lib '.'; +use hash; +my $key = 'stpzcrnm'; + +use List::AllUtils qw/ sum /; + +say sum + map { split '' } + map { sprintf "%04b", $_ } + map { hex } + map { split '' } + map { knot_hash( join '-', $key, $_) } 0..127; diff --git a/14/2.pl b/14/2.pl new file mode 100644 index 0000000..76e7c30 --- /dev/null +++ b/14/2.pl @@ -0,0 +1,36 @@ +use 5.20.0; + +use lib '.'; +use hash; +my $key = 'stpzcrnm'; + +use List::AllUtils qw/ sum /; + +my @grid = + map { [ map { $_ ? '#' : ' ' } map { split '', sprintf "%04b", hex } split '' ] } + map { knot_hash( join '-', $key, $_) } 0..127; + +my $clusters; +for my $x ( 0..127 ) { + for my $y ( 0..127 ) { + $clusters+= eradicate(\@grid,$x,$y); + } +} + +say $clusters; + +use experimental qw/ signatures /; +sub eradicate($grid,$i,$j) { + return 0 if $grid->[$i][$j] ne '#'; + $grid->[$i][$j] = ' '; + eradicate($grid,$i-1,$j) if $i > 0; + eradicate($grid,$i,$j-1) if $j > 0; + eradicate($grid,$i+1,$j); + eradicate($grid,$i,$j+1); + return 1; +} + + +sub print_g { + say @$_ for @grid; +} diff --git a/14/hash.pm b/14/hash.pm new file mode 100644 index 0000000..4d45841 --- /dev/null +++ b/14/hash.pm @@ -0,0 +1,34 @@ +use 5.20.0; + +use List::AllUtils qw/ reduce part /; +use experimental qw/ signatures /; + +use base 'Exporter'; +our @EXPORT = qw/ knot_hash /; + +sub knot_hash ( $string ) { + my @commands = map { ord } split '', $string; + push @commands, 17, 31, 73, 47, 23; + + my $skip = 0; + + my $i = 0; + my @array = 0..255; + + for ( 1..64 ) { + for my $c ( @commands ) { + @array[0..$c-1] = @array[ reverse 0..$c-1]; + push @array, shift @array for 1..$c + $skip++; + $i += $c + $skip-1; + } + } + + unshift @array, pop @array for 1..($i%@array); + + my $j; + my @grouped = map { + reduce { $a ^ $b } @$_ + } part { $j++ / 16 } @array; + + return join '', map { sprintf "%02x", $_ } @grouped; +}