2
1
Fork 0

Day 3: Add C solution

This commit is contained in:
Mia Herkt 2021-12-03 21:29:10 +01:00
parent 78d929de2f
commit 5766390cb0
Signed by: mia
GPG key ID: 72E154B8622EC191
2 changed files with 97 additions and 0 deletions

32
03/solution_1.c Normal file
View file

@ -0,0 +1,32 @@
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fp = fopen("input.txt", "r");
char buf[16];
unsigned rlen = sizeof(buf) - 1;
unsigned bitcnt[2][sizeof(buf) - 1] = {0};
size_t gamma = 0, epsilon = 0;
while (fgets(buf, sizeof(buf), fp) != NULL) {
for (size_t i = 0; i < rlen; i++) {
if (buf[i] == '0')
bitcnt[0][i]++;
else if (buf[i] == '1')
bitcnt[1][i]++;
else {
rlen = i;
break;
}
}
}
for (size_t i = 0; i < rlen; i++) {
if (bitcnt[0][i] < bitcnt[1][i])
gamma ^= 1 << (rlen - i - 1);
else
epsilon ^= 1 << (rlen - i - 1);
}
printf("Answer: %lu\n", gamma * epsilon);
}

65
03/solution_2.c Normal file
View file

@ -0,0 +1,65 @@
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
long long flt(long long *data, size_t n, size_t rlen, char most) {
size_t nused = n;
char used[n];
memset(used, 1, n);
for (size_t b = 0; b < rlen; b++) {
size_t bitcnt[2][rlen];
memset(bitcnt[0], 0, rlen * sizeof(size_t));
memset(bitcnt[1], 0, rlen * sizeof(size_t));
for (size_t i = 0; i < n; i++) {
if (used[i]) {
if ((data[i] >> (rlen - b - 1)) & 1)
bitcnt[1][b]++;
else
bitcnt[0][b]++;
}
}
if (nused > 1) {
char cond;
if (bitcnt[0][b] == bitcnt[1][b])
cond = most;
else
cond = (bitcnt[0][b] > bitcnt[1][b]) ? !most : most;
for (size_t i = 0; i < n; i++) {
if (used[i]) {
if (((data[i] >> (rlen - b - 1)) & 1) != cond) {
used[i] = 0;
nused--;
}
}
}
}
if (nused == 1) {
for (size_t i = 0; i < n; i++) {
if (used[i])
return data[i];
}
}
}
return 0;
}
int main(void) {
FILE *fp = fopen("input.txt", "r");
char buf[16], *end;
size_t n = 0;
long long data[1000] = {0};
while (fgets(buf, sizeof(buf), fp) != NULL) {
data[n] = strtoll(buf, &end, 2);
n++;
}
printf("Answer: %lld\n",
flt(data, n, end - buf, 1) * flt(data, n, end - buf, 0));
}