Skip to content

Instantly share code, notes, and snippets.

@neofight78
Last active December 2, 2021 10:18
Show Gist options
  • Save neofight78/fc46972d5de6d21262da35e3c766d24d to your computer and use it in GitHub Desktop.
Save neofight78/fc46972d5de6d21262da35e3c766d24d to your computer and use it in GitHub Desktop.
Advent of Code 2021 - Day 2: Dive!
fn plot_course(instructions: &[&str]) -> i64 {
let mut pos = 0;
let mut depth = 0;
for &instruction in instructions {
let mut parts = instruction.split_whitespace();
let direction = parts.next().unwrap();
let units = parts.next().unwrap().parse::<i64>().unwrap();
match direction {
"forward" => pos += units,
"down" => depth += units,
"up" => depth -= units,
_ => panic!("Unknown direction: {}", direction),
}
}
pos * depth
}
fn plot_course_with_aim(instructions: &[&str]) -> i64 {
let mut pos = 0;
let mut depth = 0;
let mut aim = 0;
for &instruction in instructions {
let mut parts = instruction.split_whitespace();
let direction = parts.next().unwrap();
let units = parts.next().unwrap().parse::<i64>().unwrap();
match direction {
"forward" => {
pos += units;
depth += units * aim;
}
"down" => aim += units,
"up" => aim -= units,
_ => panic!("Unknown direction: {}", direction),
}
}
pos * depth
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment