Skip to content

Instantly share code, notes, and snippets.

@colintsteele
Created December 3, 2021 17:20
Show Gist options
  • Save colintsteele/08888619eb62fc07e3c5dbcadf700aa1 to your computer and use it in GitHub Desktop.
Save colintsteele/08888619eb62fc07e3c5dbcadf700aa1 to your computer and use it in GitHub Desktop.
bitmarine
test_input = %w[00100 11110 10110 10111 10101 01111 00111 11100 10000 11001 00010 01010]
# puzzle_input <<-BIN
# # your puzzle input pasted here
# BIN
def most_common(list)
count = list.tally
if count.values.uniq.size == 1 # equal number of 1s and 0s
'1'
else
count.max_by(&:last).first
end
end
def gamma(input)
columns = input.first.size
matrix = input.map { |i| i.split('') }
bits = []
columns.times do |bit_column|
bits << find_common(matrix.map {|b| b[bit_column]})
end
bits.join
end
def epsilon(g)
ones = g.length.times.map{"1"}.join
("%0#{g.length}b" % (Integer("0b#{g}") ^ Integer("0b#{ones}")))
end
def power_output(binaries)
gams = gamma(binaries)
eps = epsilon(gams)
Integer("0b#{eps}") * Integer("0b#{gams}")
end
#part 2 methods
def o2_info(input, but_which_o2: :c)
columns = input.first.size
matrix = input.map { |i| i.split('') }
accepted = matrix.dup
columns.times do |bit_column|
bit = most_common(accepted.map{ |b| b[bit_column] })
if but_which_o2 == :c
accepted.reject! {|bs| bs[bit_column] == bit }
else
accepted.select! {|bs| bs[bit_column] == bit }
end
return accepted.join if accepted.size == 1
end
accepted.first.join # probably not necessary
end
def life_support(binaries)
co2 = o2_info(binaries, but_which_o2: :c)
o2 = o2_info(binaries, but_which_o2: :o)
Integer("0b#{co2}") * Integer("0b#{o2}")
end
power_output puzzle_input # part 1 solution
life_support puzzle_input # part 2 solution
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment