optimize day 3
This commit is contained in:
parent
7d2923a6bc
commit
40682f6cb6
40
src/day_3.jl
40
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)
|
||||
|
||||
cobits = map(x -> x[i], i2)
|
||||
comc = count(==('1'), cobits) >= count(==('0'), cobits) ? '0' : '1'
|
||||
oxmc = sum(oxbits) >= length(oxbits) / 2 ? '1' : '0'
|
||||
comc = sum(cobits) >= length(cobits) / 2 ? '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
|
||||
|
Loading…
x
Reference in New Issue
Block a user