advent-of-code

advent of code attempts
git clone git://bvnf.space/advent-of-code.git
Log | Files | Refs

a.lua (1124B)


      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
local f
if (arg[1]) then
    f = assert(io.open(arg[1], "r"))
else
    f = io.stdin
end

--[[
    rock     = 1
    paper    = 2
    scissors = 3
--]]

function parse(char)
    local res = {
        A = 1, B = 2, C = 3,
        X = 1, Y = 2, Z = 3,
    }
    return res[char]
end

function resultA(them, us)
    if them == us then
        return 3
    elseif (us - them) % 3 == 1 then
        return 6
    else
        return 0
    end
end

function resultB(them, outcome)
    if outcome == 2 then
        return them
    elseif outcome == 3 then
        return (them % 3) + 1
    else
        if them - 1 == 0 then
            return 3
        else
            return them - 1
        end
    end
end


totala = 0
totalb = 0
for line in f:lines() do
    -- lines look like "A X"
    --                  123
    local them = parse(assert(string.sub(line, 1, 1)))
    local us   = parse(assert(string.sub(line, 3, 3)))
    local scorea = resultA(them, us) + us
    local scoreb = resultB(them, us) + ((us-1) * 3)
    totala = totala + scorea
    totalb = totalb + scoreb
end

print("Part A:", totala)
print("Part B:", totalb)