Created
December 7, 2019 23:52
-
-
Save jcoglan/783d665d74d7d1643cdcabec1ffe2e09 to your computer and use it in GitHub Desktop.
This file contains 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 characters
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 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 characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment