Paul Waring

Freelance C Developer based in Manchester, UK

Advent of Code 2015 Day 1

Day 1: Not Quite Lisp

Part A

Input is a list of characters, with the following meanings:

Starting at the ground floor (zero), which floor does the input take you to?

This is relatively easy to solve, as we just need to read the input one character at a time and increment or decrement a counter based on the character. The following function will suffice:

#include <string.h>

int final_floor(const char *restrict input) {
    int current_floor = 0;
    int input_length = strlen(input);

    for (int i = 0; i < input_length; i++) {
        switch (input[i]) {
            case '(':
                current_floor++;
                break;
            case ')':
                current_floor--;
                break;
        }
    }
    
    return current_floor;
}

Part B

The meaning of the input is unchanged, but this time find the position which causes the first entry into the basement (floor -1).

This is also easy to solve, as we follow the same process of reading the input one character at a time, but instead we stop as soon as the current floor is -1.

#include <string.h>

int first_position_floor(const char *restrict input, int target_floor) {
    // Positions are 1-indexed
    int current_position = 0;
    int current_floor = 0;
    int input_length = strlen(input);
    bool target_floor_reached = false;

    for (int i = 0; i < input_length && !target_floor_reached; i++) {
        if (current_floor == target_floor) {
            target_floor_reached = true;
        } else {
            current_position++;

            switch (input[i]) {
                case '(':
                    current_floor++;
                    break;
                case ')':
                    current_floor--;
                    break;
            }
        }
    }

    return current_position;
}