commit 81656fd60b37fbd975a98e7210662e2316eace1a
parent 38b5f7abe355b00d9062fffff80303021f39c056
Author: amin <dev@aminmesbah.com>
Date: Mon, 2 Dec 2019 04:20:51 +0000
Add solution for 2019 01-2
FossilOrigin-Name: edff82c7bb6b7f11a2ad0636e8f72378f6d3e7d1753ebaf2e15d839a058c7cdd
Diffstat:
M | day01_1.zig | | | 42 | ++++++++++++++++++++++++++++++++++-------- |
1 file changed, 34 insertions(+), 8 deletions(-)
diff --git a/day01_1.zig b/day01_1.zig
@@ -2,16 +2,20 @@ const std = @import("std");
const dbg = std.debug;
pub fn main() void {
- var total_fuel: u32 = 0;
- for (input) |mass, i| {
- var module_fuel = get_fuel(mass);
- total_fuel += module_fuel;
+ var fuel_for_module_mass: i32 = 0;
+ var fuel_for_total_mass: i32 = 0;
+ for (input) |mass| {
+ var module_mass_fuel = get_fuel(mass);
+ var total_fuel = get_total_module_fuel(mass);
+ fuel_for_module_mass += module_mass_fuel;
+ fuel_for_total_mass += total_fuel;
}
- dbg.warn("Total fuel: {}\n", total_fuel);
+ dbg.warn("01-1 Total fuel for the modules: {}\n", fuel_for_module_mass);
+ dbg.warn("01-2 Total fuel for the modules and fuel: {}\n", fuel_for_total_mass);
}
-fn get_fuel(mass: u32) u32 {
- return (mass / 3) - 2;
+fn get_fuel(mass: i32) i32 {
+ return @divFloor(mass, 3) - 2;
}
test "get fuel" {
@@ -21,7 +25,29 @@ test "get fuel" {
dbg.assert(get_fuel(100756) == 33583);
}
-const input = [_]u32{
+fn get_total_module_fuel(module_mass: i32) i32 {
+ const module_fuel_mass = get_fuel(module_mass);
+ var unfueled_fuel = module_fuel_mass;
+ var fuel_fuel_mass: i32 = 0;
+ while (unfueled_fuel > 0) {
+ // "fuel" is a really strange word
+ var fuel_for_fuel = get_fuel(unfueled_fuel);
+ if (fuel_for_fuel <= 0) {
+ break;
+ }
+ fuel_fuel_mass += fuel_for_fuel;
+ unfueled_fuel = fuel_for_fuel;
+ }
+ return module_fuel_mass + fuel_fuel_mass;
+}
+
+test "get total module fuel" {
+ dbg.assert(get_total_module_fuel(14) == 2);
+ dbg.assert(get_total_module_fuel(1969) == 966);
+ dbg.assert(get_total_module_fuel(100756) == 50346);
+}
+
+const input = [_]i32{
91617,
134652,
101448,