Day 8 part 1
This commit is contained in:
parent
33c926887d
commit
e82f8b3820
1
inputs/8.txt
Executable file
1
inputs/8.txt
Executable file
File diff suppressed because one or more lines are too long
1
inputs/8_test.txt
Normal file
1
inputs/8_test.txt
Normal file
@ -0,0 +1 @@
|
||||
2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2
|
60
src/day8.rs
Normal file
60
src/day8.rs
Normal file
@ -0,0 +1,60 @@
|
||||
use std::error::Error;
|
||||
use std::fs;
|
||||
use std::result;
|
||||
|
||||
type Result<T> = result::Result<T, Box<Error>>;
|
||||
|
||||
const INPUT: &str = "inputs/8.txt";
|
||||
|
||||
pub fn solve_part1() -> Result<u32> {
|
||||
let license = read_license(INPUT)?;
|
||||
Ok(sum_metadata(&license, 0, 0).0)
|
||||
}
|
||||
|
||||
fn read_license(filename: &str) -> Result<Vec<u32>> {
|
||||
let license = fs::read_to_string(filename)?;
|
||||
let license = license.trim();
|
||||
Ok(license
|
||||
.split(' ')
|
||||
.map(|num| num.parse().unwrap())
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn sum_metadata(license: &[u32], mut index: usize, mut sum_acc: u32) -> (u32, usize) {
|
||||
let num_children = license[index];
|
||||
let num_metadata = license[index + 1];
|
||||
index += 2;
|
||||
if num_children != 0 {
|
||||
for _ in 0..num_children {
|
||||
let (child_sum_acc, child_index) = sum_metadata(license, index, sum_acc);
|
||||
sum_acc = child_sum_acc;
|
||||
index = child_index;
|
||||
}
|
||||
}
|
||||
if num_metadata != 0 {
|
||||
let sum: u32 = license[index..index + num_metadata as usize].iter().sum();
|
||||
index += num_metadata as usize;
|
||||
sum_acc += sum;
|
||||
}
|
||||
(sum_acc, index)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const TEST_INPUT: &str = "inputs/8_test.txt";
|
||||
fn test_license() -> Vec<u32> {
|
||||
vec![2, 3, 0, 3, 10, 11, 12, 1, 1, 0, 1, 99, 2, 1, 1, 2]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_license_file() {
|
||||
assert_eq!(read_license(TEST_INPUT).unwrap(), test_license());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sums_license_metadata() {
|
||||
assert_eq!(sum_metadata(&test_license(), 0, 0).0, 138);
|
||||
}
|
||||
}
|
@ -10,6 +10,7 @@ mod day4;
|
||||
mod day5;
|
||||
mod day6;
|
||||
mod day7;
|
||||
mod day8;
|
||||
|
||||
fn main() {
|
||||
// println!("Day 1:");
|
||||
@ -30,7 +31,9 @@ fn main() {
|
||||
// println!("Day 6:");
|
||||
// println!("{}", day6::solve_part1().unwrap());
|
||||
// println!("{}", day6::solve_part2().unwrap());
|
||||
println!("Day 7:");
|
||||
// println!("Day 7:");
|
||||
// println!("{}", day7::solve_part1().unwrap());
|
||||
println!("{}", day7::solve_part2().unwrap());
|
||||
// println!("{}", day7::solve_part2().unwrap());
|
||||
println!("Day 8:");
|
||||
println!("{}", day8::solve_part1().unwrap());
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user