Skip to content

Instantly share code, notes, and snippets.

@scottynomad
Created December 12, 2020 06:19
Show Gist options
  • Save scottynomad/369fc32c64c2e22b4144547546b68612 to your computer and use it in GitHub Desktop.
Save scottynomad/369fc32c64c2e22b4144547546b68612 to your computer and use it in GitHub Desktop.
AOC 2020 Day 12
pub mod day12 {
// (+E/-W, +N/-S)
#[derive(Debug, Copy, Clone)]
pub struct Point(f32, f32);
#[derive(Debug)]
pub struct State {
current: Point,
heading: Point
}
impl State {
fn rotate_heading(&mut self, angle_change: f32) {
let rads = angle_change.to_radians();
let last_heading = self.heading;
self.heading.0 = (rads.sin() * last_heading.1 + rads.cos() * last_heading.0).round();
self.heading.1 = (rads.cos() * last_heading.1 - rads.sin() * last_heading.0).round();
}
}
pub fn run(input: &str, initial_heading: Point, part1: bool) -> f32 {
let mut state = State { current: Point(0.0, 0.0), heading: initial_heading };
for line in input.lines() {
let cmd = line.chars().next().unwrap();
let arg = line[1..].parse::<f32>().unwrap();
match cmd {
'E' => if part1 { state.current.0 += arg } else { state.heading.0 += arg },
'W' => if part1 { state.current.0 -= arg } else { state.heading.0 -= arg },
'N' => if part1 { state.current.1 += arg } else { state.heading.1 += arg },
'S' => if part1 { state.current.1 -= arg } else { state.heading.1 -= arg },
'F' => {
state.current.0 += arg * state.heading.0;
state.current.1 += arg * state.heading.1;
},
'L' => state.rotate_heading(-arg as f32),
'R' => state.rotate_heading(arg as f32),
_ => panic!("Unexpected cmd")
}
// println!("{} {:?}", line, state);
}
state.current.0.abs() + state.current.1.abs()
}
pub fn part1(input: &str) -> f32 {
run(input, Point(1.0, 0.0), true)
}
pub fn part2(input: &str) -> f32 {
run(input, Point(10.0, 1.0), false)
}
}
fn main() {
let input = std::fs::read_to_string("input.txt").expect("Reading input.txt");
println!("Day 12: {} {}", day12::part1(&input), day12::part2(&input));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment