main.pony 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. use "files"
  2. use "format"
  3. use "itertools"
  4. primitive Fuel
  5. // calculate the amount of fuel needed
  6. fun calc(x: U64) : U64 => (x / 3) - 2
  7. // calculate the amount of fuel needed, naively recursively taking
  8. //in account the weight of the fuel
  9. fun calc_recursive(x: U64) : U64 =>
  10. let weight = calc(x)
  11. if weight > 6 then
  12. weight + calc_recursive(weight)
  13. else
  14. weight
  15. end
  16. actor Main
  17. new create(env: Env) =>
  18. // use a command-line flag to figure out which version of the fuel
  19. //calculation to use
  20. let part_one = env.args.contains("--part-one", {(l, r) => l == r})
  21. let part_two = env.args.contains("--part-two", {(l, r) => l == r})
  22. if part_one or part_two then
  23. calculate_fuel(env, part_one)
  24. else
  25. env.err.print("Usage: 01 [--part-one|--part-two]")
  26. env.exitcode(99)
  27. end
  28. fun calculate_fuel(env: Env, part_one: Bool) =>
  29. // since we're storing the input list externally, we'll need the
  30. //ability to read and also stat files, so build that capability
  31. let caps = recover val FileCaps.>set(FileRead).>set(FileStat) end
  32. try
  33. // try opening the file, whose name we've hard-coded
  34. with file = OpenFile(FilePath(env.root as AmbientAuth, "input.txt", caps)?) as File
  35. do
  36. // iterate through the lines of the file
  37. let sum = Iter[String](file.lines())
  38. // try to parse all the lines as a number
  39. .filter_map[U64]({(str) => try str.u64()? else None end})
  40. // calculate the amount of fuel required for each one
  41. .map[U64]({(x) => if part_one then Fuel.calc(x) else Fuel.calc_recursive(x) end })
  42. // and sum them up
  43. .fold[U64](0, {(sum, x) => sum + x})
  44. // print out the resulting number
  45. env.out.print(Format.int[U64](sum))
  46. end
  47. else
  48. // if something failed, then print an error message of some kind and exit
  49. env.err.print("Couldn't read expected file `input.txt'")
  50. env.exitcode(99)
  51. end