diff options
author | Vincent Douillet <vincent@vdouillet.fr> | 2021-12-03 14:09:39 +0100 |
---|---|---|
committer | Vincent Douillet <vincent@vdouillet.fr> | 2021-12-03 14:09:39 +0100 |
commit | 04e79fa276ae1c3620868d85941b2c7b7c11222a (patch) | |
tree | 573b20f62b00a468bc7101e59caeb76b51989ea6 | |
parent | c851f16d1df21d7579af72d842521b951261b092 (diff) |
day 3
-rw-r--r-- | .gitignore | 2 | ||||
-rw-r--r-- | 03.c | 55 | ||||
-rw-r--r-- | Makefile | 5 |
3 files changed, 61 insertions, 1 deletions
@@ -1,4 +1,6 @@ +?? ??? *.o input/ *.swp +answer.csv @@ -0,0 +1,55 @@ +#include <stdlib.h> +#include <stdio.h> +#include <err.h> +#include <string.h> +#include "input.h" + +#define INPUT "input/03.txt" +#define INPUT_SIZE 12 + +void part1(char** input, size_t lineCount) { + int oneCount[INPUT_SIZE]; + for(int k = 0; k < INPUT_SIZE; k++) { + oneCount[k] = 0; + } + + for(size_t i = 0; i < lineCount; i++) { + char* line = input[i]; + for(int j = 0; j < INPUT_SIZE; j++) { + if(line[j] == '1') + oneCount[j]++; + } + } + + // null terminated string + char binary[INPUT_SIZE + 1]; + for(int h = 0; h < INPUT_SIZE; h++) { + binary[h] = oneCount[h] > lineCount / 2.0f ? '1' : '0'; + } + binary[INPUT_SIZE] = '\0'; + char* endp = NULL; + unsigned long gamma = strtoul(binary, &endp, 2); + unsigned long epsilon = gamma ^ 0xFFF; + if(*endp != '\0') + err(1, "erreur de parsing du gammaat"); + + printf("%ld\n", gamma * epsilon); +} + +int main() { + // lecture du fichier d'entree + FILE* file=fopen(INPUT,"r"); + if(file == NULL) + err(1, "Le fichier %s n'existe pas\n", INPUT); + + size_t lineCount = count_lines(file); + char** input = malloc(lineCount * sizeof(char*)); + read_lines_as_string(file, input, lineCount); + // fermeture du fichier + fclose(file); + + part1(input, lineCount); + + free_strings(input, lineCount); + return 0; +} @@ -1,7 +1,7 @@ CC=cc CFLAGS=-std=c1x -W -Wall -g LDFLAGS= -EXEC=011 012 021 022 +EXEC=011 012 021 022 03 all: $(EXEC) @@ -17,6 +17,9 @@ all: $(EXEC) 022: input.o 022.o $(CC) -o $@ $> $(LDFLAGS) +03: input.o 03.o + $(CC) -o $@ $> $(LDFLAGS) + .c.o: $(CC) -o $@ -c $< $(CFLAGS) |