feat: solve day 2 part 2
This commit is contained in:
parent
28223a1b34
commit
b36eb44b3c
31
src/day2.rs
31
src/day2.rs
@ -53,6 +53,23 @@ pub fn part1(commands: &[CommandLine]) -> u32 {
|
||||
return depth * horizontal;
|
||||
}
|
||||
|
||||
pub fn part2(commands: &[CommandLine]) -> u32 {
|
||||
let mut depth = 0;
|
||||
let mut horizontal = 0;
|
||||
let mut aim = 0;
|
||||
for command in commands {
|
||||
match command.0 {
|
||||
Command::Up => aim -= command.1,
|
||||
Command::Down => aim += command.1,
|
||||
Command::Forward => {
|
||||
horizontal += command.1;
|
||||
depth += aim * command.1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return depth * horizontal;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@ -70,5 +87,19 @@ mod tests {
|
||||
let result = part1(&commands);
|
||||
assert_eq!(result, 150);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part2_example() {
|
||||
let commands = [
|
||||
CommandLine(Command::Forward, 5),
|
||||
CommandLine(Command::Down, 5),
|
||||
CommandLine(Command::Forward, 8),
|
||||
CommandLine(Command::Up, 3),
|
||||
CommandLine(Command::Down, 8),
|
||||
CommandLine(Command::Forward, 2)
|
||||
];
|
||||
let result = part2(&commands);
|
||||
assert_eq!(result, 900)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -10,9 +10,9 @@ fn main() {
|
||||
// let result2 = day1::part2(&input);
|
||||
|
||||
let result1 = day2::part1(&input);
|
||||
// let result2 = day2::part2(&input);
|
||||
let result2 = day2::part2(&input);
|
||||
|
||||
println!("Part 1 result: {}", result1);
|
||||
// println!("Part 2 result: {}", result2);
|
||||
println!("Part 2 result: {}", result2);
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user