include("utils.jl") function parse_input(filename) input_lines = collect(non_empty_lines(filename)) width = length(input_lines[1]) integers = map(x->parse(Int, x, base = 2), input_lines) (integers, width) end function most_common_bit(integers, width) score = zeros(Int, width) for int in integers for index in 1:width score[index] += ((int >> (index-1) & 1) - 0.5) * 2 end end map(map(sign, score)) do x if x == 0 1 else x end end end function solution3_1() integers, width = parse_input("3.data") score = most_common_bit(integers, width) result = 0 cresult = 0 for i in 1:width result += ((score[i] + 1) >> 1) << (i - 1) cresult += (((score[i] * -1) + 1) >> 1) << (i - 1) end (result, cresult, result * cresult) end function filterdata(integers, width, score_factor) ints = copy(integers) for i in reverse(1:width) score = most_common_bit(ints, width) * score_factor ints = filter(ints) do x (x & (1 << (i - 1))) >> (i - 1) == (score[i] + 1) >> 1 end if length(ints) == 1 break end end ints[1] end function solution3_2() integers, width = parse_input("3.data") oxy = filterdata(integers, width, 1) co2 = filterdata(integers, width, -1) (oxy, co2, oxy * co2) end solution3_2()