view 02/02.jl @ 1:a83e493cb7f4

Day 02
author Lewin Bormann <lbo@spheniscida.de>
date Fri, 02 Dec 2022 19:57:31 +0100
parents
children 5bf75b17187c
line wrap: on
line source

const input = "02/input.txt"

struct InputLine
    opponent::Char
    choice::Char
end

function parse(fh::IO)::Vector{InputLine}
    v = Vector{InputLine}();
    while true
        l = readline(fh);
        if isempty(l)
            break;
        end
        a, b = split(chomp(l));
        push!(v, InputLine(a[1], b[1]));
    end
    v
end

function score(il::InputLine)::Int
    shapescore = Int(il.choice - 'W');
    op, me = Int(il.opponent-'A'), Int(il.choice-'X')
    @assert abs(me-op) <= 2
    if abs(me-op) == 0
        shapescore + 3
    elseif abs(me-op) == 1
        shapescore + (me > op ? 6 : 0)
    else
        shapescore + (me < op ? 6 : 0)
    end
end

function score2(il::InputLine)::Int
    winscore = 3 * Int(il.choice-'X');
    winshape = (Int(il.opponent-'A')+1)%3;
    loseshape = (Int(il.opponent-'A')-1);
    if loseshape < 0
        loseshape += 3
    end
    if il.choice == 'X'
        (loseshape+1) + winscore
    elseif il.choice == 'Y'
        Int(il.opponent-'A')+1 + winscore
    elseif il.choice == 'Z'
        (winshape+1) + winscore
    else
        @assert false
    end
end

function calc(v::Vector{InputLine})::Tuple{Int, Int}
    sum(map(score, v)), sum(map(score2, v))
end

function run_02(file::String)::Tuple{Int,Int}
    open(file; read=true) do fh
        p = parse(fh);
        calc(p)
    end
end