~aperezdc/aoc2022

ceb3620f8ea1f8b2c8c69adccef5615089ef6194 — Adrian Perez de Castro 2 years ago 6c505d7
Day 02, second part
5 files changed, 92 insertions(+), 4 deletions(-)

M README.md
M day02/.gitignore
M day02/Makefile
R day02/{day02.c => day02a.c}
A day02/day02b.c
M README.md => README.md +1 -0
@@ 12,6 12,7 @@ Languages used
--------------

- [Lua](https://www.lua.org/) (version 5.4)
- [C11](https://en.wikipedia.org/wiki/C11)


Licensing

M day02/.gitignore => day02/.gitignore +1 -1
@@ 1,1 1,1 @@
day02
day02[ab]

M day02/Makefile => day02/Makefile +6 -3
@@ 1,6 1,9 @@
CFLAGS += -std=c11 -Os
CFLAGS += -std=c11 -Os -Wall

day02: day02.o
all: day02a day02b

day02a: day02a.o
day02b: day02b.o

clean:
	$(RM) day02 day02.o
	$(RM) day02a day02a.o day02b day02b.o

R day02/day02.c => day02/day02a.c +0 -0
A day02/day02b.c => day02/day02b.c +84 -0
@@ 0,0 1,84 @@
/*
 * day02.c
 * Copyright (C) 2022 Adrian Perez de Castro <aperez@igalia.com>
 *
 * Distributed under terms of the MIT license.
 */

#include <assert.h>
#include <stdbool.h>
#include <stdio.h>

enum Fig {
    Rock = 1,
    Paper = 2,
    Scissors = 3,
};

enum Outcome {
    Lose = 'X',
    Draw = 'Y',
    Win = 'Z',
};

static enum Fig
winner(enum Fig f)
{
    switch (f) {
        case Rock:
            return Paper;
        case Paper:
            return Scissors;
        case Scissors:
            return Rock;
    }

    assert(!"unreachable");
}

static enum Fig
loser(enum Fig f)
{
    switch (f) {
        case Rock:
            return Scissors;
        case Paper:
            return Rock;
        case Scissors:
            return Paper;
    }

    assert(!"unreachable");
}

int
main(int argc, char *argv[])
{
    char other;
    char outcome;

    unsigned score = 0;

    while (!feof(stdin) && scanf("%c %c\n", &other, &outcome) == 2) {
        assert(other >= 'A' && other <= 'C');
        assert(outcome >= 'X' && outcome <= 'Z');

        const enum Fig fother = other - 'A' + 1;

        switch ((enum Outcome) outcome) {
            case Lose:
                score += loser(fother) + 0;
                break;
            case Draw:
                score += fother + 3;
                break;
            case Win:
                score += winner(fother) + 6;
                break;
        }

    }
    printf("%u\n", score);

    return 0;
}