Skip to content

Commit

Permalink
Year 2016: Day 16
Browse files Browse the repository at this point in the history
  • Loading branch information
joshleaves committed Mar 10, 2024
1 parent dab452f commit 0b3ca69
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 23 additions & 0 deletions spec/year_2016/day_16_spec.rb
Original file line number Diff line number Diff line change
@@ -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
13 changes: 13 additions & 0 deletions year_2016.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
28 changes: 28 additions & 0 deletions year_2016/day_16.rb
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 0b3ca69

Please sign in to comment.