advent2021

Advent of Code 2021 Solutions
git clone git://bsandro.tech/advent2021
Log | Files | Refs

commit 5cb3777952b8ebf00878668998d91b0db99535ae
parent 12cad2011c8345dc17e8f5da903c3169611f3d83
Author: bsandro <[email protected]>
Date:   Tue,  7 Dec 2021 15:16:18 +0200

Day 07, puzzle 2

Diffstat:
Mday07/Makefile | 4++--
Mday07/puzzle.c | 13++++++++++++-
2 files changed, 14 insertions(+), 3 deletions(-)

diff --git a/day07/Makefile b/day07/Makefile @@ -3,8 +3,8 @@ CC=cc SRC=$(wildcard *.c) DEPS:=$(wildcard *.h) OBJ:=$(SRC:.c=.o) - -CFLAGS=-O2 -std=c99 -Werror -Wall -Wextra -I. -I../common +CFLAGS=-O0 -g -std=c99 -Werror -Wall -Wextra -I. -I../common +LDFLAGS=-lc -lm all: $(NAME) diff --git a/day07/puzzle.c b/day07/puzzle.c @@ -8,6 +8,7 @@ #include <stdbool.h> #include <assert.h> #include <time.h> +#include <math.h> #include "util.h" @@ -42,6 +43,7 @@ void puzzle(const char *filename, size_t *result1, size_t *result2) { qs((int *)numbers.data, 0, numbers.count - 1); + // median average size_t index = numbers.count / 2; int *data = (int *)numbers.data; int mid = data[index]; @@ -49,7 +51,16 @@ void puzzle(const char *filename, size_t *result1, size_t *result2) { *result1 += abs(data[i] - mid); } - *result2 = 0; + // geometric average + double sum = 0; + for (size_t i = 0; i < numbers.count; ++i) { + sum += data[i]; + } + int avg = floor((sum + 1) / (double)numbers.count); + for (size_t i = 0; i < numbers.count; ++i) { + int dist = abs(data[i] - avg); + *result2 += dist * (1 + dist) / 2; + } // mutiny! ignoring feof/ferror. free(numbers.data);