2023-06: Implement part 2

This commit is contained in:
LordMathis 2023-12-06 22:38:42 +01:00
parent ef364a9ae0
commit dae33e4a4b
3 changed files with 57 additions and 9 deletions

View File

@ -1,5 +1,7 @@
mod part_one; //mod part_one;
mod part_two;
fn main() { fn main() {
part_one::part_one(); //part_one::part_one();
part_two::part_two();
} }

View File

@ -15,21 +15,21 @@ pub fn part_one() {
for i in 0..race_results[0].len() { for i in 0..race_results[0].len() {
margin *= process_race_result(race_results[0][i], race_results[1][i]); margin *= process_race_result(race_results[0][i], race_results[1][i]);
} }
println!("{:?}", margin); println!("{:?}", margin);
} }
} }
fn process_line(s: &str) -> Vec<u32> { fn process_line(s: &str) -> Vec<u32> {
let nums_str = s.split(':').collect::<Vec<&str>>()[1]
let nums_str = s.split(':').collect::<Vec<&str>>()[1].split_whitespace().collect::<Vec<&str>>(); .split_whitespace()
.collect::<Vec<&str>>();
let nums: Vec<u32> = nums_str.iter().map(|s| s.parse::<u32>().unwrap()).collect(); let nums: Vec<u32> = nums_str.iter().map(|s| s.parse::<u32>().unwrap()).collect();
return nums; return nums;
} }
fn process_race_result(time: u32, distance: u32) -> u32 { fn process_race_result(time: u32, distance: u32) -> u32 {
let mut win_count = 0; let mut win_count = 0;
for i in 0..time { for i in 0..time {
@ -41,11 +41,10 @@ fn process_race_result(time: u32, distance: u32) -> u32 {
return win_count; return win_count;
} }
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>> fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where where
P: AsRef<Path>, P: AsRef<Path>,
{ {
let file = File::open(filename)?; let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines()) Ok(io::BufReader::new(file).lines())
} }

View File

@ -0,0 +1,47 @@
use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
pub fn part_two() {
if let Ok(lines) = read_lines("./input.txt") {
let mut race_result: Vec<u64> = Vec::new();
for line in lines {
race_result.push(process_line(&line.unwrap()));
}
let win_count = process_race_result(race_result[0], race_result[1]);
println!("{:?}", win_count);
}
}
fn process_line(s: &str) -> u64 {
let nums_str = s.split(':').collect::<Vec<&str>>()[1]
.split_whitespace()
.collect::<Vec<&str>>()
.concat();
let num: u64 = nums_str.parse::<u64>().unwrap();
return num;
}
fn process_race_result(time: u64, distance: u64) -> u64 {
let mut win_count = 0;
for i in 0..time {
if i * (time - i) > distance {
win_count += 1;
}
}
return win_count;
}
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where
P: AsRef<Path>,
{
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}