summaryrefslogtreecommitdiff
path: root/7.c
blob: 88da7f1dac4ec8d66312911ba3a30e163070ae57 (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
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

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 Distance(int from, int to)
{
    return abs(from - to);
}

int main(void)
{
    char buff[0x8000];
    int *num = NULL;
    int num_count = 0;
    char *p = NULL;
    int min = 2147483647;
    int max = 0;
    int f = 0;
    int n = 0;
    int lowest = 2147483647;

    ReadLine(buff, sizeof buff, stdin);

    p = strtok(buff, ",");

    while(p)
    {
        num = realloc(num, (num_count + 1) * sizeof *num);
        f = atoi(p);

        if (f > max)
        {
            max = f;
        }

        if (f < min)
        {
            min = f;
        }

        num[num_count++] = f;
        p = strtok(NULL, ",");
    }

    for(f = min; f <= max; f++)
    {
        int result = 0;

        for(n = 0; n < num_count; n++)
        {
            result += Distance(f, num[n]);
        }

        if (result < lowest)
        {
            lowest = result;
        }
    }

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

    return 0;
}