From 0b3ca698b7772e60beca8155436ad471dd157c3c Mon Sep 17 00:00:00 2001 From: red Date: Sun, 10 Mar 2024 03:04:53 +0100 Subject: [PATCH] Year 2016: Day 16 --- README.md | 2 +- spec/year_2016/day_16_spec.rb | 23 +++++++++++++++++++++++ year_2016.md | 13 +++++++++++++ year_2016/day_16.rb | 28 ++++++++++++++++++++++++++++ 4 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 spec/year_2016/day_16_spec.rb create mode 100644 year_2016/day_16.rb diff --git a/README.md b/README.md index f3eb285..404a675 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ I'm also adding notes that may be useful if you're learning Ruby. Notes for solving: * [2015, complete](year_2015.md) -* [2016, up to day 15](year_2016.md) +* [2016, up to day 16](year_2016.md) * [2023, up to day 04](year_2023.md) # How to use diff --git a/spec/year_2016/day_16_spec.rb b/spec/year_2016/day_16_spec.rb new file mode 100644 index 0000000..d454471 --- /dev/null +++ b/spec/year_2016/day_16_spec.rb @@ -0,0 +1,23 @@ +require 'year_2016/day_16' + +describe Year2016::Day16 do + context 'when Part 1' do + it 'gives a final result' do + expect(described_class.new('10000', true).to_s(20)).to eq('01100') + end + end + + context 'when Results' do + subject(:input_data) do + '11100010111110100' + end + + it 'correctly answers part 1' do + expect(described_class.new(input_data, true).to_s(272)).to eq('10100011010101011') + end + + it 'correctly answers part 2' do + expect(described_class.new(input_data).to_s(35_651_584)).to eq('01010001101011001') + end + end +end diff --git a/year_2016.md b/year_2016.md index 60ec622..5f08ad7 100644 --- a/year_2016.md +++ b/year_2016.md @@ -215,3 +215,16 @@ Year2016::Day15 ``` This one is funnier as a maths problem than an engineering problem. An [elegant solution](https://github.com/rHermes/adventofcode/blob/master/2016/15/y2016_d15_p01.py) worked in a very few lines. + +## Day 16: Dragon Checksum + +``` +Year2016::Day16 + when Part 1 + gives a final result + when Results + correctly answers part 1 + correctly answers part 2 +``` + +I liked this one, a lot. diff --git a/year_2016/day_16.rb b/year_2016/day_16.rb new file mode 100644 index 0000000..feef6e9 --- /dev/null +++ b/year_2016/day_16.rb @@ -0,0 +1,28 @@ +class Year2016 + class Day16 + def initialize(input_data, input_part_one = false) + @version = input_part_one ? 1 : 2 + @input = input_data.chomp.chars.map do |char| + char == '1' + end + end + + def expand_string(new_str) + [new_str, [false], new_str.reverse.map(&:!)].inject(&:concat) + end + + def checksum(string) + string.each_slice(2).map do |lhs, rhs| + lhs == rhs + end + end + + def to_s(disk_size) + str = @input + str = expand_string(str) until str.length >= disk_size + str = str[0..disk_size - 1] if str.length >= disk_size + str = checksum(str) until str.length.odd? + str.map{|elt| elt ? '1' : '0' }.join + end + end +end