summaryrefslogtreecommitdiff
path: root/8a.c
blob: 9c747b2d70f370dc55f2b05cdf83a857d658bfd0 (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

struct digit
{
    char sig[10];
    int digit;
    int unique;
};

static char *ReadLine(char *p, size_t size, FILE *fp)
{
    if ((p=fgets(p, size, fp)))
    {
        size_t l = strlen(p);

        while(l && p[l-1] == '\n')
        {
            p[--l] = 0;
        }
    }

    return p;
}

static int CompareLen(const void *a, const void *b)
{
    const char **pa = a;
    const char **pb = b;
    int l1;
    int l2;

    l1 = strlen(*pa);
    l2 = strlen(*pb);

    return l1 - l2;
}

static int CalcCodes(struct digit digit[10], char *signal[10])
{
    qsort(signal, 10, sizeof signal[0], CompareLen);
}

static int GetDigit(const struct digit *digit, const char *p)
{
    int check[10] = {0};
    int f;

    for(f = 0; f < 10; f++)
    {
        if (strlen(digit[f].sig) == strlen(p))
        {
            int n;
            
            check[f] = 1;

            if (!digit[f].unique)
            {
                for(n = 0; n < strlen(p); n++)
                {
                    if(!strchr(digit[f].sig, p[n]))
                    {
                        check[f] = 0;
                    }
                }
            }
        }
    }

    for(f = 0; f < 10; f++)
    {
        if(check[f])
        {
            return digit[f].digit;
        }
    }

    printf("No digit for %s\n", p);
    exit(1);
}

int main(void)
{
    char buff[0x8000];
    char *signal[10] = {0};
    char *digit[4] = {0};
    struct digit dig[10];
    int num = 0;
    int sum = 0;
    int f = 0;

    while(ReadLine(buff, sizeof buff, stdin))
    {
        char result[5] = "0000";

        for(f = 0; f < 10; f++)
        {
            signal[f] = strtok(f == 0 ? buff : NULL, " |");
        }

        CalcCodes(dig, signal);

        for(f = 0; f < 4; f++)
        {
            size_t len;

            digit[f] = strtok(NULL, " |");

            num = GetDigit(dig, digit[f]);
            result[f] = '0' + num;
        }

        sum += atoi(result);
    }

    printf("sum = %d\n", sum);

    return 0;
}