diff --git a/src/bin/part06.rs b/src/bin/part06.rs new file mode 100644 index 0000000..26d0705 --- /dev/null +++ b/src/bin/part06.rs @@ -0,0 +1,87 @@ +use std::time; + + +#[derive(Debug)] +struct Race { + time: u64, + distance: u64, +} + +impl Race { + fn get_boundaries(&self) -> (u32, u32) { + let sqrt = ((self.time * self.time - 4 * self.distance) as f64).sqrt() / 2.0; + let t1 = (self.time as f64 / 2.0) - sqrt + 0.0001; + let t2 = (self.time as f64 / 2.0) + sqrt - 0.0001; + (t1.ceil() as u32, t2.floor() as u32) + } + + fn get_num_of_solutions(&self) -> u32 { + let (t1, t2) = self.get_boundaries(); + t2 - t1 + 1 + } +} + +fn main() { + println!("PART 1"); + + let s1 = time::Instant::now(); + let races = load_input_part1(); + let d1 = s1.elapsed(); + println!("Load: {:?}", d1); + + let s2 = time::Instant::now(); + let num_solutions = races.iter().map(|r| r.get_num_of_solutions()).collect::>(); + let d2 = s2.elapsed(); + println!("Num-Solutions: {:?} in {:?}", num_solutions, d2); + + let s3 = time::Instant::now(); + let result: u32 = num_solutions.iter().map(|n| *n as u32).product(); + let d3 = s3.elapsed(); + println!("Result: {} in {:?}", result, d3); + + println!("PART 2"); + + let race = load_input_part2(); + let s4 = time::Instant::now(); + let num_solutions = race.get_num_of_solutions(); + let d4 = s4.elapsed(); + println!("Num-Solutions: {:?} in {:?}", num_solutions, d4); + + println!("Total: {:?}", d1 + d2 + d3 + d4); +} + +fn load_input_part1() -> Vec { + let mut races: Vec = Vec::new(); + + let data = std::fs::read_to_string("src/bin/part06.txt") + .expect("Could not read file"); + let mut lines = data.lines(); + + let times = lines.next().unwrap().split_whitespace().skip(1).map(|s| s.parse::().unwrap()).collect::>(); + let distances = lines.next().unwrap().split_whitespace().skip(1).map(|s| s.parse::().unwrap()).collect::>(); + + for (i, t) in times.iter().enumerate() { + races.push( + Race { + time: *t, + distance: distances[i] + } + ) + } + + races +} + +fn load_input_part2() -> Race { + let data = std::fs::read_to_string("src/bin/part06.txt") + .expect("Could not read file"); + let mut lines = data.lines(); + + let time = lines.next().unwrap().split_whitespace().skip(1).fold(String::new(), |acc, x| acc.to_owned() + x).parse::().unwrap(); + let distance = lines.next().unwrap().split_whitespace().skip(1).fold(String::new(), |acc, x| acc.to_owned() + x).parse::().unwrap(); + + Race { + time, + distance + } +} \ No newline at end of file diff --git a/src/bin/part06.sample b/src/bin/part06.sample new file mode 100644 index 0000000..b39f49d --- /dev/null +++ b/src/bin/part06.sample @@ -0,0 +1,2 @@ +Time: 7 15 30 +Distance: 9 40 200 \ No newline at end of file diff --git a/src/bin/part06.txt b/src/bin/part06.txt new file mode 100644 index 0000000..81e2b2e --- /dev/null +++ b/src/bin/part06.txt @@ -0,0 +1,2 @@ +Time: 61 70 90 66 +Distance: 643 1184 1362 1041 \ No newline at end of file