-
-
Save kenzan100/797b993d5c6bff16ccf068c23e27ab2b to your computer and use it in GitHub Desktop.
AdventOfCode 2021 Day 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://adventofcode.com/2021/day/3 | |
require 'pp' | |
require_relative 'get_response' | |
# Abstracted getting/parsing input | |
raw = GetResponse.new(day: 3).call | |
# ----- Part 2 ------ | |
# writing my own transpose just for fun | |
def transpose(raw) | |
transposed = Array.new(raw.first.length) { Array.new(raw.length) } | |
raw.each.with_index do |row, i| | |
row.split("").each.with_index do |cell, j| | |
transposed[j][i] = cell | |
end | |
end | |
transposed | |
end | |
transposed = transpose(raw) | |
gamma = raw.length.times.map { |i| i } | |
epsilon = raw.length.times.map { |i| i } | |
def reduce(row, indices, mode:) | |
return indices if indices.length <= 1 | |
one = 0 | |
zero = 0 | |
indices.each do |idx| | |
row[idx] == "1" ? (one += 1) : (zero += 1) | |
end | |
indices.map do |idx| | |
target = if mode == :gamma | |
one >= zero ? "1" : "0" | |
else | |
zero <= one ? "0" : "1" | |
end | |
row[idx] == target ? idx : nil | |
end.compact | |
end | |
transposed.each.with_index do |row, i| | |
gamma = reduce(row, gamma, mode: :gamma) | |
epsilon = reduce(row, epsilon, mode: :epsilon) | |
end | |
ox = raw[gamma.first].to_i(2) | |
co2 = raw[epsilon.first].to_i(2) | |
pp ox * co2 | |
# ------ Pt. 1 -------- | |
# buckets, gamma, epsilon = 3.times.map { Array.new(12) { 0 } } | |
# pp [buckets, gamma, epsilon] | |
# raw.each do |row| | |
# row.split("").each.with_index do |digit, i| | |
# buckets[i] += (digit == "1" ? 1 : -1) | |
# end | |
# end | |
# buckets.each.with_index do |digit, i| | |
# if digit > 0 | |
# gamma[i] = "1" | |
# epsilon[i] = "0" | |
# else | |
# gamma[i] = "0" | |
# epsilon[i] = "1" | |
# end | |
# end | |
# pp [ gamma, epsilon ] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment