r/adventofcode • • Dec 05 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 5 Solutions -🎄-

--- Day 5: Alchemical Reduction ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 5

Transcript:

On the fifth day of AoC / My true love sent to me / Five golden ___


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked at 0:10:20!

30 Upvotes

515 comments sorted by

View all comments

Show parent comment

1

u/phira Dec 05 '18

Plain ol' C, I'd be interested in how it benchmarked against your rust version on the same machine if you find yourself with time.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

#define FSIZE 50000

int main() {
    char buffer[FSIZE];
    char unblocked[FSIZE];

    int f = open("five.txt", 0);
    int offset = 0;
    int length;
    int pass_length;
    int min_length = FSIZE;

    // Read file into input buffer
    read(f, &buffer, FSIZE);

    // First pass plain reaction to compress buffer
    length = 0;
    for (int i=0; i<FSIZE; i++) {
        // Perform any reaction or accumulate
        if (length > 0 && abs(buffer[length-1] - buffer[i]) == 32) {
            length--;
        } else {
            buffer[length] = buffer[i];  // We can reassign into the same buffer
            length++;
        }
    }
    printf("Part one: %d\n", length);

    // Second pass find minimum length
    for (int d='a'; d<='z'; d++) {
        pass_length = 0;

        for (int i=0; i<length; i++) {
            // Ignore blocker characters
            if (buffer[i] == d || buffer[i] == (d-32))
                continue;

            // Bail if it's too long to hit minimum. If the remainder of the buffer is perfectly structured
            // it can remove at most length-pass_length chars
            if (min_length < (pass_length - (length - pass_length)))
                break;

            // Perform any reaction or accumulate
            if (pass_length > 0 && abs(unblocked[pass_length-1] - buffer[i]) == 32) {
                pass_length--;
            } else {
                unblocked[pass_length] = buffer[i];
                pass_length++;
            }
        }
        if (pass_length < min_length)
            min_length = pass_length;
    }
    printf("Part two: %d\n", min_length);
}

2

u/CryZe92 Dec 05 '18

Nice, the short circuiting is actually a pretty cool idea. It seems to take 1.107ms, merging this idea with the parallelization should break the 1ms barrier.