Day 6 done

This commit is contained in:
Drew Galbraith 2023-12-06 10:59:02 -08:00
parent bd452e6fd7
commit 0d4261c666
3 changed files with 99 additions and 0 deletions

2
input/day06.txt Normal file
View File

@ -0,0 +1,2 @@
Time: 61 67 75 71
Distance: 430 1036 1307 1150

94
src/day6.rs Normal file
View File

@ -0,0 +1,94 @@
use std::io;
fn split_string(str: &String) -> Vec<u64> {
let start = str.find(':').expect("No ':' in string") + 1;
str[start..]
.trim()
.split(' ')
.filter(|str| str.len() > 0)
.map(|str| str.parse().expect("Could not parse u32"))
.collect()
}
fn get_big_int(str: &String) -> u64 {
let start = str.find(':').expect("No ':' in string") + 1;
str[start..]
.trim()
.split(' ')
.filter(|str| str.len() > 0)
.collect::<Vec<&str>>()
.join("")
.parse()
.expect("Could not parse")
}
fn count_options(time: u64, dist: u64) -> u64 {
let a: f64 = 1.0;
let b: f64 = -1.0 * (time as f64);
let c: f64 = dist as f64;
let root_part = ((b * b) - (4.0 * a * c)).sqrt();
let root1 = ((-1.0 * b) + root_part) / (2.0 * a);
let root2 = ((-1.0 * b) - root_part) / (2.0 * a);
let minroot = root1.min(root2);
let maxroot = root1.max(root2);
let mut minroot_int: i64 = minroot.ceil() as i64;
let mut maxroot_int: i64 = maxroot.floor() as i64;
if minroot_int < 0 {
println!("Negative root: {} <- {}", minroot_int, minroot);
return 0;
}
if maxroot_int < 0 {
println!("Negative root: {} <- {}", maxroot_int, maxroot);
return 0;
}
if minroot_int as f64 == minroot {
minroot_int += 1;
}
if maxroot_int as f64 == maxroot {
maxroot_int -= 1;
}
return (maxroot_int - minroot_int + 1) as u64;
}
pub fn get_winning_combos() -> u64 {
let mut buffer = String::new();
assert_ne!(io::stdin().read_line(&mut buffer).unwrap(), 0);
let times = split_string(&buffer);
buffer = String::new();
assert_ne!(io::stdin().read_line(&mut buffer).unwrap(), 0);
let dists = split_string(&buffer);
let mut product = 1;
if times.len() != dists.len() {
println!("Times and distances are a different length");
return 0;
}
for i in 0..times.len() {
product *= count_options(times[i], dists[i]);
}
product
}
pub fn get_single_winning_combo() -> u64 {
let mut buffer = String::new();
assert_ne!(io::stdin().read_line(&mut buffer).unwrap(), 0);
let time = get_big_int(&buffer);
buffer = String::new();
assert_ne!(io::stdin().read_line(&mut buffer).unwrap(), 0);
let dist = get_big_int(&buffer);
count_options(time, dist)
}

View File

@ -5,6 +5,7 @@ mod day2;
mod day3;
mod day4;
mod day5;
mod day6;
fn main() {
let args: Vec<String> = env::args().collect();
@ -23,6 +24,8 @@ fn main() {
"day4b" => println!("Sum: {}", day4::get_card_points().1),
"day5a" => println!("Min: {}", day5::get_lowest_location(false)),
"day5b" => println!("Min: {}", day5::get_lowest_location(true)),
"day6a" => println!("Product: {}", day6::get_winning_combos()),
"day6b" => println!("Product: {}", day6::get_single_winning_combo()),
_ => println!("Unrecognized day: {}", args[1]),
}
}