From c085f4461fecd03e9685312a8adf0886357f312d Mon Sep 17 00:00:00 2001 From: s00ner Date: Sat, 4 Dec 2021 11:48:04 -0500 Subject: [PATCH] Solved Part 2 --- day03/input.sample.txt | 12 ++++++++++++ day03/solution.rb | 35 +++++++++++++++++++++++++++++------ 2 files changed, 41 insertions(+), 6 deletions(-) create mode 100644 day03/input.sample.txt diff --git a/day03/input.sample.txt b/day03/input.sample.txt new file mode 100644 index 0000000..665fd57 --- /dev/null +++ b/day03/input.sample.txt @@ -0,0 +1,12 @@ +00100 +11110 +10110 +10111 +10101 +01111 +00111 +11100 +10000 +11001 +00010 +01010 \ No newline at end of file diff --git a/day03/solution.rb b/day03/solution.rb index fd5186a..3f6ba70 100644 --- a/day03/solution.rb +++ b/day03/solution.rb @@ -1,16 +1,14 @@ #!/bin/env ruby -#part 1 +# Part 1 report = File.readlines('./input').map(&:strip) masks = [] -report[0].length.times{ masks.push(2 ** _1) } -report.map!{ _1.to_i(2) } +report[0].length.times { masks.push(2**_1) } +report.map! { _1.to_i(2) } gamma = 0 masks.each do |mask| - if report.map{ mask & _1 }.reject(&:zero?).count > report.count / 2 - gamma += mask - end + gamma += mask if report.map { mask & _1 }.reject(&:zero?).count > report.count / 2 end epsilon = gamma ^ masks.sum @@ -18,3 +16,28 @@ puts "Gamma is #{gamma}" puts "Epsilon is #{epsilon}" puts "Power is #{gamma * epsilon}" +# Part 2 +def get_rating(report, masks, invert) + report_copy = report.clone + masks.each do |mask| + common = invert ? 1 : 0 + if report_copy.map { mask & _1 }.reject(&:zero?).count >= report_copy.count / 2.to_f + common = invert ? 0 : 1 + end + report_copy.reject! do |number| + if common.zero? + (mask & number).zero? ? false : true + else + (mask & number).zero? ? true : false + end + end + return report_copy[0] if report_copy.count == 1 + end +end + +masks.reverse! +o2 = get_rating(report, masks, false) +co2 = get_rating(report, masks, true) +puts "Oxygen rating is #{o2}" +puts "CO2 rating is #{co2}" +puts "Life Support rating is #{o2 * co2}"