Part 1


In [1]:
test = [
    "0: 3",
    "1: 2",
    "4: 4",
    "6: 4"
]


Out[1]:
4-element Array{String,1}:
 "0: 3"
 "1: 2"
 "4: 4"
 "6: 4"

In [2]:
function parse_input(values)
    result = Dict()
    for v in values
        depth, range = match(r"([0-9]+): ([0-9]+)", v).captures
        result[parse(Int32, depth)] = parse(Int32, range)
    end
    result
end


Out[2]:
parse_input (generic function with 1 method)

In [3]:
firewall = parse_input(test)


Out[3]:
Dict{Any,Any} with 4 entries:
  0 => 3
  4 => 4
  6 => 4
  1 => 2

In [4]:
function compute_severity(firewall, delay)    
    severity = 0
    max_time = maximum(keys(firewall)) + delay
    p = -delay
    for t = 0:max_time
        if haskey(firewall, p) && t % (2*firewall[p] - 2)==0
            severity += t*firewall[p]
        end        
        p += 1
    end
    severity
end


Out[4]:
compute_severity (generic function with 1 method)

In [5]:
compute_severity(parse_input(test), 0)


Out[5]:
24

In [6]:
open("inputs/day13.txt") do fd
    lines = readlines(fd)
    compute_severity(parse_input(lines), 0)
end


Out[6]:
1704

Part 2


In [7]:
function is_caught(firewall, delay)    
    max_time = maximum(keys(firewall)) + delay
    p = 0
    for t = delay:max_time
        if haskey(firewall, p) && t % (2*firewall[p] - 2)==0
            return true
        end        
        p += 1
    end
    return false
end

function no_caught(firewall)    
    w = 0
    while is_caught(firewall, w)
        if w%10000000 == 0
            println(w)
        end
        w += 1
    end    
    w
end


Out[7]:
no_caught (generic function with 1 method)

In [8]:
compute_severity(parse_input(test), 10)


Out[8]:
0

In [9]:
no_caught(parse_input(test))


0
Out[9]:
10

In [13]:
open("inputs/day13.txt") do fd
    lines = readlines(fd)
    @time no_caught(parse_input(lines))
end


0
  7.560550 seconds (60.41 M allocations: 1.141 GiB, 0.79% gc time)
Out[13]:
3970918

In [ ]: