logo

adventofcode

Code used to solve https://adventofcode.com/, one branch per year git clone https://hacktivis.me/git/adventofcode.git

day1.c (937B)


  1. #include <assert.h> /* assert() */
  2. #include <fenv.h> /* fesetround(), FE_DOWNWARD */
  3. #include <math.h> /* lround() */
  4. #include <stdio.h> /* printf(), getline() */
  5. #include <stdlib.h> /* atol() */
  6. long int
  7. fuel_required(long int mass)
  8. {
  9. long int result;
  10. fesetround(FE_DOWNWARD);
  11. result = (lround(mass / 3) - 2);
  12. return result;
  13. }
  14. long int
  15. fuel_fuel(long int input)
  16. {
  17. long int result;
  18. result = fuel_required(input);
  19. if(result <= 0)
  20. return 0;
  21. else
  22. return result + fuel_fuel(result);
  23. }
  24. int
  25. main(void)
  26. {
  27. char *line_mass = NULL;
  28. size_t len = 0;
  29. long int modules_total = 0, grand_total = 0, module_fuel;
  30. while(getline(&line_mass, &len, stdin) != -1)
  31. {
  32. module_fuel = fuel_required(atol(line_mass));
  33. modules_total += module_fuel;
  34. grand_total += module_fuel + fuel_fuel(module_fuel);
  35. }
  36. printf("Modules fuel: %ld\n", modules_total);
  37. printf("Grand total: %ld\n", grand_total);
  38. return 0;
  39. }