dustin
/
aoc2021
Archived
1
0
Fork 0

Day 2, part 1

master
Dustin 2021-12-02 23:06:04 -06:00
parent 733813e719
commit e9d49de28d
3 changed files with 1061 additions and 0 deletions

1000
day2-input.txt Normal file

File diff suppressed because it is too large Load Diff

View File

@ -2,6 +2,7 @@ use std::io;
use argh::FromArgs;
mod pilot;
mod sonar;
#[derive(FromArgs)]
@ -15,6 +16,7 @@ struct Arguments {
#[argh(subcommand)]
enum SubCommand {
Sonar(SonarTracker),
Pilot(SubPilot),
}
#[derive(FromArgs)]
@ -30,6 +32,15 @@ struct SonarTracker {
window: usize,
}
#[derive(FromArgs)]
/// pilot the sub!
#[argh(subcommand, name = "pilot")]
struct SubPilot {
/// path to input data file
#[argh(positional)]
input: String,
}
fn main() -> io::Result<()> {
let args: Arguments = argh::from_env();
match args.command {
@ -37,6 +48,11 @@ fn main() -> io::Result<()> {
let count_incr = sonar::count_increases(&args.input, args.window)?;
println!("number of increases: {}", count_incr);
}
SubCommand::Pilot(args) => {
let pos = pilot::track_position(&args.input)?;
println!("Final Position: {},{}", pos.linear, pos.depth);
println!("Product: {}", pos.linear * pos.depth);
}
}
Ok(())
}

45
src/pilot.rs Normal file
View File

@ -0,0 +1,45 @@
use std::fs::File;
use std::io;
use std::io::prelude::*;
pub struct Position {
pub linear: i32,
pub depth: i32,
}
pub fn track_position(filename: &str) -> io::Result<Position> {
let f = File::open(filename)?;
let buf = io::BufReader::new(f);
let mut pos = Position {
linear: 0,
depth: 0,
};
for line in buf.lines() {
if let Ok(line) = line {
let mut parts = line.split_whitespace();
if let Some(op) = parts.next() {
if let Some(value) = parts.next() {
if let Ok(value) = i32::from_str_radix(value, 10) {
match op {
"forward" => {
pos.linear += value;
}
"down" => {
pos.depth += value;
}
"up" => {
pos.depth -= value;
}
_ => {
eprintln!("Invalid operation: {}", op);
}
}
} else {
eprintln!("Invalid value: {}", value);
}
}
}
}
}
Ok(pos)
}