1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//! # Binary Diagnostic
//!
//! Part 1 uses bit manipulation to build up the binary numbers directly one digit at a time.
//!
//! Part 2 clones the input `vec` then uses [`swap_remove`] to efficiently discard numbers that
//! don't meet the criteria without having to move all subsequent elements.
//!
//! [`swap_remove`]: Vec::swap_remove

pub struct Input<'a> {
    width: usize,
    numbers: Vec<&'a [u8]>,
}

pub fn parse(input: &str) -> Input<'_> {
    let numbers: Vec<_> = input.lines().map(str::as_bytes).collect();
    Input { width: numbers[0].len(), numbers }
}

pub fn part1(input: &Input<'_>) -> u32 {
    let mut gamma = 0;
    let mut epsilon = 0;

    for i in 0..input.width {
        let sum = sum(&input.numbers, i);
        if sum > input.numbers.len() - sum {
            gamma = (gamma << 1) | 1;
            epsilon <<= 1;
        } else {
            gamma <<= 1;
            epsilon = (epsilon << 1) | 1;
        }
    }

    gamma * epsilon
}

pub fn part2(input: &Input<'_>) -> u32 {
    let gamma = rating(input, |a, b| a >= b);
    let epsilon = rating(input, |a, b| a < b);
    gamma * epsilon
}

fn sum(numbers: &[&[u8]], i: usize) -> usize {
    let total: usize = numbers.iter().map(|b| b[i] as usize).sum();
    total - 48 * numbers.len()
}

fn fold(numbers: &[u8], width: usize) -> u32 {
    numbers.iter().take(width).fold(0, |acc, &n| (acc << 1) | (n & 1) as u32)
}

fn rating(input: &Input<'_>, cmp: impl Fn(usize, usize) -> bool) -> u32 {
    let mut numbers = input.numbers.clone();

    for i in 0..input.width {
        let sum = sum(&numbers, i);
        let keep = if cmp(sum, numbers.len() - sum) { b'1' } else { b'0' };
        filter(&mut numbers, i, keep);
        if numbers.len() == 1 {
            return fold(numbers[0], input.width);
        }
    }

    unreachable!()
}

fn filter(numbers: &mut Vec<&[u8]>, i: usize, keep: u8) {
    let mut j = 0;

    while j < numbers.len() {
        if numbers[j][i] == keep {
            j += 1;
        } else {
            numbers.swap_remove(j);
        }
    }
}