Day 01 - Not Quite Lisp
Language: Rust
Problem https://adventofcode.com/2015/day/1
Part 1:
The input is a string of parentheses. ( means go up one floor, ) means go down one.
Start at floor 0 and find the final floor after processing everything.
A fold over the characters works perfectly here:
let sum = input.chars().fold(0, |acc, c| {
acc + match c {
'(' => 1,
')' => -1,
_ => 0,
}
});
Part 2: Find the position of the first character that sends Santa into the basement, meaning the floor hits -1. I walk through the characters, update the floor, and return the index as soon as it drops:
for (i, c) in input.chars().enumerate() {
match c {
'(' => floor += 1,
')' => floor -= 1,
_ => {}
}
if floor == -1 {
return (i + 1).to_string();
}
}
Position is 1-indexed so i + 1.
Solution: https://github.com/Elyrial/AdventOfCode/blob/main/src/solutions/year2015/day01.rs
Language: C
Problem https://adventofcode.com/2015/day/1
Part 1:
The input is a string of parentheses. ( means go up one floor, ) means go down one.
Start at floor 0 and find the final floor after processing everything.
A single pass with a pointer through the string does it:
while (*p) {
if (*p == '(')
floor++;
else if (*p == ')')
floor--;
p++;
}
Part 2: Find the position of the first character that sends Santa into the basement, meaning the floor hits -1. Same loop, but check after each step and return the 1-indexed position:
while (*p) {
if (*p == '(')
floor++;
else if (*p == ')')
floor--;
if (floor == -1)
return (long long)(p - input) + 1;
p++;
}
The pointer difference p - input gives the 0-based index, so adding 1 gives the 1-indexed position.
Solution: https://github.com/Elyrial/AdventOfCode_C/blob/main/src/solutions/year2015/day01.c