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

69 lines
1.2 KiB
Rust
Raw Normal View History

2019-11-14 18:19:23 +01:00
use std::collections::HashMap;
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)?);
2019-11-14 18:19:23 +01:00
Ok(())
}
2019-11-14 19:16:49 +01:00
fn part1(input: &str) -> Result<u32> {
2019-11-14 18:19:23 +01:00
let mut twice = 0;
let mut thrice = 0;
for line in input.lines() {
let mut seen: HashMap<char, u32> = HashMap::new();
for c in line.chars() {
*seen.entry(c).or_default() += 1;
}
if seen.values().any(|x| *x == 2) {
twice += 1;
}
if seen.values().any(|x| *x == 3) {
thrice += 1;
}
}
2019-11-14 19:16:49 +01:00
Ok(twice * thrice)
2019-11-14 18:19:23 +01:00
}
2019-11-14 19:32:36 +01:00
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn part1_provided() {
let input = "abcdef
bababc
abbcde
abcccd
aabcdd
abcdee
ababab
";
assert_eq!(part1(input).unwrap(), 12);
}
#[test]
fn part1_real() {
let input = include_str!("../input/input.txt");
assert_eq!(part1(input).unwrap(), 5750);
}
}