home

Scientific Computing (Psychology 9040a)

Fall, 2021

Advent of Code 2015 Day 1: Sample solution


%% Advent of Code 2015 Day 1
% Part 1
P = fileread("AOC2015Day1_input.txt");

f = 0; % starts at floor 0

for i=1:length(P)
    if P(i)=='('
        f = f + 1;
    elseif P(i)==')'
        f = f - 1;
    end
end

fprintf("the answer to part 1 is %d\n", f);

%% Part 2

f = 0; % starts at floor 0

i = 1;
while (f>=0)
    if P(i)=='('
        f = f + 1;
    elseif P(i)==')'
        f = f - 1;
    end
    i = i + 1;
end

fprintf("the answer to part 2 is %d\n", i-1);