summaryrefslogtreecommitdiffstats
path: root/2021/day3/src/main.rs
blob: 2440a3978e188d8cad861a22668ce02e2e9290e8 (plain)
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
use std::env;
use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() {
    let args: Vec<String> = env::args().collect();

    if args.len() != 2 {
        eprintln!("Usage: {} filename", args[0]);
        std::process::exit(1);
    }

    let filename = &args[1];

    let file = File::open(filename).unwrap_or_else(|_| panic!("No such file: {}", filename));
    let reader = BufReader::new(file);

    let mut numbers: Vec<u32> = Vec::new();

    for line in reader.lines() {
        let line = line.unwrap();
        numbers.push(isize::from_str_radix(&line, 2).unwrap().try_into().unwrap());
    }

    let mut co2_numbers: Vec<u32> = numbers.clone();
    let mut oxygen: u32 = 0;
    let mut co2: u32 = 0;

    for bit in (0..12).rev() {
        let keep;
        let mut one_bits = 0;
        let mut zero_bits = 0;
        for num in &numbers {
            one_bits += (num >> bit) & 1;
            zero_bits += ((num >> bit) & 1) ^ 1;
        }

        println!("for bit: {}", bit);
        println!("one_bits: {}", one_bits);
        println!("zero_bits: {}", zero_bits);

        if zero_bits > one_bits {
            keep = 0;
        } else if zero_bits < one_bits {
            keep = 1;
        } else {
            keep = 1;
        }

        println!("keeping {}", keep);

        numbers.retain(|num| ((num >> bit) & 1) == keep);

        if numbers.len() == 1 {
            oxygen = numbers.pop().unwrap();
            break;
        }

        println!("{:?}", numbers);
    }

    println!("====co2 now====");

    for bit in (0..12).rev() {
        let keep;
        let mut one_bits = 0;
        let mut zero_bits = 0;
        for num in &co2_numbers {
            one_bits += (num >> bit) & 1;
            zero_bits += ((num >> bit) & 1) ^ 1;
        }

        println!("for bit: {}", bit);
        println!("one_bits: {}", one_bits);
        println!("zero_bits: {}", zero_bits);

        if zero_bits > one_bits {
            keep = 1;
        } else if zero_bits < one_bits {
            keep = 0;
        } else {
            keep = 0;
        }

        println!("keeping {}", keep);

        co2_numbers.retain(|num| (num >> bit) & 1 == keep);

        if co2_numbers.len() == 1 {
            co2 = co2_numbers.pop().unwrap();
            break;
        }

        println!("{:?}", co2_numbers);
    }

    println!("oxygen: {}\nco2: {}", oxygen, co2);
    println!("answer: {}", oxygen * co2);
}