summaryrefslogtreecommitdiff
path: root/Advent-of-Code-2021/AOC-7/main.c
blob: 165c671e20394a77966609d6285d72c014d4f404 (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
121
122
123
124
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define CAP 3000

#if 0
#define PFILE "sample.txt"
#else
#define PFILE "input.txt"
#endif

int vals[CAP];
size_t vals_sz = 0;

void Parse()
{
  // Parse
  char ch;
  FILE *fp;
  fp = fopen(PFILE, "r");

  char int_buf[6];
  memset(int_buf, '\0', sizeof(int_buf));
  int n = 0;
  while((ch = fgetc(fp)) != EOF)
  {
    if(ch != ',')
    {
      int_buf[n] = ch;
      n += 1;
      continue;
    }

    vals[vals_sz] = atoi(int_buf);
    vals_sz += 1;
    memset(int_buf, '\0', sizeof(int_buf));
    n = 0;
  }

}

void Part1()
{
  Parse();
  size_t fuel_arr[CAP];
  size_t fuel = 0;

  for(int i = 0; i < CAP; i++)
  {
    int target = i;
    for(int j = 0; j < vals_sz; j++)
      fuel += abs(target - vals[j]);

    fuel_arr[i] = fuel;
    fuel = 0;
  }

  // Find the smallest in the fuel array
  for(size_t i = 0; i < CAP; i++)
  {
    size_t counter = 0;
    for(int j = 0; j < CAP; j++)
    {
      if(fuel_arr[i] <= fuel_arr[j])
        counter += 1;
    }

    if(counter == CAP)
    {
      printf("%d\n", fuel_arr[i]);
      break;
    }
  }
}

size_t CountFuel(int target)
{
  // somehow works idk
  size_t sum = 0;
  for(size_t i = 1; i <= target; i++)
    sum += i;
  return sum;
}

void Part2()
{
  Parse();
  size_t fuel_arr[CAP];
  size_t fuel = 0;

  for(int i = 0; i < CAP; i++)
    {
      size_t target = i;
      for(int j = 0; j < vals_sz; j++)
        fuel += CountFuel(abs(target - vals[j]));

      fuel_arr[i] = fuel;
      fuel = 0;
    }

  // Find the smallest in the fuel array
  for(size_t i = 0; i < CAP; i++)
    {
      size_t counter = 0;
      for(size_t j = 0; j < CAP; j++)
        {
          if(fuel_arr[i] <= fuel_arr[j])
            counter += 1;
        }

      if(counter == CAP)
        {
          printf("%d: %d\n", i, fuel_arr[i]);
          break;
        }
    }
}

int main()
{
  Part2();
  return 0;
}