view 10/10.jl @ 15:6fd4445cbd22

Day 10
author Lewin Bormann <lbo@spheniscida.de>
date Sun, 11 Dec 2022 17:56:27 +0100
parents
children
line wrap: on
line source


const test_input = "10/test_input.txt";
const input = "10/input.txt";

@enum OpType begin
    Noop
    Addx
end

struct Op
    type::OpType
    arg::Int
end

function parse_line(s::S)::Op where {S<:AbstractString}
    p = split(s, ' ');
    if length(p) == 1
        Op(Noop, 0)
    else
        Op(Addx, parse(Int, p[2]))
    end
end

function parse_input(io::Iter)::Vector{Op} where {Iter}
    map(parse_line, eachline(io))
end

function check_register(interest::Vector{Int}, cycle::Int, reg::Int)::Int
    if length(interest) == 0
        return 0;
    end
    if cycle == interest[begin]
        popfirst!(interest);
        cycle * reg
    else
        0
    end
end

function evaluate(v::Vector{Op})::Int
    interest = [20, 60, 100, 140, 180, 220];
    reg = 1;
    i = 1;
    cc = 0;
    acc = 0;
    L = length(v);
    for i = 1:L
        op = v[i];
        cc += 1;
        acc += check_register(interest, cc, reg);
        if op.type == Noop
            # pass
        elseif op.type == Addx
            # first cycle;

            # second cycle;
            cc += 1;
            acc += check_register(interest, cc, reg);
            # done.
            reg += op.arg;
        end
    end
    acc
end

function draw_pixel(crt::Matrix{Bool}, cycle::Int, reg::Int)
    row, col = (div(cycle, 40)), ((cycle)%40);
    reg_ = (reg)%40;
    if abs((col)-reg_) < 2
        crt[row+1, col+1] = true;
    end
end

function draw_crt(v::Vector{Op})::Matrix{Bool}
    crt = zeros(Bool, 6, 40);
    cc = 0;
    reg = 1;
    L = length(v);
    for i = 1:L
        op = v[i];
        cc += 1;
        draw_pixel(crt, cc, reg);
        if op.type == Noop
            continue
        elseif op.type == Addx
            # first cycle;

            # second cycle;
            cc += 1;
            # done.
            reg += op.arg;
            draw_pixel(crt, cc, reg);
        end
    end
    crt
end

println("part 1:");
println("test:");
open(test_input; read=true) do fh
    println(evaluate(parse_input(fh)))
end
println("input:");
open(input; read=true) do fh
    println(evaluate(parse_input(fh)))
end

println("part 2:");
println("test:");
open(test_input; read=true) do fh
    m = (draw_crt(parse_input(fh)));
    for r in eachrow(m)
        println(r);
    end
end
println("input:");
open(input; read=true) do fh
    m = (draw_crt(parse_input(fh)));
    for r in eachrow(m)
        println(r);
    end
end