day-03.jl (2881B)
1 function build_path(ops) 2 path = map(ops) do op 3 steps = parse(Int, op[2:end]) 4 if op[1] == 'R' 5 [steps, 0] 6 elseif op[1] == 'L' 7 [-steps, 0] 8 elseif op[1] == 'U' 9 [0, steps] 10 else 11 [0, -steps] 12 end 13 end 14 path = cumsum(path) 15 insert!(path, 1, sign.(path[1])) 16 path 17 end 18 19 function build_steps(ops) 20 steps = cumsum(map(op -> parse(Int, op[2:end]),ops)) 21 insert!(steps, 1, 1) 22 steps 23 end 24 25 function get_min_intersection(p1a, p1b, p2a, p2b) 26 rotated = false 27 if p1a[1] != p1b[1] 28 p1a = [p1a[2], p1a[1]]; 29 p1b = [p1b[2], p1b[1]]; 30 p2a = [p2a[2], p2a[1]]; 31 p2b = [p2b[2], p2b[1]]; 32 rotated = true; 33 end 34 res = nothing 35 if p2a[1] == p2b[1] 36 # Parallel case. 37 if p1a[1] == p2a[1] 38 cross_start = max(p1a[2], p2a[2]) 39 cross_end = min(p1b[2], p2b[2]) 40 if cross_start <= cross_end 41 if cross_start * cross_end <= 0 42 res = [p1a[1], 0] 43 else 44 if abs(cross_start) <= abs(cross_end) 45 res = [p1a[1], cross_start] 46 else 47 res = [p1a[1], cross_end] 48 end 49 end 50 end 51 end 52 else 53 # Vertical case. 54 if (p1a[1] - p2a[1]) * (p1a[1] - p2b[1]) <= 0 && 55 (p2a[2] - p1a[2]) * (p2a[2] - p1b[2]) <= 0 56 res = [p1a[1], p2a[2]] 57 end 58 end 59 if rotated && res != nothing 60 res = [res[2], res[1]] 61 end 62 res 63 end 64 65 function part_1(input) 66 path_1 = build_path(input[1]) 67 path_2 = build_path(input[2]) 68 min_dist = Inf 69 for i = 2:length(path_1) 70 for j = 2:length(path_2) 71 min_cross = get_min_intersection(path_1[i - 1], path_1[i], path_2[j - 1], path_2[j]) 72 if !isnothing(min_cross) 73 min_dist = min(min_dist, sum(abs.(min_cross))) 74 end 75 end 76 end 77 Int(min_dist) 78 end 79 80 function part_2(input) 81 path_1 = build_path(input[1]) 82 path_2 = build_path(input[2]) 83 steps_1 = build_steps(input[1]) 84 steps_2 = build_steps(input[2]) 85 min_steps = Inf 86 for i = 2:length(path_1) 87 for j = 2:length(path_2) 88 min_cross = get_min_intersection(path_1[i - 1], path_1[i], path_2[j - 1], path_2[j]) 89 if !isnothing(min_cross) 90 step_1 = steps_1[i - 1] + sum(abs.(min_cross - path_1[i - 1])) 91 step_2 = steps_2[j - 1] + sum(abs.(min_cross - path_2[j - 1])) 92 min_steps = min(min_steps, step_1 + step_2) 93 end 94 end 95 end 96 Int(min_steps) 97 end 98 99 input = map(readlines(open("input.txt"))) do line 100 split(strip(line), ',') 101 end 102 103 println("Julia:") 104 println("Part 1: ", part_1(input)) 105 println("Part 2: ", part_2(input))