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!

31 Upvotes

515 comments sorted by

View all comments

1

u/CryZe92 Dec 05 '18 edited Dec 05 '18

Rust:

Part 1: 150ยตs

Part 2: 1.06ms

fn collapse(input: impl IntoIterator<Item = u8>, buf: &mut ArrayVec<[u8; 16384]>) {
    let mut top_byte = b'\0';
    for byte in input {
        if top_byte ^ 0x20 == byte {
            buf.pop();
            top_byte = buf.last().cloned().unwrap_or_default();
        } else {
            top_byte = byte;
            let _ = buf.try_push(byte);
        }
    }
}

pub fn part1(input: &str) -> usize {
    let mut buf = ArrayVec::new();
    collapse(input.bytes(), &mut buf);
    buf.len()
}

pub fn part2(input: &str) -> usize {
    (b'A'..b'Z' + 1)
        .into_par_iter()
        .map(|upper| {
            let mut buf = ArrayVec::new();
            let filtered = input.bytes().filter(|&b| b & !32 != upper);
            collapse(filtered, &mut buf);
            buf.len()
        })
        .min()
        .unwrap()
}

1

u/d3adbeef123 Dec 05 '18

Where does 16384 come from?

1

u/CryZe92 Dec 05 '18

This is a stack allocated array based buffer that we use here, and 16 Kilobytes fits the output. Unfortunately Rust has no const generics yet, so ArrayVec only supports certain hardcoded exponents of 2, so the next lower would be 8 Kilobytes, which wasn't enough. Considering allocating on the stack is just a subtraction / addition of the stack pointer, the amount doesn't affect the speed (but could potentially cause a stack overflow).

0

u/[deleted] Dec 05 '18

[deleted] โ€” view deleted comment

1

u/CryZe92 Dec 05 '18

I don't think arrayvec supports that though. What would work with arrayvec though is making the array size generic with something like A: Array<Item = u8>, but then I would've needed to specify the array size in part1 and part2 (unless I would want to lift it out even further).

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.