From 3144a5f5289c5003a75e9d60e306caa3176b524f Mon Sep 17 00:00:00 2001 From: Mia Herkt Date: Wed, 7 Dec 2022 22:51:26 +0100 Subject: [PATCH] =?UTF-8?q?07:=20C:=20Don=E2=80=99t=20needlessly=20store?= =?UTF-8?q?=20file=20entries?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 07/solution.c | 34 +++++++++++++--------------------- 1 file changed, 13 insertions(+), 21 deletions(-) diff --git a/07/solution.c b/07/solution.c index b44cde5..ad20f9e 100644 --- a/07/solution.c +++ b/07/solution.c @@ -14,7 +14,6 @@ uint32_t fnv1a_32(const char *buf, size_t len) typedef struct entry { uint32_t id; - int isdir; size_t size; size_t n_entries; size_t n_alloc; @@ -22,18 +21,17 @@ typedef struct entry { struct entry *parent; } entry; -entry *findent(entry *e, int isdir, const char *name) { +entry *findent(entry *e, const char *name) { uint32_t id = fnv1a_32(name, strlen(name)); for (size_t i = 0; i < e->n_entries; i++) { - if (e->entries[i]->isdir == isdir) - if (e->entries[i]->id == id) - return e->entries[i]; + if (e->entries[i]->id == id) + return e->entries[i]; } return NULL; } -entry *addent(entry *parent, int isdir, const char *name) { +entry *addent(entry *parent, const char *name) { if (parent->n_entries >= parent->n_alloc) { parent->n_alloc += 10; if (parent->n_entries) @@ -45,7 +43,6 @@ entry *addent(entry *parent, int isdir, const char *name) { entry *e = parent->entries[parent->n_entries - 1] = calloc(1, sizeof(entry)); e->id = fnv1a_32(name, strlen(name)); - e->isdir = isdir; e->parent = parent; return e; @@ -54,7 +51,6 @@ entry *addent(entry *parent, int isdir, const char *name) { int main(int argc, char **argv) { char l[64]; entry *root = calloc(1, sizeof(entry)); - root->isdir++; entry *current = root; size_t S = 0, G = 0, required = 0; @@ -67,16 +63,14 @@ int main(int argc, char **argv) { else if (l[5] == '.') current = current->parent; else - current = findent(current, 1, l + 5); + current = findent(current, l + 5); } } else if (l[0] == 'd') { - addent(current, 1, l + 4); + addent(current, l + 4); } else { - char *p; - size_t sz = strtoul(l, &p, 10); - entry *f = addent(current, 0, p + 1); - f->size = sz; - for (f = current; f->parent; f = f->parent) + size_t sz = strtoul(l, NULL, 10); + entry *f = current; + for (; f->parent; f = f->parent) f->size += sz; f->size += sz; } @@ -92,12 +86,10 @@ int main(int argc, char **argv) { current->n_entries--; current = (current->entries++)[0]; } else { - if (current->isdir) { - if (current->size < 100000) - S += current->size; - else if (current->size >= required && (current->size < G || !G)) - G = current->size; - } + if (current->size < 100000) + S += current->size; + else if (current->size >= required && (current->size < G || !G)) + G = current->size; current = current->parent; }