Files
adventofcode-2019/day04/Day04.rs

64 lines
1.3 KiB
Rust
Raw Normal View History

fn main() {
part1(246515, 739105);
part2(246515, 739105);
}
fn digit_n(digit: u32, n: usize) -> usize {
let place = 10usize.pow(5 - digit);
(n / place) % 10
}
fn is_increasing(n: usize) -> bool {
for digit in 0 .. 5 {
let this = digit_n(digit, n);
let next = digit_n(digit + 1, n);
if next < this {
return false;
}
}
true
}
fn has_double(n: usize) -> bool {
for digit in 0 .. 5 {
let this = digit_n(digit, n);
let next = digit_n(digit + 1, n);
if next == this {
return true;
}
}
false
}
fn has_strict_double(n: usize) -> bool {
let mut doubles: [usize; 10] = Default::default();
for digit in 0 .. 5 {
let this = digit_n(digit, n);
let next = digit_n(digit + 1, n);
if next == this {
doubles[this] += 1;
}
}
doubles.contains(&1)
}
fn part1(lower: usize, upper: usize) {
let mut count = 0;
for n in lower ..= upper {
if is_increasing(n) && has_double(n) {
count += 1;
}
}
println!("Part 1: {}", count);
}
fn part2(lower: usize, upper: usize) {
let mut count = 0;
for n in lower ..= upper {
if is_increasing(n) && has_strict_double(n) {
count += 1;
}
}
println!("Part 2: {}", count);
}