view 02/02.jl @ 2:5bf75b17187c

Improvement to day 02 solution
author Lewin Bormann <lbo@spheniscida.de>
date Fri, 02 Dec 2022 20:01:44 +0100
parents a83e493cb7f4
children
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
    shape = (if il.choice == 'X'; loseshape elseif il.choice == 'Y'; Int(il.opponent-'A') else winshape end);
    shape+1 + winscore
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

print(run_02(input))