Day 2, 3, and 4.

This commit is contained in:
2017-12-04 10:46:19 +01:00
parent f8873234a0
commit d1d29bcd64
12 changed files with 892 additions and 0 deletions

89
2017/02/src/main.rs Normal file
View File

@@ -0,0 +1,89 @@
use std::io::{self, Read};
type Data = Vec<Vec<u32>>;
fn parse(input: &str) -> Data {
input
.lines()
.map(|line| {
line.split_whitespace()
.flat_map(|cell| cell.parse::<u32>())
.collect::<Vec<_>>()
})
.collect::<Vec<_>>()
}
fn checksum(data: &Data) -> u32 {
data.iter()
.map(|row| {
let max = row.iter().max().unwrap_or(&0);
let min = row.iter().min().unwrap_or(&0);
max - min
})
.sum()
}
fn divisible(data: &Data) -> u32 {
data.iter()
.map(|row| {
let mut iter = row.iter();
while let Some(a) = iter.next() {
for b in iter.clone() {
if a % b == 0 {
return a / b;
} else if b % a == 0 {
return b / a;
}
}
}
0
})
.sum()
}
fn main() {
let mut input = String::new();
io::stdin()
.read_to_string(&mut input)
.expect("failed to parse input");
let data = parse(&input);
println!("checksum={}", checksum(&data));
println!("divisible={}", divisible(&data));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_checksum() {
let input = "5 1 9 5\n\
7 5 3\n\
2 4 6 8";
let data = parse(input);
assert_eq!(checksum(&data), 18);
}
#[test]
fn test_divisible() {
let input = "5 9 2 8\n\
9 4 7 3\n\
3 8 6 5";
let data = parse(input);
assert_eq!(divisible(&data), 9);
}
}