Sfoglia il codice sorgente

day 17 with fucking rust

metya 4 anni fa
parent
commit
ac18232684

+ 17 - 0
day17_trick_shot/Cargo.toml

@@ -0,0 +1,17 @@
+[package]
+name = "day17_trick_shot"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+regex = "1.5"
+
+
+[dev-dependencies]
+criterion = "0.3"
+
+[[bench]]
+name = "my_bench"
+harness = false

+ 177 - 0
day17_trick_shot/README.md

@@ -0,0 +1,177 @@
+--- Day 17: Trick Shot ---
+--------------------------
+
+You finally decode the Elves' message. `HI`, the message says. You continue searching for the sleigh keys.
+
+
+Ahead of you is what appears to be a large [ocean trench](https://en.wikipedia.org/wiki/Oceanic_trench). Could the keys have fallen into it? You'd better send a probe to investigate.
+
+
+The probe launcher on your submarine can fire the probe with any [integer](https://en.wikipedia.org/wiki/Integer) velocity in the `x` (forward) and `y` (upward, or downward if negative) directions. For example, an initial `x,y` velocity like `0,10` would fire the probe straight up, while an initial velocity like `10,-1` would fire the probe forward at a slight downward angle.
+
+
+The probe's `x,y` position starts at `0,0`. Then, it will follow some trajectory by moving in *steps*. On each step, these changes occur in the following order:
+
+
+* The probe's `x` position increases by its `x` velocity.
+* The probe's `y` position increases by its `y` velocity.
+* Due to drag, the probe's `x` velocity changes by `1` toward the value `0`; that is, it decreases by `1` if it is greater than `0`, increases by `1` if it is less than `0`, or does not change if it is already `0`.
+* Due to gravity, the probe's `y` velocity decreases by `1`.
+
+
+For the probe to successfully make it into the trench, the probe must be on some trajectory that causes it to be within a *target area* after any step. The submarine computer has already calculated this target area (your puzzle input). For example:
+
+
+
+```
+target area: x=20..30, y=-10..-5
+```
+
+This target area means that you need to find initial `x,y` velocity values such that after any step, the probe's `x` position is at least `20` and at most `30`, *and* the probe's `y` position is at least `-10` and at most `-5`.
+
+
+Given this target area, one initial velocity that causes the probe to be within the target area after any step is `7,2`:
+
+
+
+```
+.............#....#............
+.......#..............#........
+...............................
+S........................#.....
+...............................
+...............................
+...........................#...
+...............................
+....................TTTTTTTTTTT
+....................TTTTTTTTTTT
+....................TTTTTTTT#TT
+....................TTTTTTTTTTT
+....................TTTTTTTTTTT
+....................TTTTTTTTTTT
+
+```
+
+In this diagram, `S` is the probe's initial position, `0,0`. The `x` coordinate increases to the right, and the `y` coordinate increases upward. In the bottom right, positions that are within the target area are shown as `T`. After each step (until the target area is reached), the position of the probe is marked with `#`. (The bottom-right `#` is both a position the probe reaches and a position in the target area.)
+
+
+Another initial velocity that causes the probe to be within the target area after any step is `6,3`:
+
+
+
+```
+...............#..#............
+...........#........#..........
+...............................
+......#..............#.........
+...............................
+...............................
+S....................#.........
+...............................
+...............................
+...............................
+.....................#.........
+....................TTTTTTTTTTT
+....................TTTTTTTTTTT
+....................TTTTTTTTTTT
+....................TTTTTTTTTTT
+....................T#TTTTTTTTT
+....................TTTTTTTTTTT
+
+```
+
+Another one is `9,0`:
+
+
+
+```
+S........#.....................
+.................#.............
+...............................
+........................#......
+...............................
+....................TTTTTTTTTTT
+....................TTTTTTTTTT#
+....................TTTTTTTTTTT
+....................TTTTTTTTTTT
+....................TTTTTTTTTTT
+....................TTTTTTTTTTT
+
+```
+
+One initial velocity that *doesn't* cause the probe to be within the target area after any step is `17,-4`:
+
+
+
+```
+S..............................................................
+...............................................................
+...............................................................
+...............................................................
+.................#.............................................
+....................TTTTTTTTTTT................................
+....................TTTTTTTTTTT................................
+....................TTTTTTTTTTT................................
+....................TTTTTTTTTTT................................
+....................TTTTTTTTTTT..#.............................
+....................TTTTTTTTTTT................................
+...............................................................
+...............................................................
+...............................................................
+...............................................................
+................................................#..............
+...............................................................
+...............................................................
+...............................................................
+...............................................................
+...............................................................
+...............................................................
+..............................................................#
+
+```
+
+The probe appears to pass through the target area, but is never within it after any step. Instead, it continues down and to the right - only the first few steps are shown.
+
+
+If you're going to fire a highly scientific probe out of a super cool probe launcher, you might as well do it with *style*. How high can you make the probe go while still reaching the target area?
+
+
+In the above example, using an initial velocity of `6,9` is the best you can do, causing the probe to reach a maximum `y` position of `*45*`. (Any higher initial `y` velocity causes the probe to overshoot the target area entirely.)
+
+
+Find the initial velocity that causes the probe to reach the highest `y` position and still eventually be within the target area after any step. *What is the highest `y` position it reaches on this trajectory?*
+
+
+--- Part Two ---
+----------------
+
+Maybe a fancy trick shot isn't the best idea; after all, you only have one probe, so you had better not miss.
+
+
+To get the best idea of what your options are for launching the probe, you need to find *every initial velocity* that causes the probe to eventually be within the target area after any step.
+
+
+In the above example, there are `*112*` different initial velocity values that meet these criteria:
+
+
+
+```
+23,-10  25,-9   27,-5   29,-6   22,-6   21,-7   9,0     27,-7   24,-5
+25,-7   26,-6   25,-5   6,8     11,-2   20,-5   29,-10  6,3     28,-7
+8,0     30,-6   29,-8   20,-10  6,7     6,4     6,1     14,-4   21,-6
+26,-10  7,-1    7,7     8,-1    21,-9   6,2     20,-7   30,-10  14,-3
+20,-8   13,-2   7,3     28,-8   29,-9   15,-3   22,-5   26,-8   25,-8
+25,-6   15,-4   9,-2    15,-2   12,-2   28,-9   12,-3   24,-6   23,-7
+25,-10  7,8     11,-3   26,-7   7,1     23,-9   6,0     22,-10  27,-6
+8,1     22,-8   13,-4   7,6     28,-6   11,-4   12,-4   26,-9   7,4
+24,-10  23,-8   30,-8   7,0     9,-1    10,-1   26,-5   22,-9   6,5
+7,5     23,-6   28,-10  10,-2   11,-1   20,-9   14,-2   29,-7   13,-3
+23,-5   24,-8   27,-9   30,-7   28,-5   21,-10  7,9     6,6     21,-5
+27,-10  7,2     30,-9   21,-8   22,-7   24,-9   20,-6   6,9     29,-5
+8,-2    27,-8   30,-5   24,-7
+
+```
+
+*How many distinct initial velocity values cause the probe to be within the target area after any step?*
+
+

+ 10 - 0
day17_trick_shot/benches/my_bench.rs

@@ -0,0 +1,10 @@
+extern crate day17_trick_shot;
+use day17_trick_shot as day17;
+use criterion::{criterion_group, criterion_main, Criterion};
+
+fn ben(c: &mut Criterion) {
+    c.bench_function("day17", |b| b.iter(|| day17::main()));
+}
+
+criterion_group!(benches, ben);
+criterion_main!(benches);

+ 1 - 0
day17_trick_shot/example.txt

@@ -0,0 +1 @@
+target area: x=20..30, y=-10..-5

+ 1 - 0
day17_trick_shot/input.txt

@@ -0,0 +1 @@
+target area: x=169..206, y=-108..-68

+ 55 - 0
day17_trick_shot/main.py

@@ -0,0 +1,55 @@
+from doctest import Example
+import os, sys, re
+task_dir = os.path.dirname(__file__)
+sys.path.append(f'{task_dir}/..')
+from get_tasks import get_input, generate_readme, check_example
+
+def hit(position, target):
+    x, y = position
+    x1, x2, y1, y2 = target
+    return True if x <= x2 and x >= x1 and y >= y1 and y <= y2 else False
+
+def launch_prob(target):
+    succes = {}
+    succes_init_velocity = []
+    for i in range(1, target[1]+1):
+        for j in range(target[2], -target[2]):
+            init_velocity = i, j
+            hor, ver = i, j
+            hy = 0
+            x, y  = 0, 0
+            while not (apple := hit((x, y), target)):
+                py = y
+                x += hor; y += ver
+                if py > y and hy == 0: hy = py
+                if hor < 0: hor += 1
+                elif hor > 0: hor -= 1
+                else: pass
+                ver -= 1
+                if (x > target[1]) or (y < target[2]): break
+            if apple: 
+                succes[hy] = init_velocity
+                succes_init_velocity.append(init_velocity)
+    return succes, succes_init_velocity
+
+def part1(input: list[str]):
+    target = [int(c) for c in re.findall('-?\d+', input[0])]
+    hy, _ = launch_prob(target)
+    print("The answer of part1 is:", max(hy))
+    
+def part2(input: list[str]):
+    target = [int(c) for c in re.findall('-?\d+', input[0])]
+    _, v = launch_prob(target)
+    print("The answer of part1 is:", len(v))
+    
+    
+if __name__ == "__main__":
+    input, example = get_input(task_dir, 17)
+    
+    check_example(example, part1)
+    check_example(example, part2)
+    
+    part1(input)
+    part2(input)
+    
+    generate_readme(task_dir, 17)

+ 52 - 0
day17_trick_shot/src/lib.rs

@@ -0,0 +1,52 @@
+#![allow(dead_code)]
+#![allow(unused_variables)]
+use regex::Regex;
+
+#[inline]
+pub fn main() {
+    let reg = Regex::new(r"-?\d+").unwrap();
+    let target: Vec<i32> = reg
+        .captures_iter(&include_str!("../input.txt"))
+        .map(|x| x.get(0).unwrap().as_str().parse().unwrap())
+        .collect();
+    let (a, b) = launch_prob(target);
+}
+
+fn launch_prob(target: Vec<i32>) -> (i32, Vec<i32>) {
+    let [x1, x2, y1, y2] = <[i32; 4]>::try_from(target).ok().unwrap();
+    let mut acc = 0;
+    let mut maxy = Vec::new();
+    for i in 1..x2 + 1 {
+        for j in y1..-y1 {
+            let mut hor = i;
+            let mut ver = j;
+            let mut hy = 0;
+            let mut x = 0;
+            let mut y = 0;
+            while !(x <= x2 && x >= x1 && y >= y1 && y <= y2) {
+                let py = y;
+                x += hor;
+                y += ver;
+                if py > y && hy == 0 {
+                    hy = py;
+                };
+                ver -= 1;
+                if hor < 0 {
+                    hor += 1;
+                } else if hor > 0 {
+                    hor -= 1;
+                } else {
+                    hor = 0;
+                }
+                if x >= x2 || y <= y1 {
+                    break;
+                }
+            }
+            if x <= x2 && x >= x1 && y >= y1 && y <= y2 {
+                acc += 1;
+                maxy.push(hy);
+            }
+        }
+    }
+    return (acc, maxy);
+}

+ 53 - 0
day17_trick_shot/src/main.rs

@@ -0,0 +1,53 @@
+#![allow(dead_code)]
+#![allow(unused_variables)]
+use regex::Regex;
+
+fn main() {
+    let reg = Regex::new(r"-?\d+").unwrap();
+    let target: Vec<i32> = reg
+        .captures_iter(&include_str!("../input.txt"))
+        .map(|x| x.get(0).unwrap().as_str().parse().unwrap())
+        .collect();
+    let (a, b) = launch_prob(target);
+    println!("Part1 {:?}, Part2 {:?}", a, b.iter().max().unwrap())
+}
+
+fn launch_prob(target: Vec<i32>) -> (i32, Vec<i32>) {
+    let [x1, x2, y1, y2] = <[i32; 4]>::try_from(target).ok().unwrap();
+    println!("Target {:?}", (x1,x2,y1,y2));
+    let mut acc = 0;
+    let mut maxy = Vec::new();
+    for i in 1..x2+1 {
+        for j in y1..-y1 {
+            let mut hor = i;
+            let mut ver = j;
+            let mut hy = 0;
+            let mut x = 0;
+            let mut y = 0;
+            while !(x <= x2 && x >= x1 && y >= y1 && y <= y2){
+                let py = y;
+                x += hor;
+                y += ver;
+                if py > y && hy == 0 {
+                    hy = py;
+                    };
+                ver -= 1;
+                if hor < 0 {
+                    hor += 1;
+                } else if hor > 0 {
+                    hor -= 1;
+                } else {
+                    hor = 0;
+                }               
+                if x >= x2 || y <= y1  {
+                    break;
+                }
+            }
+            if x <= x2 && x >= x1 && y >= y1 && y <= y2 {
+                acc += 1;
+                maxy.push(hy);
+            }
+        }
+    }
+    return (acc, maxy);
+}

+ 0 - 2
day8_seven_segment_search/src/lib.rs

@@ -48,8 +48,6 @@ pub fn solve_p() {
                 .unwrap()
         })
         .sum::<usize>();
-    // println!("The asnwer of part1 is: {}", part1);
-    // println!("The asnwer of part1 is: {}", part2);
 }
 
 fn get_key(code: &str, counter: &Counter<char>) -> usize {