From 40682f6cb67eb3aa6f440b2c2fdcfd868b17be2e Mon Sep 17 00:00:00 2001 From: Patrick Michl Date: Fri, 3 Dec 2021 09:26:46 +0100 Subject: [PATCH] optimize day 3 --- src/day_3.jl | 40 ++++++++++++++++------------------------ 1 file changed, 16 insertions(+), 24 deletions(-) diff --git a/src/day_3.jl b/src/day_3.jl index 0d7456b..0e16021 100644 --- a/src/day_3.jl +++ b/src/day_3.jl @@ -3,44 +3,36 @@ import .Aoc: @aoc function p1(input::Vector{String}) - o = [[],[],[],[],[],[],[],[],[],[],[],[]] - for l in input - c = match(r"(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)", l).captures - for i in 1:12 - push!(o[i], c[i]) - end - end γ = "" ϵ = "" - for n in o - γ *= count(==("1"), n) > count(==("0"), n) ? "1" : "0" - ϵ *= count(==("1"), n) > count(==("0"), n) ? "0" : "1" + for n in 1:length(input[1]) + bits = map(x -> parse(Int, x[n]), input) + more_ones = sum(bits) > length(bits) / 2 + γ *= more_ones ? "1" : "0" + ϵ *= more_ones ? "0" : "1" end parse(Int, γ; base=2) * parse(Int, ϵ; base=2) end function p2(input::Vector{String}) - i1 = deepcopy(input) - i2 = deepcopy(input) + i1 = copy(input) + i2 = copy(input) ox = "" co = "" for i in 1:length(input[1]) - oxbits = map(x -> x[i], i1) - oxmc = count(==('1'), oxbits) >= count(==('0'), oxbits) ? '1' : '0' - filter!(x -> x[i] == oxmc, i1) + oxbits = map(x -> parse(Int, x[i]), i1) + cobits = map(x -> parse(Int, x[i]), i2) + + oxmc = sum(oxbits) >= length(oxbits) / 2 ? '1' : '0' + comc = sum(cobits) >= length(cobits) / 2 ? '0' : '1' - cobits = map(x -> x[i], i2) - comc = count(==('1'), cobits) >= count(==('0'), cobits) ? '0' : '1' + filter!(x -> x[i] == oxmc, i1) filter!(x -> x[i] == comc, i2) - if length(i1) == 1 && ox == "" - ox = i1[begin] - end - - if length(i2) == 1 && co == "" - co = i2[begin] - end + length(i1) == 1 && ox == "" ? (ox = i1[1]) : nothing + length(i2) == 1 && co == "" ? (co = i2[1]) : nothing + ox != "" && co != "" ? break : continue end parse(Int, ox; base=2) * parse(Int, co; base=2) end