Day 1: Dusty Shed

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

  • Hugh@programming.dev
    link
    fedilink
    arrow-up
    5
    ·
    edit-2
    2 days ago

    Lua

    My first time ever using lua.

    Usage: lua frequencies.lua < input

    local frequencies = {}
    local pt1 = 1
    local pt2 = 1
    local uniq = 0
    
    -- initialise table of zeros. Assumes all IDs are three digit nums
    for i = 1, 999 do
            table.insert(frequencies, {id = i, frequency = 0})
    end
    
    while true do
            local line = io.read("*number")
            if line == nil then break end
            frequencies[line].frequency = frequencies[line].frequency + 1
            if frequencies[line].frequency == 1 then
                    uniq = uniq + 1
            end
    end
    
    print("Number of unique IDs is: " .. uniq)
    
    local function compareDescending(a, b)
            return a.frequency > b.frequency
    end
    
    table.sort(frequencies, compareDescending)
    
    -- Get the top three
    print("Pos\tID\tfreq")
    for i = 1, 3 do
            print(i, frequencies[i].id, frequencies[i].frequency)
            pt1 = pt1 * frequencies[i].id
    end
    
    -- Get the bottom three
    for i = 1, 3 do
            j = uniq - 3 + i
            print(j, frequencies[j].id, frequencies[j].frequency)
            pt2 = pt2 * frequencies[j].id
    end
    
    print("Answer to part 1 is: " .. pt1)
    print("Answer to part 2 is: " .. pt2)
    

    edit: updated to include solution to part 2