Created
December 7, 2019 23:52
-
-
Save jcoglan/783d665d74d7d1643cdcabec1ffe2e09 to your computer and use it in GitHub Desktop.
Revisions
-
jcoglan created this gist
Dec 7, 2019 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,18 @@ input_path = File.expand_path('../input.txt', __FILE__) masses = File.read(input_path).lines.map(&:to_i) def fuel(mass) (mass / 3.0).floor - 2 end p masses.reduce(0) { |s, m| s + fuel(m) } def required_fuel(init) Enumerator.produce(fuel(init)) { |mass| fuel(mass) } end fuels = masses.flat_map do |mass| required_fuel(mass).take_while { |f| f > 0 } end p fuels.reduce(0, :+) This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,28 @@ use std::fs; use std::iter; fn main() { let content = fs::read_to_string("input.txt").unwrap(); let masses: Vec<f64> = content.lines().flat_map(|line| line.parse()).collect(); let fuel: f64 = masses.iter().map(|mass| fuel(*mass)).sum(); println!("{}", fuel); let fuel: f64 = masses .iter() .flat_map(|mass| required_fuel(*mass).take_while(|f| *f > 0.0)) .sum(); println!("{}", fuel); } fn required_fuel(mut mass: f64) -> impl Iterator<Item = f64> { iter::from_fn(move || { mass = fuel(mass); Some(mass) }) } fn fuel(mass: f64) -> f64 { (mass / 3.0).floor() - 2.0 }