139 lines
2.4 KiB
C
139 lines
2.4 KiB
C
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
#include <stdint.h>
|
|
|
|
#define INPUT "../inputs/input-day3"
|
|
|
|
#define BIT_CHECK(v, n) (v >> n) & 1U
|
|
#define BIT_SET(v, n) (v |= 1U << n)
|
|
|
|
void
|
|
print_bits(uint16_t v, int max)
|
|
{
|
|
for(int i = 0; i < max; ++i) {
|
|
printf("%d", BIT_CHECK(v, i));
|
|
}
|
|
printf("\n");
|
|
}
|
|
|
|
uint16_t
|
|
from_bits(char *bits)
|
|
{
|
|
uint16_t val = 0;
|
|
|
|
for(int i = 0; i < 12; ++i) {
|
|
if(bits[i] == '1') {
|
|
BIT_SET(val, i);
|
|
}
|
|
}
|
|
|
|
return val;
|
|
}
|
|
|
|
int
|
|
count_lines()
|
|
{
|
|
int total = 0;
|
|
static char buf[256];
|
|
FILE *f = fopen(INPUT, "r");
|
|
while(fgets(buf, 256, f))
|
|
total++;
|
|
fclose(f);
|
|
return total;
|
|
}
|
|
|
|
uint16_t*
|
|
load_all(int count)
|
|
{
|
|
uint16_t *i = calloc(sizeof(uint16_t), count);
|
|
|
|
int idx = 0;
|
|
static char buf[256];
|
|
FILE *f = fopen(INPUT, "r");
|
|
|
|
while(fgets(buf, 256, f)) {
|
|
i[idx] = from_bits(buf);
|
|
idx++;
|
|
}
|
|
|
|
fclose(f);
|
|
|
|
return i;
|
|
}
|
|
|
|
void
|
|
first()
|
|
{
|
|
int cnt = count_lines();
|
|
uint16_t *v = load_all(cnt);
|
|
|
|
uint16_t gamma = 0;
|
|
uint16_t epsilon = 0;
|
|
|
|
for(int z = 0; z < 12; ++z) {
|
|
int high = 0;
|
|
int low = 0;
|
|
for(int i = 0; i < cnt; ++i) {
|
|
int bit = BIT_CHECK(v[i], z);
|
|
if(bit) {
|
|
high++;
|
|
} else {
|
|
low++;
|
|
}
|
|
}
|
|
if(high > low) {
|
|
BIT_SET(gamma, (11-z));
|
|
} else {
|
|
BIT_SET(epsilon, (11-z));
|
|
}
|
|
}
|
|
|
|
printf("gamma: %d\nepsilon: %d\n", gamma, epsilon);
|
|
print_bits(gamma, 16);
|
|
print_bits(epsilon, 16);
|
|
printf("result: %d\n", gamma * epsilon);
|
|
free(v);
|
|
}
|
|
|
|
void
|
|
second()
|
|
{
|
|
int cnt = count_lines();
|
|
uint16_t *v = load_all(cnt);
|
|
|
|
uint16_t gamma = 0;
|
|
uint16_t epsilon = 0;
|
|
|
|
for(int z = 0; z < 12; ++z) {
|
|
int high = 0;
|
|
int low = 0;
|
|
for(int i = 0; i < cnt; ++i) {
|
|
int bit = BIT_CHECK(v[i], z);
|
|
if(bit) {
|
|
high++;
|
|
} else {
|
|
low++;
|
|
}
|
|
}
|
|
if(high > low) {
|
|
BIT_SET(gamma, (11-z));
|
|
} else {
|
|
BIT_SET(epsilon, (11-z));
|
|
}
|
|
}
|
|
|
|
printf("gamma: %d\nepsilon: %d\n", gamma, epsilon);
|
|
print_bits(gamma, 16);
|
|
print_bits(epsilon, 16);
|
|
printf("result: %d\n", gamma * epsilon);
|
|
free(v);
|
|
}
|
|
|
|
int
|
|
main()
|
|
{
|
|
first();
|
|
|
|
return 0;
|
|
} |