Day 2: Fulminating Farmland
Megathread guidelines
- Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
- You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL
FAQ
- What is this?: Here is a post with a large amount of details: https://programming.dev/post/6637268
- Where do I participate?: https://adventofcode.com/
- Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465


Lua
For part one I created a linked list of the colours, then pointed the “next” value of the last node to the first node, so that I could call
node.nextforever. Other people used mod which seems like a much more sensible solution. Oh well at least I learned about linked lists in lua!usage
lua robots.lua < inputPart1
Dots = "roygbv" function List.insert(node, value) node = {next = node, data = value} return node end function List.makeloop(head) local node = head local prev = nil while node do prev = node node = node.next end prev.next = head end function List.move(char, list) local incr = 0 local node = list if node.data == char then incr = 6 else while node.data ~= char do incr = incr + 1 node = node.next end end return incr, node end list = nil dist = 0 for i=#Dots,1,-1 do list = List.insert(list, Dots:sub(i,i)) end List.makeloop(list) local line = io.read("*line") for i=1,#line do incr, list = List.move(line:sub(i,i), list) dist = dist + incr end print(dist)For part 2 I just counted how many times each colour appeared, then printed them out in the correct order. I learned that iterating over a table in Lua using
pairs(table)is non-deterministic because it is a implemented using hashes, so I had to have another table to explicitly store the order.usage:
lua rearrange.lua < input | lua robot.luaPart2
local counts = {r=0, o=0, y=0, g=0, b=0, v=0} local order = {"r", "v", "b", "g", "y", "o"} local line = io.read("*line") for i = 1, #line do local char = line:sub(i, i) counts[char] = counts[char] + 1 end for _, key in ipairs(order) do for i = 1, counts[key] do io.write(key) end endI also learned a valuable lesson in version control when attempting to use
teeto debug and deleted my entire solution.Deleting your solution just means you get to rewrite it more optimally :)