advent-of-code/aoc2018/src/day01.rs

148 lines
2.1 KiB
Rust
Raw Normal View History

2019-11-14 17:57:25 +01:00
use std::collections::HashSet;
2019-12-01 22:22:12 +01:00
use aoc::Result;
2019-11-14 17:57:25 +01:00
2019-11-15 00:14:07 +01:00
const INPUT: &str = include_str!("../input/day01.txt");
2019-11-14 17:57:25 +01:00
2019-11-15 00:14:07 +01:00
pub fn run() -> Result<()> {
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() {
if freqs.contains(&freq) {
2019-11-14 19:16:49 +01:00
return Ok(freq);
2019-11-14 17:57:25 +01:00
} else {
freqs.insert(freq);
}
2019-11-14 19:32:36 +01:00
freq += line.parse::<i32>()?;
2019-11-14 17:57:25 +01:00
}
}
}
2019-11-14 19:32:36 +01:00
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn part1_provided1() {
let input = "+1
-2
+3
+1
";
assert_eq!(part1(input).unwrap(), 3);
}
#[test]
fn part1_provided2() {
let input = "+1
+1
+1
";
assert_eq!(part1(input).unwrap(), 3);
}
#[test]
fn part1_provided3() {
let input = "+1
+1
-2
";
assert_eq!(part1(input).unwrap(), 0);
}
#[test]
fn part1_provided4() {
let input = "-1
-2
-3
";
assert_eq!(part1(input).unwrap(), -6);
}
#[test]
fn part1_real() {
2019-11-15 00:14:07 +01:00
assert_eq!(part1(INPUT).unwrap(), 427);
2019-11-14 19:32:36 +01:00
}
#[test]
fn part2_provided1() {
let input = "+1
-2
+3
+1
";
assert_eq!(part2(input).unwrap(), 2);
}
#[test]
fn part2_provided2() {
let input = "+1
-1
";
assert_eq!(part2(input).unwrap(), 0);
}
#[test]
fn part2_provided3() {
let input = "+3
+3
+4
-2
-4
";
assert_eq!(part2(input).unwrap(), 10);
}
#[test]
fn part2_provided4() {
let input = "-6
+3
+8
+5
-6
";
assert_eq!(part2(input).unwrap(), 5);
}
#[test]
fn part2_provided5() {
let input = "+7
+7
-2
-7
-4
";
assert_eq!(part2(input).unwrap(), 14);
}
#[test]
fn part2_real() {
2019-11-15 00:14:07 +01:00
assert_eq!(part2(INPUT).unwrap(), 341);
2019-11-14 19:32:36 +01:00
}
}