aboutsummaryrefslogtreecommitdiff
path: root/day12/day12.c
blob: 2147c134cb8ec6394e327d94ddca376f0ec7554c (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
#include <stdio.h>
#include <stdlib.h>

#define ungetchar(ch) ungetc(ch, stdin)

int getnumber(char* input, int* i) {
  int ch, num = 0, neg = 0;

  if(input[(*i)++] == '-') {
    ch = input[(*i)++];

    if(ch < '0' || ch > '9')
      return 0;
    else
      neg = 1;
  }
  (*i)--;

  while((ch = input[(*i)++]) >= '0' && ch <= '9')
    num = (num * 10) + (ch - 48);
  (*i)--;

  if(neg)
    return -num;
  else
    return num;
}

int sumnumbers(char* input) {
  int tot = 0, ch, i = 0;

  while((ch = input[i++]) != '\0') {
    if((ch >= '0' && ch <= '9') || ch == '-') {
      i--;
      tot += getnumber(input, &i);
    }
  }

  return tot;
}

int sumnonred(char* input) {
  return 0;
}

char* readtheinput() {
  char *theinput, ch;
  int i = 0, max = 1024;
    
  theinput = (char*) malloc(max * sizeof(char));

  while((ch = getchar()) != EOF) {
    theinput[i++] = ch;
    if(i == max) {
      max += 1024;
      theinput = (char*) realloc((void*) theinput, max * sizeof(char));
    }
  }

  theinput[i] = '\0';

  return theinput;
}

int main() {
  char* theinput;

  theinput = readtheinput();

  printf("Sum of all numbers: %d\n", sumnumbers(theinput));
  printf("Sum of all non-red numbers: %d\n", sumnonred(theinput));

  free(theinput);
  return 0;
}