day 3 part 1
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
blackbeard420 2021-12-05 10:50:13 -05:00
parent 275a396afd
commit 020b576e1c
Signed by: blackbeard420
GPG Key ID: 88C719E09CDDA4A5
3 changed files with 106 additions and 3 deletions

101
day3.c Normal file
View File

@ -0,0 +1,101 @@
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <arpa/inet.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;
}
int
main()
{
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);
return 0;
}

View File

@ -1,5 +1,5 @@
DAYS = day1 day2
DAYS = day1 day2 day3
CFLAGS = -Wall -Werror

View File

@ -1,9 +1,11 @@
#!/bin/sh
DAYS="day1 day2"
DAYS="day1 day2 day3"
for x in $DAYS; do
echo "running" $x
./$x
echo "complete"
done
done
exit