Skip to content

Commit

Permalink
Year 2015: Day 04
Browse files Browse the repository at this point in the history
  • Loading branch information
joshleaves committed Feb 24, 2024
1 parent 2d00862 commit 098ebf0
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 11 deletions.
23 changes: 23 additions & 0 deletions spec/year_2015/day_04_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
require 'year_2015/day_04'

describe Year2015::Day04 do
context 'when Part 1' do
it 'gives a final result' do
expect(described_class.new('abcdef', true).to_i).to eq(609_043)
end
end

context 'when Results' do
subject(:input_data) do
'iwrupvqb'
end

it 'correctly answers part 1' do
expect(described_class.new(input_data, true).to_i).to eq(346_386)
end

it 'correctly answers part 2' do
expect(described_class.new(input_data).to_i).to eq(9_958_218)
end
end
end
17 changes: 6 additions & 11 deletions year_2015.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,25 +48,20 @@ The only thing to be wary of is on line 16: without the call to `#dup`, all of S

Passing by value or reference is a really wonky subject, but this [blog post](https://robertheaton.com/2014/07/22/is-ruby-pass-by-reference-or-pass-by-value/) got nice examples that will get you started.

## Day 04: The Ideal Stocking Stuffer
## Day 04:The Ideal Stocking Stuffer

```
Year2015::Day04
Part 1
finds winning numbers
calculates points
Year2016::Day05
when Part 1
gives a final result
Part 2
distributes cards
when Part 2
gives a final result
Results
when Results
correctly answers part 1
correctly answers part 2
```

Part one is pretty easy. One useful method is the [`#&`](https://ruby-doc.org/core-3.0.1/Array.html#method-i-26) operator that takes two arrays and returns a new one with only the matching contents. The syntax is clearly inspired by [bit masking](https://en.wikipedia.org/wiki/Mask_(computing)), which is a subject you should look into if you've never heard of it.

Part two is a bit more annoying and requires to do a two-pass, but nothing really improbable.
Not gonna lie, brute-forcing [MD5 hashes](https://en.wikipedia.org/wiki/MD5) is not something interesting.

## Day 05: Doesn't He Have Intern-Elves For This?

Expand Down
26 changes: 26 additions & 0 deletions year_2015/day_04.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
require 'digest'

class Year2015
class Day04
def initialize(input_data, input_part_one = false)
@version = input_part_one ? 1 : 2
@input = input_data.chomp
end

def md5
@md5 ||= Digest::MD5.new
end

def hash(str)
md5.reset
md5 << str
md5.hexdigest
end

def to_i
0.upto(100**100) do |i|
return i if hash("#{@input}#{i}").start_with?('0' * (@version + 4))
end
end
end
end

0 comments on commit 098ebf0

Please sign in to comment.