Skip to content

Instantly share code, notes, and snippets.

@mbrenig
Last active December 2, 2019 17:47
Show Gist options
  • Save mbrenig/ca7fc51fa8c37cfee947efcdab64542b to your computer and use it in GitHub Desktop.
Save mbrenig/ca7fc51fa8c37cfee947efcdab64542b to your computer and use it in GitHub Desktop.
use std::fs::File;
use std::io::{prelude::*, BufReader};
use std::cmp::max;
fn fuel_for_mass(mass: i32) -> i32 {
let mut fuel = mass;
fuel = fuel / 3; // assume round down
fuel -= 2;
//println!("mass: {} requires: {}", mass, max(fuel, 0));
max(fuel, 0)
}
fn all_fuel_for_mass(number: i32) -> i32 {
let mut total = 0;
let fuel = fuel_for_mass(number);
total += fuel;
let mut fuel_for_fuel = fuel_for_mass(fuel);
while fuel_for_fuel > 0 {
total += fuel_for_fuel;
fuel_for_fuel = fuel_for_mass(fuel_for_fuel)
}
total
}
fn main() {
assert_eq!(all_fuel_for_mass(14), 2);
assert_eq!(all_fuel_for_mass(1969), 966);
assert_eq!(all_fuel_for_mass(100756), 50346);
let file = File::open("input.txt").expect("Failed to open input file.");
let reader = BufReader::new(file);
let mut total = 0;
for line in reader.lines() {
// line is a result at this point
let numberstring = line.expect("Failed to parse line");
let number: i32 = numberstring
.parse()
.unwrap_or_else(|e| panic!("Could not parse '{}': {}", numberstring, e));
let fuel_req = all_fuel_for_mass(number);
total += fuel_req;
println!("Module: {}\tfuel_req: {}\tTotoal: {}", number, fuel_req, total);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_all_fuel_for_mass() {
assert_eq!(all_fuel_for_mass(14), 2);
assert_eq!(all_fuel_for_mass(1969), 966);
assert_eq!(all_fuel_for_mass(100756), 50346);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment