2017: Day 01
This commit is contained in:
62
2017/01/src/main.rs
Normal file
62
2017/01/src/main.rs
Normal file
@@ -0,0 +1,62 @@
|
||||
use std::env;
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
|
||||
|
||||
fn captcha(input: &str, step: usize) -> u32 {
|
||||
let digits = input
|
||||
.chars()
|
||||
.flat_map(|c| c.to_digit(10))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let len = digits.len();
|
||||
|
||||
digits
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|&(i, digit)| *digit == digits[(i + step) % len])
|
||||
.map(|(_, digit)| digit)
|
||||
.sum::<u32>()
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let file_name = env::args().nth(1).expect("path to input file");
|
||||
|
||||
let mut input = String::new();
|
||||
|
||||
fs::File::open(file_name)
|
||||
.and_then(|mut file| file.read_to_string(&mut input))
|
||||
.expect("faild to read file");
|
||||
|
||||
for line in input
|
||||
.lines()
|
||||
.map(|line| line.trim())
|
||||
.filter(|line| !line.is_empty())
|
||||
{
|
||||
println!("part-01: {}", captcha(line, 1));
|
||||
println!("part-02: {}", captcha(line, line.len() / 2));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn part_1() {
|
||||
assert_eq!(captcha("1122", 1), 3);
|
||||
assert_eq!(captcha("1111", 1), 4);
|
||||
assert_eq!(captcha("1234", 1), 0);
|
||||
assert_eq!(captcha("91212129", 1), 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part_2() {
|
||||
assert_eq!(captcha("1212", 2), 6);
|
||||
assert_eq!(captcha("1221", 2), 0);
|
||||
assert_eq!(captcha("123425", 3), 4);
|
||||
assert_eq!(captcha("123123", 3), 12);
|
||||
assert_eq!(captcha("12131415", 4), 4);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user