Add c implementation for day1
This commit is contained in:
parent
006f94b97d
commit
f518db5cd5
47
day1/c/day1.c
Normal file
47
day1/c/day1.c
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
int calculate_fuel1(int mass)
|
||||||
|
{
|
||||||
|
return mass / 3 - 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
int calculate_fuel2(int mass)
|
||||||
|
{
|
||||||
|
int fuel = mass / 3 - 2;
|
||||||
|
if (fuel < 0)
|
||||||
|
return 0;
|
||||||
|
else
|
||||||
|
return fuel + calculate_fuel2(fuel);
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(void)
|
||||||
|
{
|
||||||
|
FILE *fp;
|
||||||
|
char *line = NULL;
|
||||||
|
size_t len = 0;
|
||||||
|
ssize_t read;
|
||||||
|
|
||||||
|
fp = fopen("../input", "r");
|
||||||
|
if (fp == NULL)
|
||||||
|
exit(EXIT_FAILURE);
|
||||||
|
|
||||||
|
int fuel1 = 0;
|
||||||
|
int fuel2 = 0;
|
||||||
|
int mass;
|
||||||
|
|
||||||
|
while ((read = getline(&line, &len, fp)) != -1) {
|
||||||
|
mass = atoi(line);
|
||||||
|
fuel1 += calculate_fuel1(mass);
|
||||||
|
fuel2 += calculate_fuel2(mass);
|
||||||
|
}
|
||||||
|
|
||||||
|
printf("Solution for Part One: %d\n", fuel1);
|
||||||
|
printf("Solution for Part Two: %d\n", fuel2);
|
||||||
|
|
||||||
|
fclose(fp);
|
||||||
|
if (line)
|
||||||
|
free(line);
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user