Skip to content

Commit

Permalink
find cycle
Browse files Browse the repository at this point in the history
  • Loading branch information
michaeladler committed Dec 15, 2023
1 parent 3a85d17 commit 5fd8d42
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions src/day14/solve.c
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,6 @@ void solve(const char *buf, size_t buf_size, Solution *result) {

i64 part1, part2 = 0;

int total_cycles = 1000000000;

XXH128_hash_t hashes[MAX_CYCLE_LEN];
int hashes_count = 0;
_cleanup_(ust_XXH128_hash_t_free) ust_XXH128_hash_t seen = ust_XXH128_hash_t_init(hash, equal);
Expand All @@ -148,9 +146,9 @@ void solve(const char *buf, size_t buf_size, Solution *result) {
int duplicates_count = 0;

// find cycle
for (int cycle = 1; cycle <= MAX_CYCLE_LEN; cycle++) {
for (int cycle = 0; cycle < MAX_CYCLE_LEN; cycle++) {
tilt_north(rows, cols);
if (cycle == 1) { part1 = compute_total_load(rows, cols); }
if (cycle == 0) { part1 = compute_total_load(rows, cols); }

tilt_west(rows, cols);
tilt_south(rows, cols);
Expand All @@ -161,17 +159,25 @@ void solve(const char *buf, size_t buf_size, Solution *result) {

ust_XXH128_hash_t_node *node = ust_XXH128_hash_t_find(&seen, value);
if (node != NULL) {
log_debug("cycle %d seen before", cycle);
duplicates[duplicates_count++] = value;
} else {
ust_XXH128_hash_t_insert(&seen, value);
}
}

for (int i = 0; i < duplicates_count; i++) {
// printf("duplicate %d: %lu%lu\n", i, duplicates[i].low64, duplicates[i].high64);
int cycle_start = 0;
while (!equal(&hashes[cycle_start], &duplicates[0])) { cycle_start++; }
int cycle_len = 1;
while (!equal(&hashes[cycle_start + cycle_len], &duplicates[0])) { cycle_len++; }
log_debug("cycle starts at %d and has length %d", cycle_start, cycle_len);

// sanity check
for (int i = 0; i < cycle_len; i++) {
assert(equal(&hashes[cycle_start + i], &hashes[cycle_start + cycle_len + i]));
}

int total_cycles = 1000000000;

// print_platform(rows, cols);

snprintf(result->part1, sizeof(result->part1), "%ld", part1);
Expand Down

0 comments on commit 5fd8d42

Please sign in to comment.