summaryrefslogtreecommitdiffstats
path: root/2021/day3/src
diff options
context:
space:
mode:
authorYigit Sever2021-12-10 19:54:01 +0300
committerYigit Sever2021-12-10 19:54:01 +0300
commit3c97ec63d921c7d2f132a834f9b739cc8d039c99 (patch)
tree492bbff2312042c68e1a2d2d95ed0bf599dfe545 /2021/day3/src
parentae3853b6e8ab02023ccd74baac6dc177b1ee879a (diff)
downloadaoc-3c97ec63d921c7d2f132a834f9b739cc8d039c99.tar.gz
aoc-3c97ec63d921c7d2f132a834f9b739cc8d039c99.tar.bz2
aoc-3c97ec63d921c7d2f132a834f9b739cc8d039c99.zip
2021, day3: done
Diffstat (limited to '2021/day3/src')
-rw-r--r--2021/day3/src/main.rs99
1 files changed, 99 insertions, 0 deletions
diff --git a/2021/day3/src/main.rs b/2021/day3/src/main.rs
new file mode 100644
index 0000000..2440a39
--- /dev/null
+++ b/2021/day3/src/main.rs
@@ -0,0 +1,99 @@
1use std::env;
2use std::fs::File;
3use std::io::{BufRead, BufReader};
4
5fn main() {
6 let args: Vec<String> = env::args().collect();
7
8 if args.len() != 2 {
9 eprintln!("Usage: {} filename", args[0]);
10 std::process::exit(1);
11 }
12
13 let filename = &args[1];
14
15 let file = File::open(filename).unwrap_or_else(|_| panic!("No such file: {}", filename));
16 let reader = BufReader::new(file);
17
18 let mut numbers: Vec<u32> = Vec::new();
19
20 for line in reader.lines() {
21 let line = line.unwrap();
22 numbers.push(isize::from_str_radix(&line, 2).unwrap().try_into().unwrap());
23 }
24
25 let mut co2_numbers: Vec<u32> = numbers.clone();
26 let mut oxygen: u32 = 0;
27 let mut co2: u32 = 0;
28
29 for bit in (0..12).rev() {
30 let keep;
31 let mut one_bits = 0;
32 let mut zero_bits = 0;
33 for num in &numbers {
34 one_bits += (num >> bit) & 1;
35 zero_bits += ((num >> bit) & 1) ^ 1;
36 }
37
38 println!("for bit: {}", bit);
39 println!("one_bits: {}", one_bits);
40 println!("zero_bits: {}", zero_bits);
41
42 if zero_bits > one_bits {
43 keep = 0;
44 } else if zero_bits < one_bits {
45 keep = 1;
46 } else {
47 keep = 1;
48 }
49
50 println!("keeping {}", keep);
51
52 numbers.retain(|num| ((num >> bit) & 1) == keep);
53
54 if numbers.len() == 1 {
55 oxygen = numbers.pop().unwrap();
56 break;
57 }
58
59 println!("{:?}", numbers);
60 }
61
62 println!("====co2 now====");
63
64 for bit in (0..12).rev() {
65 let keep;
66 let mut one_bits = 0;
67 let mut zero_bits = 0;
68 for num in &co2_numbers {
69 one_bits += (num >> bit) & 1;
70 zero_bits += ((num >> bit) & 1) ^ 1;
71 }
72
73 println!("for bit: {}", bit);
74 println!("one_bits: {}", one_bits);
75 println!("zero_bits: {}", zero_bits);
76
77 if zero_bits > one_bits {
78 keep = 1;
79 } else if zero_bits < one_bits {
80 keep = 0;
81 } else {
82 keep = 0;
83 }
84
85 println!("keeping {}", keep);
86
87 co2_numbers.retain(|num| (num >> bit) & 1 == keep);
88
89 if co2_numbers.len() == 1 {
90 co2 = co2_numbers.pop().unwrap();
91 break;
92 }
93
94 println!("{:?}", co2_numbers);
95 }
96
97 println!("oxygen: {}\nco2: {}", oxygen, co2);
98 println!("answer: {}", oxygen * co2);
99}