summaryrefslogtreecommitdiff
path: root/2a.c
blob: 180d72aa884a73ab461f77da6bba4d5aa21427a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    char buff[80];
    int depth = 0;
    int aim = 0;
    int horiz = 0;

    while(fgets(buff, sizeof buff, stdin))
    {
        char *tok[2] = {0};

        tok[0] = strtok(buff," ");

        if (tok[0]) tok[1] = strtok(NULL, " ");

        if (tok[0] && tok[1])
        {
            int i = atoi(tok[1]);

            if(strcmp(tok[0], "forward") == 0)
            {
                horiz += i;

                depth += i * aim;
            }

            if(strcmp(tok[0], "down") == 0)
            {
                aim += i;
            }

            if(strcmp(tok[0], "up") == 0)
            {
                aim -= i;
            }
        }
        else
        {
            printf("Bad input");
            exit(1);
        }
    }

    printf("depth=%d\n", depth);
    printf("horiz=%d\n", horiz);
    printf("product=%d\n", depth*horiz);

    return 0;
}