Add day 2 and partial day3

This commit is contained in:
Andrew R. M 2021-12-10 11:31:06 -05:00
parent 729a8ff201
commit b8077a35c3
4 changed files with 1124 additions and 0 deletions

60
src/day2/day2.rb Normal file
View File

@ -0,0 +1,60 @@
Point = Struct.new(:x, :y) do
def +(other)
self.class.new(self.x + other.x, self.y + other.y)
end
end
def process_input(input_string)
split = input_string.split
return split.first.to_sym, split.last.to_i
end
def step_to_point(direction, amount)
x = y = 0
case direction
when :forward
x = amount
when :down
y = amount
when :up
y = -amount
end
return Point.new(x, y)
end
position = Point.new(0, 0)
inputs = ARGF.read.lines
inputs.map do |input|
direction, amount = process_input(input)
point = step_to_point(direction, amount)
position += position + point
end
puts "Position is (#{position.x}, #{position.y})"
puts "The product of depth and height is #{position.x * position.y}"
# Aim portion
def step_to_point_with_aim(direction, amount, aim)
x = y = 0
case direction
when :forward
x += amount
y += amount * aim
when :down
aim += amount
when :up
aim -= amount
end
return Point.new(x, y), aim
end
position = Point.new(0, 0)
aim = 0
inputs.map do |input|
direction, amount = process_input(input)
point, aim = step_to_point_with_aim(direction, amount, aim)
position += position + point
end
puts "Position considering aim is (#{position.x}, #{position.y})"
puts "The product of depth and height considering aim is #{position.x * position.y}"

1000
src/day2/input Normal file

File diff suppressed because it is too large Load Diff

52
src/day3/day3.rb Normal file
View File

@ -0,0 +1,52 @@
def process_input(input)
input.strip.to_i(2)
end
def find_most_common_bit(report)
bit_length = report.first.bit_length
ones_count = []
zeros_count = []
report.each do |column|
index = 0
while index <= bit_length + 1 do
ones_count[index] ||= 0
zeros_count[index] ||= 0
case column[index]
when 0 then zeros_count[index] += 1
when 1 then ones_count[index] += 1
end
index += 1
end
end
result = ones_count.zip(zeros_count)
puts "Result: #{result}"
result.map do |digit|
if digit.first > digit.last then 1 else 0 end
end
return result
end
def find_least_common_bit(report)
most_common_bit = find_most_common_bit(report)
least_common_bit = most_common_bit.map do |bit|
case bit
when 0 then 1
when 1 then 0
end
end
return least_common_bit
end
inputs = ARGF.read.lines
puts "Report looks like: "
report = []
inputs.each do |input|
puts " #{input}"
processed_input = process_input(input)
report << processed_input
end
puts "Gamma Rate: #{find_most_common_bit(report)}"
puts "Epsilon Rate: #{find_least_common_bit(report)}"

12
src/day3/input Normal file
View File

@ -0,0 +1,12 @@
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010