-
Notifications
You must be signed in to change notification settings - Fork 0
/
d3.cpp
125 lines (118 loc) · 2.63 KB
/
d3.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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstring>
#include <vector>
using namespace std;
int filter(vector<string> input, vector<int> idx, int flag)
{
vector<int> cand = idx;
int iter = 0, res = 0;
while (cand.size() > 1)
{
vector<int> ones;
vector<int> zero;
for (int i = 0; i < cand.size(); i++)
{
if (input[cand[i]].substr(iter, 1) == "1")
{
ones.push_back(cand[i]);
}
else
{
zero.push_back(cand[i]);
}
}
if (flag == 1)
{
// get most frequent
if (ones.size() >= zero.size())
cand = ones;
else
cand = zero;
}
else
{
// get least frequent
if (ones.size() < zero.size())
cand = ones;
else
cand = zero;
}
iter++;
}
for (int i = 0; i < input[cand[0]].size(); i++)
{
if (input[cand[0]].substr(input[cand[0]].size() - 1 - i, 1) == "1")
{
res += 1 << i;
}
}
return res;
}
int main(int argc, char *argv[])
{
string filename = argv[1];
ifstream fin;
fin.open(filename.c_str());
if (!fin)
{
cout << "Error opening " << filename << endl;
exit(1);
}
string item;
vector<string> input;
while (getline(fin, item))
{
input.push_back(item);
}
int res = 0;
switch (stoi(argv[2]))
{
case 0:
{
int gamma = 0, epsilon = 0;
int width = input[0].size();
vector<int> freq(width, 0);
for (int i = 0; i < input.size(); i++)
{
for (int j = 0; j < width; j++)
{
if (input[i].substr(j, 1) == "1")
{
freq[j] += 1;
}
else
{
freq[j] -= 1;
}
}
}
for (int i = 0; i < width; i++)
{
if (freq[width - 1 - i] > 0)
{
gamma += 1 << i;
}
}
epsilon = (1 << width) - 1 - gamma;
res = gamma * epsilon;
break;
}
case 1:
{
int oxygen = 0, co2 = 0;
vector<int> idx(input.size());
for (int i = 0; i < input.size(); i++)
idx[i] = i;
oxygen = filter(input, idx, 1);
co2 = filter(input, idx, 0);
res = oxygen * co2;
break;
}
default:
break;
}
std::cout << res << std::endl;
return 0;
}