Day 4 complete part 1 and 2
This commit is contained in:
parent
89f79dab93
commit
d2198c8046
2 changed files with 67 additions and 0 deletions
64
src/day4.rs
Normal file
64
src/day4.rs
Normal file
|
@ -0,0 +1,64 @@
|
|||
use std::io;
|
||||
|
||||
fn part1(x: &u32) -> bool {
|
||||
let matching = x
|
||||
.to_string()
|
||||
.chars()
|
||||
.map(|c| c.to_digit(10).unwrap())
|
||||
.fold((true, false, 0), |acc, next| {
|
||||
(acc.0 && next >= acc.2, acc.1 || next == acc.2, next)
|
||||
});
|
||||
|
||||
matching.0 && matching.1
|
||||
}
|
||||
|
||||
fn part2(x: &u32) -> bool {
|
||||
let matching = x.to_string().chars().map(|c| c.to_digit(10).unwrap()).fold(
|
||||
(true, false, 0, 0),
|
||||
|acc, next| {
|
||||
if next == acc.3 && acc.2 >= 2 {
|
||||
(acc.0 && next >= acc.3, acc.1, acc.2 + 1, next)
|
||||
} else if next != acc.3 && acc.2 == 2 {
|
||||
(acc.0 && next >= acc.3, true, 1, next)
|
||||
} else if next == acc.3 && acc.2 < 2 {
|
||||
(acc.0 && next >= acc.3, acc.1, acc.2 + 1, next)
|
||||
} else {
|
||||
(acc.0 && next >= acc.3, acc.1, 1, next)
|
||||
}
|
||||
},
|
||||
);
|
||||
matching.0 && (matching.1 || matching.2 == 2)
|
||||
}
|
||||
|
||||
pub fn main() -> io::Result<()> {
|
||||
let input = "123257-647015";
|
||||
|
||||
let range: Vec<u32> = input
|
||||
.split("-")
|
||||
.map(|x| x.parse::<u32>().unwrap())
|
||||
.take(2)
|
||||
.collect();
|
||||
|
||||
println!("part1 = {}", (range[0]..range[1]).filter(part1).count());
|
||||
println!("part2 = {}", (range[0]..range[1]).filter(part2).count());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_part1() {
|
||||
assert!(part1(&111111));
|
||||
assert!(!part1(&223450));
|
||||
assert!(!part1(&123789));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_part2() {
|
||||
assert!(!part2(&111111));
|
||||
assert!(!part2(&223450));
|
||||
assert!(!part2(&123789));
|
||||
assert!(part2(&112233));
|
||||
assert!(part2(&223334));
|
||||
assert!(!part2(&123444));
|
||||
assert!(part2(&111122));
|
||||
}
|
|
@ -1,6 +1,7 @@
|
|||
mod day1;
|
||||
mod day2;
|
||||
mod day3;
|
||||
mod day4;
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{self, BufRead, BufReader};
|
||||
|
@ -18,5 +19,7 @@ fn main() -> io::Result<()> {
|
|||
|
||||
day3::main()?;
|
||||
|
||||
day4::main()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue