blob: 29d334e2674f340af4be75d9aef7f31e902ab10b (
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
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if 1
#define PART_1
#else
#define PART_2
#endif
#if 0
#define FILE_PATH "example.txt"
#define NUMS 12
#define BITS 5
#else
#define FILE_PATH "input.txt"
#define NUMS 1000
#define BITS 12
#endif
int nums[NUMS] = {0};
void parse()
{
FILE *fp = fopen(FILE_PATH, "r");
if(!fp) {
fprintf(stderr, "ERROR: Could not open file %s\n", FILE_PATH);
exit(EXIT_FAILURE);
}
char line[32];
int index = 0;
while(fgets(line, sizeof(line), fp) != NULL)
{
for(int i = 0; i < BITS; i++)
nums[index] |= (line[i] - '0') << (BITS-1 - i);
index++;
}
fclose(fp);
}
ulong gen_gamma()
{
int most_common[BITS] = {0};
for(int i = 0; i < BITS; i++)
{
int ones = 0;
for(int j = 0; j < NUMS; j++)
if(nums[j] & (1 << i)) ones++;
if(ones > NUMS/2) most_common[i] = 1;
}
ulong gamma = 0;
for(int i = 0; i < BITS; i++)
gamma |= most_common[i] << i;
return gamma;
}
void print_nums()
{
for(int i = 0; i < NUMS; i++)
printf("%b\n", nums[i]);
}
void part_1()
{
ulong gamma = gen_gamma();
ulong epsilon = (~gamma & ~(~0 << BITS));
printf("Power consumption is %lu", gamma*epsilon);
}
void part_2()
{
exit(EXIT_FAILURE);
}
int main(void)
{
parse();
#ifdef PART_1
part_1();
#endif
#ifdef PART_2
part_2();
#endif
return 0;
}
|