2019: day01: part 1

This commit is contained in:
Antoine Martin 2019-12-01 16:03:34 +01:00
parent f743d60f85
commit 22fcfdae4f
7 changed files with 193 additions and 0 deletions

4
Cargo.lock generated
View file

@ -4,3 +4,7 @@
name = "aoc2018"
version = "0.1.0"
[[package]]
name = "aoc2019"
version = "0.1.0"

View file

@ -1,4 +1,5 @@
[workspace]
members = [
"aoc2018",
"aoc2019",
]

9
aoc2019/Cargo.toml Normal file
View file

@ -0,0 +1,9 @@
[package]
name = "aoc2019"
version = "0.1.0"
authors = ["Antoine Martin <antoine97.martin@gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

100
aoc2019/input/day01.txt Normal file
View file

@ -0,0 +1,100 @@
102111
81442
104967
146349
97956
148336
55752
110518
136080
79361
101709
71796
72543
88058
87187
67778
75471
135632
101309
67060
87048
64775
52160
119184
55284
83289
94809
78017
117854
76469
94504
92372
133595
107269
57182
85578
83777
91167
86119
114263
60369
72562
69544
92699
135045
147230
83105
143488
56494
63019
112366
128119
58293
132542
93266
76032
111651
127490
107633
61260
120876
116254
101151
128722
111623
103470
53224
93922
87624
131864
82431
90465
148373
90119
123744
118713
143700
113581
140687
119516
149497
72281
108641
111605
148274
69326
116571
56540
87595
55068
120602
56557
125534
133162
51828
117883
94637
54577
135114
83866

42
aoc2019/src/day01.rs Normal file
View file

@ -0,0 +1,42 @@
use super::Result;
const INPUT: &str = include_str!("../input/day01.txt");
pub fn run() -> Result<()> {
println!("part 1: {}", part1(INPUT)?);
Ok(())
}
fn fuel_needed(module_weight: u64) -> u64 {
(module_weight / 3) - 2
}
fn part1(input: &str) -> Result<u64> {
input
.lines()
.map(|line| line.parse::<u64>())
.map(|w| match w {
Ok(w) => Ok(fuel_needed(w)),
Err(e) => Err(Box::from(e)),
})
.sum()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn part1_provided() {
assert_eq!(fuel_needed(12), 2);
assert_eq!(fuel_needed(14), 2);
assert_eq!(fuel_needed(1969), 654);
assert_eq!(fuel_needed(100756), 33583);
}
#[test]
fn part1_real() {
assert_eq!(part1(INPUT).unwrap(), 3268951);
}
}

8
aoc2019/src/lib.rs Normal file
View file

@ -0,0 +1,8 @@
pub mod day01;
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
#[macro_export]
macro_rules! err {
($($string:expr),+) => (Box::<dyn Error>::from(format!($($string),+)))
}

29
aoc2019/src/main.rs Normal file
View file

@ -0,0 +1,29 @@
use std::env;
use aoc2019::day01;
use aoc2019::Result;
fn main() -> Result<()> {
let days: &[fn() -> Result<()>] = &[day01::run];
let mut args = env::args();
args.next();
match args.next() {
Some(arg) => {
let day: usize = arg.parse().expect("Please provide a day number");
days[day - 1]().expect("error running day specified");
}
None => {
for (i, day) in days.iter().enumerate() {
let i = i + 1;
println!("day{}: ", i);
day().unwrap_or_else(|e| panic!("error running day {}: {}", i, e));
println!();
}
}
}
Ok(())
}