-
Notifications
You must be signed in to change notification settings - Fork 0
/
day3.cpp
62 lines (51 loc) · 1.8 KB
/
day3.cpp
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
#include <iostream>
#include <numeric>
#include "AOC_Solver.h"
uint64_t aoc::day3::part_1(std::vector<std::string>& input) {
const size_t digits = input[0].length();
std::string gamma_rate{}, epsilon_rate{};
for (unsigned int i = 0; i < digits; ++i) {
int ones{ 0 };
for (auto& binary_val : input) {
ones += binary_val[i] == '1' ;
}
if (ones > input.size() / 2) {
gamma_rate += "1";
epsilon_rate += "0";
}
else {
gamma_rate += "0";
epsilon_rate += "1";
}
}
return std::stoll(gamma_rate, nullptr, 2) * std::stoll(epsilon_rate, nullptr, 2);
}
uint64_t aoc::day3::part_2(std::vector<std::string>& input)
{
const size_t digits = input[0].length();
char common_bit;
std::vector oxygen{ input };
auto end_it = oxygen.end();
for (unsigned int i = 0; i < digits && oxygen.size()>1; ++i){
size_t oxygen_size = end_it - oxygen.begin();
if (oxygen_size == 1)continue;
int ones = std::accumulate(oxygen.begin(), end_it, 0,
[&](int a, std::string& b) {return a + (b[i] == '1'); });
common_bit = (ones > (oxygen_size / 2) ? '1' : '0');
if (oxygen_size % 2 == 0 && oxygen_size / 2 == ones)common_bit = '1';
end_it = std::remove_if(oxygen.begin(), end_it,
[&](std::string& a) {return a[i] != common_bit; });
}
end_it = input.end();
for (unsigned int i = 0; i < digits && input.size()>1; ++i) {
size_t co2_size = end_it - input.begin();
if (co2_size == 1)continue;
int ones = std::accumulate(input.begin(), end_it, 0,
[&](int a, std::string& b) {return a + (b[i] == '1'); });
common_bit = (ones > (co2_size / 2) ? '1' : '0');
if (co2_size % 2 == 0 && co2_size / 2 == ones)common_bit = '1';
end_it = std::remove_if(input.begin(), end_it,
[&](std::string& a) {return a[i] == common_bit; });
}
return std::stoll(oxygen[0], nullptr, 2) * std::stoll(input[0], nullptr, 2);
}