day 2
This commit is contained in:
parent
7b645a9ace
commit
d0a856da6e
3 changed files with 1049 additions and 0 deletions
|
@ -7,4 +7,8 @@ edition = "2021"
|
||||||
name = "day01"
|
name = "day01"
|
||||||
path = "src/day01/main.rs"
|
path = "src/day01/main.rs"
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "day02"
|
||||||
|
path = "src/day02/main.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
|
1000
input/day02.txt
Normal file
1000
input/day02.txt
Normal file
File diff suppressed because it is too large
Load diff
45
src/day02/main.rs
Normal file
45
src/day02/main.rs
Normal 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"),
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue