Skip to content

Instantly share code, notes, and snippets.

@rondreas
Created December 1, 2019 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rondreas/6578a0b1751fc4f133a4c753c58cf9e1 to your computer and use it in GitHub Desktop.
Save rondreas/6578a0b1751fc4f133a4c753c58cf9e1 to your computer and use it in GitHub Desktop.
Advent of Code 2019, Day 1
use std::env; // Get the standard library module for the process environment, so we can access arguments passed etc...
use std::fs; // Module for filesystem, so rust is aware of file objects
// The equation specified in the description for getting the fuel required to lift a given mass
fn required_fuel(mass: i32) -> i32 {
return mass / 3 - 2;
}
fn main(){
let args: Vec<String> = env::args().collect(); // Get the arguments as a string vector
let filename = &args[1]; // Where the first passed argument should be the path to the file with inputs,
// Attempt getting the contents from the file, on panic let user know we failed,
// first had an .except but couldn't pass this formatted string like I wanted.
let contents = fs::read_to_string(filename)
.unwrap_or_else(|_| panic!("Failed to read contents of {}", filename));
// Split the content into separate lines,
let lines = contents.split("\n");
// Solve the problem of the day
let mut fuel_for_modules = 0;
let mut total_fuel_req = 0; // So we're looking for the total sum of fuel required,
for line in lines { // For each line in lines parse
if line.is_empty(){
continue; // Skipping any empty lines, likely the last one in this case.
}
let module_mass = line.parse::<i32>().unwrap(); // Read the value as a 32-bit interger
let mut fuel_for_module = 0; // Sum of the required fuel for this `module`
let mut fuel = required_fuel(module_mass); // The fuel required for the `module`
fuel_for_modules += fuel; // Sum up the fuel needed to carry the modules to answer the first solution
while fuel > 0 {
fuel_for_module += fuel; // Add the fuel to the fuel needed to carry this module,
fuel = required_fuel(fuel); // Get the required fuel for the fuel we just added,
}
total_fuel_req += fuel_for_module; // Add the fuel to the sum total for all required fuel, for the second solution
}
println!("The solution to the first problem {}", fuel_for_modules);
println!("and for the second problem {}", total_fuel_req);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment