|
| 1 | +abstract type Instruction end |
| 2 | + |
| 3 | +struct Add <: Instruction |
| 4 | + label::String |
| 5 | + len::Int |
| 6 | +end |
| 7 | + |
| 8 | +struct Rem <: Instruction |
| 9 | + label::String |
| 10 | +end |
| 11 | + |
| 12 | +function calcHash(str::AbstractString)::Int |
| 13 | + result = 0 |
| 14 | + for c in str |
| 15 | + result += Int(c) |
| 16 | + result *= 17 |
| 17 | + result = result % 256 |
| 18 | + end |
| 19 | + result |
| 20 | +end |
| 21 | + |
| 22 | +function solveA(input) |
| 23 | + steps = split(input, ",") |
| 24 | + [ calcHash(s) for s in steps ] |> sum |
| 25 | +end |
| 26 | + |
| 27 | +function parseStep(str)::Instruction |
| 28 | + if str[end] == '-' |
| 29 | + return Rem(join(str[1:end-1])) |
| 30 | + else |
| 31 | + label = str[1:end - 2] |
| 32 | + len = parse(Int, str[end]) |
| 33 | + return Add(join(label), len) |
| 34 | + end |
| 35 | +end |
| 36 | + |
| 37 | +function placeLensInBoxes!(hashmap::Dict{String, Int}, instructions::Vector{Instruction}, boxes::Vector{Vector{Add}}) |
| 38 | + for instruction in instructions |
| 39 | + n = hashmap[instruction.label] |
| 40 | + box = boxes[n + 1] |
| 41 | + i = findfirst(x -> x.label == instruction.label, box) |
| 42 | + if instruction isa Add |
| 43 | + if i === nothing |
| 44 | + push!(box, instruction) |
| 45 | + else |
| 46 | + box[i] = instruction |
| 47 | + end |
| 48 | + else # Rem |
| 49 | + i !== nothing && deleteat!(box, i) |
| 50 | + end |
| 51 | + end |
| 52 | +end |
| 53 | + |
| 54 | +calculateFocusingPower(box::Int, slot::Int, len::Int) = box * slot * len |
| 55 | + |
| 56 | +function solveB(input) |
| 57 | + boxesN = 256 |
| 58 | + steps = split(input, ",") |
| 59 | + instructions = [ parseStep(s) for s in steps ] |
| 60 | + hashmap = Dict([ (i.label, calcHash(i.label)) for i in instructions ]) |
| 61 | + boxes::Vector{Vector{Add}} = repeat([Vector{Add}[]], boxesN) |
| 62 | + placeLensInBoxes!(hashmap, instructions, boxes) |
| 63 | + result = 0 |
| 64 | + for b in 1:boxesN |
| 65 | + for (i, lens) in enumerate(boxes[b]) |
| 66 | + result += calculateFocusingPower(b, i, lens.len) |
| 67 | + end |
| 68 | + end |
| 69 | + return result |
| 70 | +end |
| 71 | + |
| 72 | +function main(file = "day15.txt") |
| 73 | + # input = collect(eachline(file)) |
| 74 | + input = strip(read(file, String)) |
| 75 | + # 495972 |
| 76 | + println("Solving Day15A...") |
| 77 | + println(solveA(input)) |
| 78 | + # 245223 |
| 79 | + println("Solving Day15B...") |
| 80 | + println(solveB(input)) |
| 81 | +end |
| 82 | + |
| 83 | +if !isinteractive() |
| 84 | + main() |
| 85 | +end |
| 86 | + |
| 87 | +function repl() |
| 88 | + # file = "day15s.txt" |
| 89 | + file = "day15.txt" |
| 90 | + println("file: $file") |
| 91 | + main(file) |
| 92 | +end |
0 commit comments