From d4f482804b9777768fa4f9fedde0cd549578502b Mon Sep 17 00:00:00 2001 From: Brian Chu Date: Sun, 19 Dec 2021 22:57:37 -0800 Subject: catch up on solutions up to day 20 --- day17.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 day17.py (limited to 'day17.py') diff --git a/day17.py b/day17.py new file mode 100644 index 0000000..53881ea --- /dev/null +++ b/day17.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python + +# target area: 236 <= x <= 262, -78 <= y <= -58 +# i was originally going to do a brute force solution +# since the problem implies that the displacement on the x axis is the Vx'th triangular number +# which gives a lower bound on the number of steps to calculate the displacement on the y axis +# but there's actually a really brilliant solution located at +# https://github.com/prendradjaja/advent-of-code-2021/blob/main/17--trick-shot/a.py +# which I am paraphrasing here + +yvel = 77 +print(sum(n for n in range(1, yvel+1))) + + +# part 2 +xMin, xMax, yMin, yMax = 236, 262, -78, -58 + +def is_hit(vel): + for pos in trajectory(vel): + if xMin <= pos[0] <= xMax and yMin <= pos[1] <= yMax: + return True + return False + +def trajectory(vel): + pos = (0,0) + while pos[0] <= xMax and pos[1] >= yMin: + yield pos + pos = (pos[0] + vel[0], pos[1] + vel[1]) + vel = ( + max(0, vel[0] - 1), + vel[1] - 1 + ) + +result = 0 +for xvel in range(0, xMax+1): + for yvel in range(yMin, -yMin): + if is_hit((xvel, yvel)): + result += 1 +print(result) -- cgit 1.4.1-2-gfad0