day02.lua (796B)
1 local waypoints = { 2 r=0, 3 o=1, 4 y=2, 5 g=3, 6 b=4, 7 v=5 8 } 9 local wl = 6 10 local input = {} 11 12 while true do 13 local w = io.read(1) 14 if not w or w=="\n" then break end 15 table.insert(input, w) 16 end 17 18 function calcDistance(input) 19 local d = 0 20 local p = 0 21 22 for _, w in ipairs(input) do 23 if waypoints[w] > p then 24 d = d + (waypoints[w] - p) 25 p = waypoints[w] 26 else 27 d = d + (wl + waypoints[w]) - p 28 p = (wl + waypoints[w]) % wl 29 end 30 end 31 return d 32 end 33 34 print("part 1:", calcDistance(input)) 35 36 table.sort(input, function (a, b) 37 local a1 = waypoints[a] 38 local b1 = waypoints[b] 39 if a1==0 then a1 = 6 end 40 if b1==0 then b1 = 6 end 41 return a1>b1 42 end) 43 44 print("part 2:", calcDistance(input))