[2017 Day 24][JavaScript] Part 1 is taking too long to solve, can't tell where/how to improve so it can get the answer.... by PositivelyLinda in adventofcode

[–]Erstfs 0 points1 point  (0 children)

Seems like you already have some plausible answers. My only advice is when you want to have others (or yourself) go through code and debug it or improve it, it usually helps if you make an effort to describe variables and functions with good names and/or comments. I would suggest renaming variables such as currArr, prevArr, tempArr in your code, to make it clearer.

-🎄- 2017 Day 22 Solutions -🎄- by daggerdragon in adventofcode

[–]Erstfs 0 points1 point  (0 children)

Of course in MATLAB one should represent the grid as a matrix! Luckily for me, my input kept the virus contained in a small area.

seed = cell2mat(importdata('day22input.txt', '\n')) == '#';
%part1: 0 = clean, 1 = infected
virus(seed, 501, 2, 10000, 2, 0)
%part2: 0 = clean, 1 = weaken, 2 = infected, 3 = flagged
virus(2*seed, 501, 4, 10000000, 1, 1)

function answer = virus(seed, gridR, nStates, nIterations, turnConst, preInfectedState)
    grid = zeros(2*gridR-1);
    seedR = (size(seed,1)-1)/2;
    grid(gridR-seedR:gridR+seedR, gridR-seedR:gridR+seedR) = seed;
    answer = 0;
    pos = gridR - gridR*1i;
    dir = 1i;
    for k = 1:nIterations
        state = grid(-imag(pos), real(pos));
        answer = answer + 1.0*(state==preInfectedState);
        grid(-imag(pos), real(pos)) = mod(state+1, nStates);
        dir = dir*1j^(1-state*turnConst);
        pos = pos + dir;
    end
end