This commit is contained in:
anna 2021-12-02 21:40:16 +01:00
parent 7b645a9ace
commit d0a856da6e
Signed by: fef
GPG key ID: EC22E476DC2D3D84
3 changed files with 1049 additions and 0 deletions

View file

@ -7,4 +7,8 @@ edition = "2021"
name = "day01"
path = "src/day01/main.rs"
[[bin]]
name = "day02"
path = "src/day02/main.rs"
[dependencies]

1000
input/day02.txt Normal file

File diff suppressed because it is too large Load diff

45
src/day02/main.rs Normal file
View file

@ -0,0 +1,45 @@
use std::io;
struct Location {
pos: i32,
depth: i32,
aim: i32,
}
fn main() {
let stdin = io::stdin();
let mut loc = Location {
pos: 0,
depth: 0,
aim: 0,
};
loop {
let mut buf = String::new();
match stdin.read_line(&mut buf).unwrap() {
0 => break,
_ => handle_cmd(&mut loc, buf.trim())
}
}
println!("Submarine is at pos {}, depth {}", loc.pos, loc.depth);
println!("Answer: {}", loc.pos * loc.depth);
}
fn handle_cmd(loc: &mut Location, cmd: &str) {
let mut iter = cmd.split_whitespace();
match iter.next() {
Some("up") => loc.aim -= iter.next().unwrap().parse::<i32>().unwrap(),
Some("down") => loc.aim += iter.next().unwrap().parse::<i32>().unwrap(),
Some("forward") => {
let val = iter.next().unwrap().parse::<i32>().unwrap();
loc.pos += val;
loc.depth += val * loc.aim;
if loc.depth < 0 {
panic!("submarine attempted to fly")
}
},
Some(s) => panic!("unknown command \"{}\"", s),
None => panic!("empty command"),
}
}