Added day 17 code for part 1 and 2

Signed-off-by: Louis Vallat <louis@louis-vallat.xyz>
This commit is contained in:
Louis Vallat 2021-12-24 23:17:06 +01:00
parent 356fba5587
commit 8ab440a765
No known key found for this signature in database
GPG Key ID: 0C87282F76E61283
4 changed files with 81 additions and 0 deletions

View File

@ -83,3 +83,8 @@ day-16:
stage: build stage: build
script: script:
- cd day16; cargo run --release ./input - cd day16; cargo run --release ./input
day-17:
stage: build
script:
- cd day17; cargo run --release ./input

8
day17/Cargo.toml Normal file
View File

@ -0,0 +1,8 @@
[package]
name = "day17"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

1
day17/input Normal file
View File

@ -0,0 +1 @@
target area: x=25..67, y=-260..-200

67
day17/src/main.rs Normal file
View File

@ -0,0 +1,67 @@
use std::{fs, env};
fn read_input(path: &str) -> String {
return fs::read_to_string(path).expect("Cannot read file.");
}
fn parse_input(s: &str) -> ((i32, i32), (i32, i32)) {
let v = s.trim_end_matches("\n")
.split_once("x=").unwrap()
.1.split_once(", y=").unwrap();
let s = v.0.split_once("..").unwrap();
let e = v.1.split_once("..").unwrap();
return ((s.0.parse().unwrap(), s.1.parse().unwrap()),
(e.0.parse().unwrap(), e.1.parse().unwrap()));
}
fn has_crossed(p: &(i32, i32), z: &((i32, i32), (i32, i32))) -> bool {
return p.0 > z.0.1 || p.1 < z.1.0;
}
fn is_in(p: &(i32, i32), z: &((i32, i32), (i32, i32))) -> bool {
return p.0 >= z.0.0 && p.0 <= z.0.1 && p.1 >= z.1.0 && p.1 <= z.1.1;
}
fn compute_trajectory(mut v: (i32, i32), z: &((i32, i32), (i32, i32)), t: &mut Vec<(i32, i32)>) {
let mut l = t.last().unwrap_or(&(0, 0)).to_owned();
while !(has_crossed(&l, z) || is_in(&l, z)) {
l.0 += v.0;
l.1 += v.1;
v.0 += if v.0 > 0 { -1 } else if v.0 < 0 { 1 } else { 0 };
v.1 -= 1;
t.push(l);
}
}
fn get_max_y(v: &Vec<(i32, i32)>) -> i32 {
return v.iter().fold(i32::MIN, |acc, e| if e.1 > acc { e.1 } else { acc });
}
fn get_optimized_trajectory(z: &((i32, i32), (i32, i32))) -> (i32, usize) {
let mut v = vec![];
for i in 0..700 {
for j in -300..700 {
let mut b = vec![];
compute_trajectory((i, j), z, &mut b);
if is_in(b.last().unwrap(), z) { v.push(b); }
}
}
let mut max = i32::MIN;
for i in v.clone() {
let m = get_max_y(&i);
if m > max { max = m; }
}
return (max, v.len());
}
fn main() {
let args: Vec<String> = env::args().collect();
for arg in args.iter().skip(1) {
let input = read_input(&arg);
let vec_in = parse_input(&input);
let a = get_optimized_trajectory(&vec_in);
println!("[{}]", &arg);
println!("\t[Part 1] => Answer is '{}'.", a.0);
println!("\t[Part 2] => Answer is '{}'.", a.1);
}
}