advent-of-code/2018/aoc01/src/main.rs

46 lines
1,004 B
Rust
Raw Normal View History

2019-11-14 17:57:25 +01:00
use std::collections::HashSet;
use std::env;
use std::fs;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn main() -> Result<()> {
let mut args = env::args();
args.next();
let input = fs::read_to_string(
&args
.next()
.expect("Please provide the path to the input file"),
)?;
2019-11-14 19:16:49 +01:00
println!("part 1: {}", part1(&input)?);
println!("part 2: {}", part2(&input)?);
2019-11-14 17:57:25 +01:00
Ok(())
}
2019-11-14 19:16:49 +01:00
fn part1(input: &str) -> Result<i32> {
2019-11-14 17:57:25 +01:00
let freq = input
.lines()
.map(|line| line.parse::<i32>().unwrap())
.sum::<i32>();
2019-11-14 19:16:49 +01:00
Ok(freq)
2019-11-14 17:57:25 +01:00
}
2019-11-14 19:16:49 +01:00
fn part2(input: &str) -> Result<i32> {
2019-11-14 17:57:25 +01:00
let mut freqs = HashSet::new();
let mut freq = 0;
loop {
for line in input.lines() {
2019-11-14 19:16:49 +01:00
freq += line.parse::<i32>()?;
2019-11-14 17:57:25 +01:00
if freqs.contains(&freq) {
println!("{}", freq);
2019-11-14 19:16:49 +01:00
return Ok(freq);
2019-11-14 17:57:25 +01:00
} else {
freqs.insert(freq);
}
}
}
}