r/adventofcode • u/daggerdragon • Dec 17 '21
SOLUTION MEGATHREAD -π- 2021 Day 17 Solutions -π-
--- Day 17: Trick Shot ---
Post your code solution in this megathread.
- Include what language(s) your solution uses!
- Format your code appropriately! How do I format code?
- Here's a quick link to /u/topaz2078's
pasteif you need it for longer code blocks. - The full posting rules are detailed in the wiki under How Do The Daily Megathreads Work?.
Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.
This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.
EDIT: Global leaderboard gold cap reached at 00:12:01, megathread unlocked!
46
Upvotes
9
u/Cold_Introduction_30 Dec 17 '21 edited Dec 18 '21
FEELING PROUD... I solved day 17 part 1 in my head while in the shower!
All you had to do was sum the numbers from 1 to (absolute_value(lowest y-target) - 1)
Example:
x-target = does not matter as long as it reaches vertical line "quickly enough"
y-target = -30 .. -5
highest point = sum(1 to 29) = 29 * 30 / 2 = 435
Why it works:
Since x-velocity eventually reaches zero, the number of steps you have is unlimited. Any value of y-velocity will eventually get back to height of 0 when y-velocity reaches its original but negative value. the next step is 1 smaller than the previous step so it can equal the lowest y-target value and still hit the target.
Assumption: x-target values are positive, and y-target values are negative
26
u/The_Fail Dec 17 '21 edited Dec 17 '21
My head (only part 1) #406
Assuming that you can always reach the landing zone with vx=0, you can exploit the fact that every upward trajectory comes back down to y=0 with velocity vy=-vy_start. The largest this may be is sucht, that you reach the lower edge of the landing zone in exactly a single step and thus vy=-y1-1 for the maximum height trajectory. Summing up you get ymax=(y1)*(y1+1)/2
Did the multiplication in my head while still lying in bed.
4
u/Sykout09 Dec 17 '21
Rust:
This one was fun to optimise, as there is many level down you can go.
Level 1: You can fairly easily calculate a maximum bound of what X and Y can be. X would be between 0 to XMax inclusive. For Y, you would need to calculate the YExteme ( where YExtreme = Max(Abs(YMin), Abs(YMax))). With that, Y range would be -YExtreme to YExtreme inclusive. For X, it is fairly easily deduced for X as anything higher than XMax means it will already overshoot on the first point. It is a little harder for Y, but fairly similar principal stands. For negative Y, it is the same as X, if too negative, it will overshoot on first point. For positive Y, it is harder as you need to take into account that the projectile can come back down. But, you can easily prove that the Y velocity is the same at the start and at the time it hit the ground at X=0. To see that let's imagine an example, lets assume Y = 3, which we will get the following data
You can see that it hit the ground at -3, the negative of at the start 3. You can easily see why as when the projectile is at maximum height, the Yvelocity is 0 and the velocity to the left and right is the same, just negative of each other. This means that if Y > YExtreme, the it will always overshoot on the way up, undershoot on the way down and overshoot if the the target box is negative.
Level 2: You can pre-compute all possible valid X and Y values before cross checking them. If you look at the projectile location calculation, you can note that X and Y do not interact with each other (as in Xcoord is only dependent on XVelocity, and Ycoord is only dependent on YVelocity). This means we can filter out all valid XVelocity and YVelocity independently. Easiest way is to just simulate X and Y until the coordinate overshoots the target box.
Level 3: You can pre-compute all valid steps range for each X and Y and automatically know if any two X and Y are valid pairs by checking if they have overlapping steps range. This allow us to avoid having to re-simulate the projectile path to double check if the coordinate is valid. For example, in the example given on AoC, for X = 8, we can calculate that X will be within the target box on step 3, 4 and 5, as at those steps, the X coordinate at those step would be 21, 26, 30; all between 20 to 30. To complement, for Y = 0, the valid steps are at 4 and 5, which is at coordinate -6 and -10. Since X = 8 and Y = 0 shares the step 4 and 5, we know that (8, 0) is a valid velocity as it will hit the target on step 4 (the smallest step of the union) and at coordinate (26, -6).
Bench:
Code Part 1 + 2
29
u/CCC_037 Dec 17 '21
Rockstar:
Part 1:
Part 2:
3
u/Great_Background_266 Dec 17 '21 edited Dec 18 '21
Same stuff as most people - brute force simulation.
Way to reduce the search space:
Within these ranges, there is a subset ([x_min,x_max], [y_min, y_max]) of initial velocities that take only 1 timestep to reach the target zone. These will not result in max y-coordinate, so no need to search in this range for part 1. But just counting these options is an easy way to get to right count in part 2.
3
u/WideBoyDixon Dec 17 '21 edited Dec 18 '21
VBA
Part 1: Assuming your target range runs vertically from uy to ly and that ly is negative. With an initial upward trajectory of j, your maximum height is j(j+1)/2 and, after 2j+1 steps, you'll be back at zero with a downward velocity of j+1 and step 2j+2 will take you to -j-1. With this in mind, the maximum initial upward trajectory is -1-ly. For example, if the lower bound of your target area is -119 then your maximum initial upward trajectory is 118. The maximum height you can reach from this trajectory is 118*119/2 = 7021. I brute forced the second part in VBA:
paste
3
u/GLRD500 Dec 17 '21
Part 1 can just be 2 lines (1 if you discount the making the input)
x_range, y_range = [277, 318], [-92, -53]print(min(y_range) * (min(y_range) + 1) // 2)4
u/chestck Dec 17 '21 edited Dec 18 '21
Task 1 Python
Where y is the y-coordinate of the bottom row of the target
Full solution
2
u/visnup Dec 17 '21 edited Dec 18 '21
JavaScript, with some interactive visualizations.
I don't know why I love using generators for these problems.
Edited to use a proper code block.
2
u/p88h Dec 17 '21 edited Dec 18 '21
Elixir 3 ms each part, sme math might have been involved.
2
u/vbe-elvis Dec 17 '21
Reddit makes it hard for me to post something today..
First one I did by math, the second using kotlin:
https://pastebin.com/kSgPz6Bw
2
u/nicuveo Dec 17 '21 edited Dec 18 '21
Haskell
Figured the trick out for part 1... did not for part 2. ^^'
2
u/vss2sn Dec 17 '21 edited Dec 17 '21
Solutions in C++:
Part 1
Part 2
(As always, every file is a self-contained solution)
Explanatory notes added for the math used.
14
u/ChessDouDou Dec 17 '21
Part 1 has a quick formula:
abs(y) * (abs(y) - 1) / 2
13
u/Xaetral Dec 17 '21 edited Dec 17 '21
Solution for Part 1 using no programming language:
Since the highest point will be reached using a launching vector such that we reach y = 0 at n-1 and y = ymin at n, with ymin being the deepest row of the target area (the 3rd number in the input) and n being the step nΒ°, then the highest point is the sum from 1 to (-ymin - 1), or in other term:
highest_point = -ymin * ((-ymin - 1) / 2)
Got me rank #170 instead of being around #4000 like usual, that was surprising.
11
u/GrossGrass Dec 17 '21 edited Dec 17 '21
Python
I think most people ended up going with some variant of a brute-force solution for part 2 (which is what I used initially), but I went back and actually found a somewhat more analytical solution.
Code linked above still needs to be cleaned up, but the general explanation goes like this for both parts:
Part 1:
Let
xandybe the coordinates of the initial velocity. Given that we're optimizing for maximal height, we can assume for this part thaty >= 0. Lety_0, y_1be the lower/upper bounds for the y-coordinate of the trench. We're also assuming that the trench is in the 3rd quadrant.Then for any valid
ythat could be a potential candidate, we're going to shoot up and then shoot down, so much so that we end up in the negative region. The height gain at each step is going to look likey, y-1, ..., 0, -1, ..., -kwhere-kis the height of the final step.For convenience, let
T_nbe the n-th triangular number, i.e.n * (n + 1) / 2. Then the net height gain from that entire sequence will beT_y - T_kand the max height will beT_y. So solving this part is simply a matter of finding all(y, k)wherey_0 <= T_y - T_k <= y_1and finding the max suchT_y.We know that
y < kgiven that we have to end up in the negative, and we can actually say thatk <= -y_0because for any greaterk,T_y - T_k < y_0will hold for anyy < k, since the smallest possible difference will beT_{k - 1} - T_k = -k < y_0.So that explains the logic for part 1 as well as why the upper bound works.
Part 2:
In this case, we try to take advantage of the triangular numbers in a similar fashion. The general logic goes as follows:
yvalues to the number of steps it takes to get within trench boundsxvalues to the number of steps it takes to get within trench bounds (i.e. it's a map of step number ->xvalues). Also track any potentialxvalues such that the probe will actually fall vertically through the trench.(y, step_number)mapping, find all valid possiblexvalues for that step number in order to get valid(x, y)pairs. Then, ifstep_numberhappens to be high enough, account for the situation where the probe is falling vertically and add any such potential pairs as well.To break down the logic for step 1:
y < 0: if there areksteps, then the sequence would simply goy, y - 1, ..., y - k, and the net gain would beT_{-y - 1} - T_{k - y}. Again, noting that we can bound triangular numbers by-y_0, we simply choose two distinct triangular numbers from this range, let's sayT_iandT_j, and then figure out what the correspondingyandkvalues would be, given that their difference is in the valid range.y >= 0: if there areksteps, then similarly to above and part 1, the net gain would beT_y - T_{k - y}. Again, we do the same logic as above, but with a slightly different derivation to go fromT_iandT_jtoyandk. Note we can still choose distinct triangular numbers here, since if they're equal, thenT_i - T_j = 0, and we're assuming that we're supposed to end up in the negative.Step 2 is basically just a simpler version of step 1, since we always know that
x > 0.Edit: an alternative way here would be track both the possible
xandyvalues for a given step numberk, and then iterate over all likelykvalues and simply do a product of possiblexandyvalues. You should be able to do the math and get a tight bound for eachkby solving some quadratic inequalities, e.g. solving foryiny_0 <= T_{-y - 1} - T_{k - y} <= y_1. You should be able to get a reasonable bound onkusing similar reasoning as above.10
u/4HbQ Dec 17 '21
Python, simple recursive solution. If we are past the bottom or right side of the target, we have certainly missed it (
return 0). If we are past the top or left side of the target, we have hit it (return 1). In all other cases, we recurse with the updated position and velocity:10
u/mebeim Dec 17 '21 edited Dec 17 '21
93/77 - Python 3 solution - Walkthrough
Oh boy. Today's walkthrough took me hours, specially thinking about the formulas with pen and paper and then also formatting them in markdown. Hopefully I did not do any typo or mistake with those (pretty hard, lol).
Anyway, not a bad day at all! Got on the leaderboard for both parts, I am actually surprised that I was able to solve it this quickly. This could have been far worse with larger input numbers. In any case, my clean solutions is a simple triangular number formula for P1, and a fast brute-force with good bounds for P2, without any dictionary/set/map, just a counter.
9
u/Mathgeek007 Dec 17 '21
EXCEL: 2003/6183
VIDEO OF SOLVE
For the first part, take the negative part of your basin, make it positive, minus one, the multiply it by (itself plus 1), divide by two. Congratz, you're done, and there's literally no helpful information gleaned from this part for Part 2.
So, Part 2.
So, you know how I'm kinda okay at arithmetic? Turns out I'm absolute garbage, since poor conceptual arithmetic broke me several times. Here's the correct way to do it, since I had to tweak it about a dozen times to troubleshoot all my garbage.
First, figure out the minimum X power that would get you to your box. Then figure out the maximum X power that would reach your box falling strictly vertically. This is your "dead zone", and is an important area to consider. Otherwise;
Make a chart of every possible negative Y value, from -1 to the lowest negative value of your basin. Then, evaluate one step, then a seecond, up until every single one of those values are beyond the outer scope of your basin. This is your Step Count for each. You now can evaluate at which step counts a Y value will hit.
Next, for each X value above the Dead Zone, count show many X values keep it within your area.
Next, for each count in the Y chart, check if this is the first Step evaluation in that row. If so, count the number of X values with that many steps. if NOT, count the number of X values with that many steps that didn't have one fewer step. This should get you an accurate count of all the possible Y-negative ranges.
Next, the Dead Zone. Conceptually, if you shoot something up, it will reach level with your firing position, ending the same speed you shot it. That means the first step below Y=0, it has one MORE negative speed than you shot it. Also, in my case, the Dead Zone for each of these X values were less than the minimum number of steps needed for Y=0 to hit my zone. That means, for Y=0 to the maximum negative Y of your basin, do a similar Y calculation as before, except completely ignore X, and just look at whether, for each Y, compounding speed at Y+1 gets you within the net at all, even once. If it does, multiply the total number of those Y values by the number of Dead X values to get the number of non-negative-Y pairs work.
You now have the negative-Y pairs and non-negative Y pairs. Add the numbers together, and there you have it! Only a 160 minutes, five different Excel sheets, a refactor, two failed attempted refactors, nearly 10 failed guesses, and a headache later - you got it!
Gosh, just end me now.
8
u/4HbQ Dec 17 '21
Python, using the fact that the positions on the x-axis and the y-axis are independent. So, for a given x-velocity, we can compute all x-positions. For example, with starting velocity 7, the positions will be 7, 13, 18, ... . Now instead of computing the actual positions, we return whether this position is inside the target (on the x-axis).
We do the same for the y-axis, and then and these two sequences. This indicates whether the x,y-position is inside the target. This is nice, because we can pre-compute and reuse these boolean sequences for a nice speed-up.
7
u/AltPapaya Dec 17 '21
Python
Solution (github)
I really like that the first part could be solved with a wizard wand operator:
return y_min *-~ y_min >> 16
u/sim642 Dec 17 '21
My Scala solution.
In part 1 I realized that x and y are independent, so just simulating things in the y-axis worked.
In part 2 I also simulated things in x-axis separately, but then I had to still verify that all the combinations of suitable x and y actually work when simulated in both axes simultaneously.
6
u/[deleted] Dec 17 '21 edited Dec 17 '21
No code, just maths, part 1:
To be able to achieve maximum height we need to be able to fall into the area vertically, thus we can disregard completely the component x. Just assume it's in a value that will reach 0 between the area.
My target y position was in the negatives. We know that the same speed we will reach upwards will be the speed with which we will reach 0. For example, with speed 3 (speed, new position): (3,3), (2,5), (1,6), (0,6), (-1,5), (-2,3), (-3,0), (-4,-4)....
The higher the initial velocity the higher the height too, thus we need to select the initial velocity so that initial+1 (in negative) falls at the lower end of the target.
So if the target is -100, -50 we need an initial velocity of 99 in the y department. One less than the absolute number of the minimum y target number.
Calculating maximum height is nothing more than the sum of 1+2+...+N-1+N, which is (N+1)*N/2.
Part 2 is more complex and I haven't delved into it much, probably brute forcing it would be better and faster.
P.S. Sorry if this breaks the "code solutions only" rule, but this was my "code". At most I could add an imgur of my notepad and some captures from wolphram alpha :)
P.P.S in C# so it has code and I can so upload it to "my solutions"
6
u/mzeo77 Dec 17 '21
2021 day 17 python fits into tweet at 254 chars
6
u/kuqumi Dec 17 '21
JavaScript (golfed)
Paste this in the browser console on your input page. It should return
[ part1, part2 ]6
u/strobetal Dec 17 '21 edited Dec 17 '21
Math + Python 3 (79/333)
I solved the first part with maths... No matter how high you throw it, it comes back to y=0, and to maximize upwards velocity, it should reach the lowest point in the box in the next step.
So if -10 is the lowest point, you need velocity 9. So the highest point you reach is 9+8+7+6+5+4+3+2+1, which is
9*8/29*10/2 (whoops).Then did a brute-force simulation for part 2:
6
u/nirgle Dec 17 '21
Basic C# solution with a straightforward try-everything simulation. This one could've been called 50 Thousand Iterations Under the Sea
I thought part 2 would be more exciting since the problem description says to increase
dxto 0 if it's negative, so I figured we'd have to consider currents or something that madedxnegative at times5
u/jonathan_paulson Dec 17 '21
23/18. Python. Video of me solving.
Brute force. Just need to guess the right bounding box for the inputs. It's fairly easy to see tight bounds on the x velocity (must be positive and within the target bound), and a lower bound on the y velocity, but I'm not sure about an upper bound on the y-velocity or the number of timesteps...
5
u/Diderikdm Dec 17 '21 edited Dec 17 '21
Python:
5
u/williamlp Dec 17 '21
PostgreSQL
SQL is back! After a rough two days where I needed Python this problem was pretty fun to solve with a recursive CTE.
5
u/prendradjaja Dec 18 '21
I liked this problem! Part 1 pretty naturally leads you to figure out what bounds to use for part 2 :)
Python 3: Part 1 / Part 2
5
u/meExceptAnonymous Dec 18 '21
I used Geogebra to solve part 1!
Here's the sheet I used for modeling the problem: https://www.geogebra.org/graphing/sj4hfhkr
4
u/SuperSmurfen Dec 17 '21 edited Dec 17 '21
Rust (260/583)
Link to full solution
Set a personal best on the leaderboard today!
I went with a simple brute force approach and just simulated the process for each velocity. I guess the tricky part is to know when you can stop. You could just do it for
Nnumber of steps and hope it is big enough, however, I used the following conclusions:velocity xis0and you are not in the target x range, then you will never reach the target.velocity yis negative and you are below the target y range then you will also never reach the target.Code wise there is not much to say.
i32::signumwas nice for thevelocity xupdate:The other issue is which velocities to search for. It's quite easy to see that for a
max_xof the input you only have to search0 < x <= max_xand foryyou only need to search frommin_yand up to some large number:This makes the brute force search run in about
9mson my machine.4
u/DFreiberg Dec 17 '21 edited Dec 17 '21
Mathematica, 252 / 264
It took a while to understand why there was a definite upper
y_0bound for this problem. Y has no drag, just gravity, so its arc is going to be symmetric. Thus, as the shot comes back down, it will always pass throughy = 0with a velocity of-vy_0, since it started aty=0with a velocity of+vy_0. So, if-vy_0is smaller than the lower bound of the target, you'll always overshoot if you go any higher.It also means (as a lot of people have noticed) that there's an O(1) solution to part 1:
y_max = y_targ * (y_targ + 1) / 2.Setup:
Part 1:
Part 2:
[POEM]: Cast My Words Into The Ocean
Inspired by /u/CCC_037's solution in the programming language Rockstar. This is in no way a valid Rockstar program.
Let my time be not my time.
Let verses carry thought.
Cast meaning into poetry.
Let target be the spot.
Shatter coords into shreds;
Cast x into the sky.
If x stops rolling short of goal
Then never think of why.
Rock the system with the x.
Rock on, and rock again.
Until the target is surpassed
Rock on; but roll it then.
Take the target - why the start
While target lacks a care?
Upend the target utterly.
Why should it finish there?
Every coord now will soar
Until the sky is furled.
Count targets struck by poetry.
Shout highest. Shout the world.
4
u/Perska_ Dec 17 '21
C# https://github.com/Perska/AoC2021/blob/master/AoC2021/Days/Day17.cs
For Part 1, I actually manually searched for the solution by aiming myself at first.
For Part 2, I determined all starting X velocities that could reach the goal at some point, and brute forced Y velocities for the potential x velocities. Not sure if there's a way to do that better.
4
u/s3aker Dec 17 '21
Raku solution
Today's code is trivial, puzzle is tricky.
4
u/Smylers Dec 17 '21 edited Dec 17 '21
Perl for partΒ 2, in which the only really notable aspect is that I got to use the spaceship operator (sub probe operator?) outside of a
sortblock:<=>returns-1,0, or+1to indicate that its operands are<,=, or>respectively (easy mnemonic: the return values in numerical order match the order of the individual symbols in the spaceship from left to right). So when$vxis positive,0 <=> $vxreturns-1, and$vxis reduced. And vice versa.Full code with boilerplate for enabling signatures,
say, andsum.Edit: Removed the unnecessary
mapfrom the first line, because the input is all on a single line today. That introduces the<>=~operator, which looks a bit like something the sub probe may see swimming past it.4
u/EmeraldElement Dec 17 '21 edited Dec 17 '21
AutoHotkey
Part 1Part 2
For this one, I first simulated the X movement only because its velocity always converges to zero. This let me filter out potential X Velocity values where X wouldn't ever reach the target area, or would clip past it.
Here's that part:
And the result (for the sample) looks like this
I used similar logic to get all potential Y Velocities. Then I nested two for-each loops of the potential X and Y values, respectively and simulated them together, until it hit the target area or went past it.
By sheer luck (or foresight), I was already calculating all the distinct velocity pairs, so when I got to Part 2, I slapped a variable with an increment into the IF block and counted them up. The only adjustment that had to be made was to include negative Y velocities in the search. I had previously excluded these by logic that the maximum Y position would always be zero.
Hope you enjoyed today's puzzle and didn't get stuck! I personally still have 3 stars to get from the last couple days. Day 15 is hard!
-EE
4
u/relativistic-turtle Dec 17 '21
IntCode
Part 1 - analytical:
y(t) = t*vy0 - t*(t-1)/2(Onlyyandvy0is relevant).y=0whent=2*vy0+1, for allvy>=0y(t+1), should be just inside the target area with maximum velocity (implies that the probe was already at maximum altitude. -->y(t+1) == target_ymin.vy0 = - target_ymin - 1, -->t(usingt=2*vy0+1above)y(t)has its maximum att/2, but we take either of the integer times(t +/- 1)/2, when evaluatingyfor its maximum.Part 2 - brute force search:
Search domain:
0 <= vx0 <= target_xmaxtarget_ymin <= vy0 <= vy0_from_part1,t=0, simulate probe trajectory until the target is hit. Abort wheny < target_ymin.4
u/marshalofthemark Dec 17 '21 edited Dec 17 '21
Ruby (runtime: 40 us / 90 ms)
Happily, the syntax used in the input is identical to Ruby's range syntax*, so we can use
evalto parse the ranges literally:First a couple math formulas which will really help us:**
Triangular gives us the n-th triangular number, which is useful because for an initial x-velocity n, the projectile will start falling vertically when it reaches x = n-th triangular number.
Loc gives us the position of an object launched at an initial velocity after steps units of time. We can use this for both the x- and y-coordinates of the projectile.
Next, a method that returns an array of all the possible initial x-velocities which will allow the projectile to enter the target area.
Then, a method that lets us know, given an initial x- and y-velocity, whether the projectile will hit the target area:
Now we're ready to solve. A few other comments have already gone into the details on why that shortcut works for Part 1. I added code to account for an edge case when it doesn't.
For Part 2, we take the array of possible initial x-velocities, loop over all possible y-velocities, and tally up the number of unique velocity values.
* IIRC, AoC is written in Perl, so Eric probably just used the Perl range syntax - just so happens that Ruby copied Perl's syntax for ranges
** Written as end-less methods, which only work in Ruby 3.0+. Earlier versions required you to end a method declaration with
end.4
u/jayfoad Dec 17 '21
Dyalog APL
4
u/Jools_Jops Dec 17 '21
Python 3
part1 part2
Part 1 was easy with a bit of math, if my approximation missed some lower values for the velocity of X I do not think that would matter. So maybe I got a bit lucky on part one?
Part 2: I tried to be smart but my solution brute forces the problem. Had to "walk" the approximations outside the "target" area as otherwise I got too small a result. This is what leads me to believe I got lucky in part 1.
4
u/Divritenis Dec 17 '21
Javascript
Part one was very easy - get the absolute value of smallest Y from target, reduce it by 1 and calculate the factorial.
The idea behind it is that once you shoot up, it will come down back to 0 and as a last valid step (to be in target), it will have to go from 0 to the smallest target Y. As it spends one step with the speed of 0 (at the very peak), you need to reduce steps you're going up, hence the minus 1.
Part one: https://github.com/AugustsK/advent-of-code-solutions/blob/master/2021/day17/partOne.js
Part two is not really that clever:
Part two: https://github.com/AugustsK/advent-of-code-solutions/blob/master/2021/day17/partTwo.js
4
u/Premun Dec 17 '21 edited Jan 11 '22
C
I actually did not brute force it all the way. I remembered that you can get the sum of
nincreasing numbers:sum = n*(n+1) / 2From there, I can count the
nso that I hit targetsumwhere sum is the distance I need to travel with the X velocity. So the lowest possible velocity is to just hit the left side of the target:minVelocity = Math.Ceiling((-1 + Math.Sqrt(1 + leftSide * 8)) / 2)And the maximum is easy - you get 1 tick to shoot all the way so:
maxVelocity = rightSideThe whole solution: https://github.com/premun/advent-of-code/tree/main/src/2021/17
4
u/WickedCrow Dec 17 '21
C# github
Code footprint is small, vaguely sensible bounds on a brute force solution. Why not?
I'm more proud of my commit name than my solution.
4
u/rtm0 Dec 18 '21 edited Dec 18 '21
R / Rlang / Rstat
I used the formula for the sum of an arithmetic series to "integrate" the velocities, the work is done in vectorized logic checks. The result is compact, but its definitely brute force
4
u/prscoelho Dec 18 '21 edited Dec 18 '21
Python 3, runs example and solution in 30ms
Not exactly brute force, and it has some comments and notes at the end. Basically
pos(t) = (-1/2)t^2 + (1/2 + v)tfor both axis.You can find the t range where pos(t, v) = area, and do so separately for the x and y axis. It is the same function for x and y, it's just that x has drag and we can account for that in our range. If t for area_x[0] exists, but it doesn't exist for area_x[1], this means it stops inside the area and the range is (left, inf)
Then for each x and y, if their ranges overlap it will land on area.
For the highest y, we can find y'(t) = 0, and then max_y is y(t)
4
u/OddCoincidence Dec 19 '21
Rust
Took me embarrassingly long to figure out that the initial y velocity had to be within the range
[-abs(target_min_y), abs(target_min_y)]. π€¦ββοΈ1
u/nlowe_ Dec 17 '21 edited Dec 17 '21
Go, 1093/563
I just brute-forced it,
0<=vx<500/ymin<=vy<500whereyminis the minimum y coordinate of the target bounding box seemed sufficient for a search space and still reasonably fast, I also stopped searching if vx=0 and x was outside the bounding box or y was already below it. I'd love to revisit this one and see if I can come up with a smarter way to solve it!1
u/Dioxy Dec 17 '21 edited Dec 18 '21
TypeScript
I thought of a way to not guess the ranges, this should work on any input. My solution came based on the idea that the y velocity should be a parabola, so the velocity at y=0 should be negative your start velocity
https://kufii.github.io/advent-of-code-2021/#/17
1
u/Dooflegna Dec 17 '21 edited Dec 18 '21
The minimum x value for brute-force firing is the triangle number n that is greater than the minimum x value of the puzzle.
As a reminder, triangular numbers are the series 1+2+3+β¦ and are calculated as
(n * (n + 1)) / 2How do we know this?
We know that the x_velocity loses 1 speed every turn until it hits zero. So a velocity of 4 means that the cumulative x distance the probe can travel is 10 = (4 + 3 + 2 + 1) before it can travel no further horizontally. If the minimum x is greater than 10, then we know it can never hit the target area.
So to find the minimum x value, you simply need to calculate triangluar numbers until you are greater or equal to the minimum x value of the puzzle.
In Python:
1
u/raxomukus Dec 17 '21
Python
1
u/pimpbot9000k Dec 17 '21
Part I.
My target area was "below zero" so it was easy to deduce the initial vertical velocity:
The highest shots are achieved when the flight time it takes to hit the target is loooong -> presumably the horizontal velocity has slowed down to 0. Therefore we can deduce that with the highest shot the initial horizontal velocity must be such that when the horizontal velocity has decreased to zero the horizontal distance traveled must be between the horizontal range of the target area. Therefore the horizontal initial velocity is not relevant here because the missile is just falling straight down when it hits the target and the initial horizontal velocity does not affect vertical speed / position nor max height of the trajectory.
For maximal initial vertical velocity the target must be hit the first time the missiles y-coodinate is negative. Taking this into account, if the initial y-velocity is vy the the target is hit at point (x, -(vy + 1)).
So the initial velocity must be abs(min_target_y+1) -> calculate the max height of the trajectory with this initial vertical velocity.
Part II
I used up all my thinking abilities so I basically just guessed the range of the velocities and did some real ugly and slow brute forcing.
1
u/Skyree01 Dec 17 '21 edited Dec 18 '21
PHP
This felt like a breeze compared to yesterday, I'm quite happy with how it turned out.
Link to both parts
Part 1 can basically be a one liner: since the probe Y position decrease by 1 each step, you can calculate the maximum height by calculating the nth triangle from the highest coordinate of the target (y1)
1
u/RJdaMoD Dec 17 '21 edited Dec 17 '21
Mathematica
Well, i think this does not work for all possible inputs, but at least for the given ones:
If you set showTrajectory=True, you get some visualization like in the puzzle description, but beware the maximum y-value. Looks better on the sample data.
1
u/DaMightyZombie Dec 17 '21
Python
Part 1:
3
u/bluepichu Dec 17 '21
TypeScript, 24/5. Code here.
Is there a clever way of doing this, or proving that some choice of bounds for brute force is sufficient? I just kinda picked 1000 arbitrarily and it worked out fine...
3
u/Gurrewe Dec 17 '21
Go (golang), 439/265
Brute force on part 2, I first guessed that all values where within (-1000, 1000) but was wrong. Bumped it to 2000 and got it right!
Source
3
u/aardvark1231 Dec 17 '21
My C# Solution
Nothing fancy, just some brute force. Did not expect to finish in the 1000 range on both parts today.
3
u/[deleted] Dec 17 '21 edited Dec 17 '21
Python 3
https://colab.research.google.com/drive/1Zawd4KKsnzwl2D13PL2BSOjVI6zCKN1s?usp=sharing
Decouples x and y and then merges them
3
u/constbr Dec 17 '21
Javascript 651/1300 @ 00:16:45/00:33:35
Just fighting bugs all the way. Bugs in simulation code that wouldn't consider trajectories as valid, bugs in cycles where I wasn't considering all trajectories that could work. Especially when I'm getting right result on test input and wrong on real data, that's just like waaaatβ¦
Both parts:
3
u/BluFoot Dec 17 '21
Ruby 164 bytes
3
u/death Dec 17 '21
Day 17 solution in Common Lisp.
3
u/MasterMedo Dec 17 '21
Python featured on github
Smart solution for part one, onder one assumption:
sqrt(xmax) < abs(ymin)3
u/bZea Dec 17 '21
Elixir
Brute force all the way (~60ms). Actually started with narrowing down the range of Xs but after a quick check realised the optimization isn't really needed for these inputs.
3
u/u794575248 Dec 17 '21
J Language (an array programming language based primarily on APL)
Manual search and bruteforce.
3
u/firetech_SE Dec 17 '21
Ruby (1598/1502)
Was a bit slow today, but did some math to minimize the search space after getting my answers right. All my math is (or at least should be) explained in comments in my code:
Curiously ended up submitting the answer for some other input in part 2 at one point when my search space was too small...
3
u/kimvais Dec 17 '21
F#
One of my this years favourites so far, pretty straightforward after using some common sense to figure out the potential velocity vector bounds and using
Seq.allPairsfor some brute force. Also the fact that first of the coordinates in every trajectory are equal to the velocity vector proved to be useful for part 2.3
u/xelf Dec 17 '21 edited Dec 17 '21
Spent far too much time being clever on this one, only to post on discord and the webs and discover that everyone else had been clever as well.
Python and math!
Fun times deducing the ranges for the for loops so that it returned immediately.
3
u/2133 Dec 17 '21 edited Dec 17 '21
I was adamant to not brute force this one, ended up having to do too much math at midnight...
Here are some insights I got:
(end_velocity)(end_velocity + 1)/2 - (start_velocity)(start_velocity+1)/2 = some y in target
If end_velocity is a whole number, then we know that we can reach the target. This is just a quadratic equation! I solved the root using the quadratic formula.
Python
3
u/clouddjr Dec 17 '21
Kotlin
Interesting puzzle. Solved the first part without even writing any code. I liked that I could use Sequences that simulated changes in x and y positions and operator overloading for checking if a point is inside a target area.
Github
All solutions
3
u/flwyd Dec 17 '21
Raku, 4863/4996. I thought for awhile about analytic solutions, concluded that it was probably covered by some calculus or linear algebra that I forgot, and decided to brute force it. I'm glad I did, since part 2 would be even more challenging analytically. I also managed to introduce a whole bunch of bugs, including an extended period of WTF until I realized that
(25-7i).re β 20..30is False becauseComplex.rereturns aNumbut aRangeofIntonly acceptsβon Ints. Meanwhile,(25-7i).re ~~ 20..30(smartmatch, not set containment) returns True because There's More Than One Way To Do It, And Some Of Them Are Subtly Wrong.3
u/kolev Dec 17 '21
My solution in Go.
3
u/ficklefawn Dec 17 '21 edited Dec 17 '21
Golang
Not really proud of this one.... I was too lazy to find a proper formula for x velocity including drag value so I just constrained the x value between minDrag and maxDrag and simulated the x trajectory every time to find a possible solution. Now I see that many here did a full brute force simulating for various velocities, so this is perhaps slightly better because it simulates for more constrained values. If anyone has a nice formula for x(t) given drag, let me know!! Same for constraints on steps t. I put it to < 2*maxX because I'm sure that we never want to overshoot more than that, but there is probably a better constraint there.
Full code here
The trajectory finder, along with assumptions
3
u/rawling Dec 17 '21
C#, just for the sheer joy of a horrible
forloop3
u/Chitinid Dec 17 '21 edited Dec 17 '21
Python 3 class
3
u/rampant__spirit Dec 17 '21
Python Solution to both parts in 12 ms. I couldn't get it any faster. Open to suggestions :D
https://pastebin.com/ZJbQZkmn
3
u/r_so9 Dec 17 '21
F
paste
Removing the input parsing, the code is quite compact
3
u/kbielefe Dec 17 '21
Scala 3
Ultimately one of the shorter solutions this year in terms of amount of code. I way overthought it though, because I forgot the y velocity component is the same as the initial velocity when it crosses zero coming down.
3
u/Chaosteil Dec 17 '21
Rust
Really happy about the trick in the first part, but the second part is, yep, brute forced. Overall very neat problem.
3
u/Multipl Dec 17 '21
Python 3
https://pastebin.com/3RTtxBaY
3
u/giftpflanze Dec 17 '21
Factor
3
u/cetttbycettt Dec 17 '21 edited Dec 17 '21
R / Rlang / baseR
I first computed bounds and checked within a certain region of velocities. Compared with yesterday this was a piece of cake.
Lets denote the endpoints of the target-area with
tx1 < tx2andty1 < ty2 < 0. Thentx2is clearly an upper bound for x velocity.ty1is a lower bound for y-velocity and also-ty1is an upper bound for y velocity.Also, under some mild assumptions, the solution to part 1 is
1 / 2 * abs(ty1) * (abs(ty1) -1). github3
u/[deleted] Dec 17 '21 edited Dec 17 '21
Rust: Geometric (non-brute force) solutions for parts 1&2
Runs in 4ns & 190us on my laptop.Runs in 4ns & 10us on my laptop after some hot optimizationsThis assumes input X range contains a triangular number.
https://github.com/RocketRace/advent-of-code/blob/main/src/y2021/d17.rs
Part 1: Uses an arithmetic progression to determine the highest point in the curve given initial conditions.
Part 2: Iterates through each step count (up to a computed upper bound) and generated the two-dimensional interval of velocities that reach the target. These are generated in constant time, also modelled with arithmetic progressions. (The X velocity has two special cases to account for it never being negative.) Once you have a vector of rectangles, take the sum of unique areas, i.e. areas not counting overlap. Because every overlap is guaranteed to be between consecutive elements, you simply subtract the area of consecutive intersections from your total area!
3
u/_jstanley Dec 17 '21
SLANG
For part 1 I wrote an interactive program that let me input candidate velocities and see whether they hit the target, fall below, or sail over the top. I explored the search space manually, found a convincing best Y coordinate, and submitted it, and it was correct. The manual exploration led me to realise that for the velocities with high intial Y velocity, the X velocities always need to be the same. The "drag" effect pulls your X velocity to 0 before you hit the target, so when you hit the target you're falling straight down. Once you've found the X velocity that puts you in range of the target, you just need to increase Y until you miss the target, and try a few around there to see if there are any extra hits. I don't know how to prove that a larger Y velocity can't hit the target.
For part 2 I just did the obvious stupid brute force, except with the condition that above a certain Y velocity you only need to explore the one single X velocity that got the right answer in part 1.
For me, Advent of Code is about using a computer to solve problems. Most of the time this is done by writing a general program to solve problems of the type you're given, but sometimes just interactively working with a computer to get the answer to your specific input is enough.
No video today due to audio problems.
https://github.com/jes/aoc2021/tree/master/day17
(My Adventure Time project)
3
u/BOT-Brad Dec 17 '21 edited Dec 17 '21
Golang (both parts). (See more at https://github.com/varbrad/advent-of-code-2021)
Part 1
The x value doesn't matter, so it's just about finding the best y value. I discovered that the best value y is always the lower bound * -1 and then -1. In the example, the target area y is -10 to -5, well (-10*-1)-1 = 9, which is the right y value for the optimimum height. Finally, the max height is then just the y + (y-1) + (y-2) until y = 0 (e.g. 9+8+7+6+5+4+3+2+1 = 45). We can use the triangle # formula to calculate this quickly. I tried this with my puzzle input and the answer was right.
Part 2
I just brute forced it lol
3
u/Ning1253 Dec 17 '21 edited Dec 17 '21
__Python3__
Solution:
Part 1: Since this in an iterative model with a constant acceleration, the vertical coordinates will be the same on the way up and down until reaching an altitude of 0. Given that my y coordinates had to end up between -101 and -57, the greatest velocity would be the one such that the shot would end up at y = -101. Since the velocity at that step is 1 more than the starting step (and its mirror where the shot gets back to 0 height), the starting velocity maxes out at 100.
By triangle numbers, 50*101 = 5050 is the maximum height.
Part 2: Brute force. The maximum x velocity is the one which brings my particle to the edge of the box in one go (287 for me), the minimum is the smallest velocity such that the corresponding triangle number is greater than or equal to the lower bound (257), given me a range of [23,287).
For the y, the maximum velocity is as previously calculated, and the minimum is simply going straight down to the bottom of the box in one go, giving me a range of [-101, 101).
Leading to my code:
Pastebin
I am also like 50% sure there is a mathematical way to get the answer for part 2, using the binomial theorem maybe? I'll be thinking more on it.
3
u/lukeredpath Dec 17 '21
Sometimes, you've just gotta brute force it if you don't know any better. https://github.com/lukeredpath/AdventOfCode2021/blob/main/Sources/AdventOfCode2021/17.swift
3
u/azzal07 Dec 17 '21
Postscript, PS.
Today was refreshingly simple after the last two days. Nothing fancy, just a straight forward brute force loops over suitable starting velocities.
Awk; solves as many lines of input as you wish, so there is some variable resetting fluff
3
u/domm_plix Dec 17 '21
Perl
Took me quite a while to figure out how to calc the min x velocity (writing a brute force loop would definitly have been faster..). Then it's just a matter of trying all x-velocities between that value and the maximum of the target box, combined with all possible (based on a guesstimate) values for y velocity (cannot be less then the lowest y of the box, and I tried the double of the absolute lowest y, which worked (so take that, math!)).
The just shoot and find the highest y.
Part two was especially easy, just count the hits.
https://github.com/domm/advent_of_code/blob/main/2021/17_2.pl
3
u/adventofcodefan Dec 17 '21
Javascript / JS / Node.js
I really liked this one, it was interesting. Part 1 became a whole lot easier when I realized that you only needed the Y velocity for it. I tried doing a "mathy" way at first, but that didn't work so I just bruteforced :(. I thought I was doomed in part 2 and it would just be a way bigger input, but it wasn't lol. All I had to do make a few changes to my part 1 code.
Part 1 Part 2
3
u/chicagocode Dec 17 '21
Kotlin -> [Blog/Commentary] - [Code] - [All 2021 Solutions]
Brute force for both sections! The computer is doing the work, not me. :)
I ended up writing a function to produce a sequence of points along the probe's track, some functions to tell if the probe is within the target area or has overshot it, and using all that to solve both parts.
Note - if you follow my solutions or blog I'll be late with tomorrow's solution due to a personal conflict.
3
u/_Heziode Dec 17 '21
Ada
This is an Ada 2012 solution:
3
u/aoc-fan Dec 17 '21
TypeScript, Rare day where Part 1 was solved with a formula and Part 2 required brute force.
3
u/SpaceHonk Dec 17 '21
Swift
https://github.com/gereons/AoC2021/blob/main/Sources/AdventOfCode/puzzle17.swift
Brute force with some limits to the search space. Runs in about 1.1ms on my M1 Mac, and probably can still be made significantly faster
3
u/RibozymeR Dec 17 '21
Factor, using Math
3
u/tymscar Dec 17 '21
Today was my new favourite day! I spent a long time on part one thinking of a mathematical way to do it because I was scared of what part 2 mightβve been. But then I ended up just bruteforing and that worked great for both parts. I also tried to hone in the zone a bit better and precalculate y values and got down the runtime of both parts together to around 20ms in Javascript so I was quite happy. Here are part1 and part2
3
u/KT421 Dec 17 '21
R
https://github.com/KT421/2021-advent-of-code/blob/main/dec17.R
Brute forced it, sure that pt2 would punish me for my hubris
Instead, the answer was
nrow(shots)whereshotsis the dataframe where I stored successful hitsNice to have an easier puzzle, gives me time to hit my head against Day 16 some more
3
u/LuckyLactose Dec 17 '21
SWIFT
Full repo here.
Part 1: Hey, I can math this!
Part 2: Too tired, let's just add some for loops and be done with it.
3
u/solareon Dec 17 '21
Excel
Part 1 solved with the math of ABS(ymin)*(ABS(ymin)-1)/2 Part 2 I resorted back to the sledge hammer and built giant arrays of valid velocities then plotted positions against them. Full sheet calculation comes in around 5 minutes and RAM usage of 4GB. Day 15 currently holds the record though with 20GB of RAM usage.
Solutions here. Well not this one it's 150MB
3
u/ramendik Dec 17 '21
Python. "No force like brute force". Brute-forced p1, then p2 required a trivial correction (scanning negative vy values, which never counted for part 1)
https://github.com/mramendi/advent-of-code-2021/blob/main/17.py
3
u/ICantBeSirius Dec 17 '21 edited Dec 17 '21
Bored today so I golfed my Swift solution.
3
u/randomginger11 Dec 17 '21
Python
If anyone is looking for a visualization tool for debugging:
Includes a simple function that takes a list of points and displays an image of the trajectory and target
Part 1
Didn't brute force it!
For any given positive initial Vy, you will always come back to zero at some point. So the maximum Vy you could have and still hit the target is Vymax = -1 * (Y bottom of target). With this Vy, one step after coming back to y = 0 you will be at the very bottom edge of your target.
So start with this Vy_initial and loop through all Vx_initial (starting with 1 and going up) until you either hit the target or overshoot. If you overshoot, decrease Vy_initial by 1 and try again.
Part 2
loop through a range of possible Vy and Vx values. Bounds of the ranges are:
Then just try every pair Vx and Vy in these bounds and count the hits
3
u/usesbiggerwords Dec 17 '21
Python 3, brute force. This really should be solved by some elegant ODE solver, but I'm just not that good. The key here is picking reasonable bounds, particularly for Part 2. Careful study of the example data reveals how the bounds should be set up. Code is ugly, but works.
https://pastebin.com/Y0xriCur
3
u/Tetrat Dec 17 '21 edited Dec 18 '21
Python
Part 1 can be solved with:
Part 2 is shown here: paste
This solution takes about 43ms to run on my computer. I consider the set of time steps where the probe is in the x range each x velocity. Then repeat for y. Then check the intersection of each x set for each y set.
3
u/DaydreamingThinker Dec 17 '21
Python
I solved possible x and y parameters (with a wide upper margin for both) and saved the possible parameters for each number of steps. By looking at the intersetion of the possible step values for x and y coordinates, it was simple to construct all the points.
3
u/robinhouston Dec 17 '21
Python
It didnβt really occur to me to bruteforce it, which would definitely have been easier. Still, at least that means my solution is a little unusual.
3
u/suddengunter Dec 17 '21 edited Dec 17 '21
Go
Part1 is solved by formula, I've seen many people using it. Didn't get to it myself, read other solutions for inspiration but then was able to understand it.
Part2 could be easily brute-forced, but in my case it's optimized brute-force: I know min/max velocity for Y (very simple logic, see solution), max X is also easy. min X took me some time to figure out, but also easy. So, it leaves me with 58944 simulations to run to get solutions on my data. On the example data I only run 500 simulations (25 possible X values * 20 possible Y values), though it obviously could be optimized.
UPD: I know my code is ugly, it's 2AM and I'm doing it after long day of work, sorry
3
u/Screevo Dec 18 '21
Python3 - https://github.com/expsmartin/AOC2021/blob/main/d17.py Threw away 3 hours trying to solve this like a trick question. walked away for 6 hours, came back and assumed βnah, it reads how it readsβ and solved p1 in 20 mins and p2 in 20 seconds.
3
u/Chrinkus Dec 18 '21
My C Solution
Back to sub-24 hours! My personal "leaderboard" is to try to complete these within the day they're released. I got put off pace by my real job since the Dijkstra day but I've clawed my way back.
My part 2 clocked in at 23:39:33 so that's a win for today!
3
u/schoelle Dec 19 '21
GNU Forth
First ever code in forth. IO and string parsing in this language seems terrible. Actual solution is not that bad. Simple brute force approach for searching.
https://github.com/schoelle/adventofcode2021/tree/main/17-forth
3
u/timvisee Dec 20 '21 edited Dec 23 '21
Rust Fast. Using some shortcuts to check projectile collision.
Part 1 0.0002ms (210ns)
Part 2 0.095ms (95ΞΌs)
day01 to day17 total: 39.87ms
3
u/Sourish17 Dec 20 '21
Python 3
I still can't get over the maths lol!
Mini writeup + solution:
sourishsharma.com
3
u/artesea Dec 22 '21
PHP
Part 1 Part 2
Mainly brute force, with some restrictions on the space being looked at
3
u/msschmitt Dec 29 '21 edited Dec 29 '21
z/Architecture Assembler
This is Day 17 Part 2 in IBM High Level Assembler for z/OS. "High Level" in HLASM refers to the High Level Assembler Toolkit Feature Structured Programming Macros, which is an extra-cost add-on. This program doesn't use any macros, so we should just say it is z/OS assembler.
This solution uses no memory ("storage"), aside from the memory occupied by the loaded program. It is only using the CPU's registers.
It also does no I/O. The input target area is entered in the source. The output number of velocity values that hit the target is returned as the program's Return Code.
I executed this program on an IBM z14 mainframe.
3
u/XtremeChaosFury Dec 30 '21
Python 3 Solution
Note to Self: After reading all of these solutions, I would say the best part 1 solution is definitely using:
n * (n + 1) / 2if you understand exactly what the problem is asking you for too...
2
u/hugh_tc Dec 17 '21
Python 3, 37/136.
Part 2.
Played the waiting game. Was it worth it? Dunno. Surely there's a faster solution.
2
u/Loonis Dec 17 '21
Perl
Paste
Messy brute force solution today. Nice quick solve after last night's marathon :)
I think I spent half of my time thinking about which initial velocities to try, and went for "anything that doesn't immediately overshoot".
2
u/sebastiannielsen Dec 17 '21
A simple lovely Perl while loop and a couple for loops. Super easy.
https://pastebin.com/Admg0tfp
Used 0 --> 200 as bounding for X velocity And -200 --> 200 as y velocity
As any other values would inevitable miss a target that is inside this boundary.
In addition I had part2 already ready, as I just had to add a %loader hash array to keep track of distinct values.
2
u/rabuf Dec 17 '21 edited Dec 17 '21
Common Lisp
No smarts, just guesses. I picked a range for the x velocities and the y velocities and just hoped it would work. I could winnow it down, and may later, so that it doesn't do more work than needed. Like, given an initial x velocity it should be possible to directly calculate the initial y velocity that will reach the target (or have a chance to) or a narrower range of y velocities than I did.
I got part 2 by just extending my part 1 to count how many trajectories hit the target. No other changes were needed:
enters-targetisn't interesting, it literally just steps through the calculations and returns the peak y position and whether or not it hit the target. If y ever goes belowmin-yor x goes beyondmax-xthen it terminates and returns the peak (which will be discarded) andnil(false in Common Lisp).I picked almost arbitrary ranges for x velocity and y velocity. y velocity really is arbitrary, I just figured we couldn't be moving faster downward than the minimum y position. The upper bound was picked to have an upper bound, could've been anything. For x, the fastest it can go is the furthest bound on the target (
max-x), and the slowest it can go is roughlysqrt(2*min-x), but I didn't think of the factor of 2 when I coded it up, so I went with the square root ofmin-xwhich means extra work is done, but not too much.2
u/ri7chy Dec 17 '21
Python
this one was fun...
a relief after the last 2 days.
2
u/michaelgallagher Dec 17 '21
Python
So anyway, I started blasting
2
u/JoMartin23 Dec 17 '21 edited Dec 17 '21
Common Lisp
I'm sure there's probably some clever way to do this, but I just kinda brute forced it as per usual.
2
u/PendragonDaGreat Dec 17 '21 edited Dec 17 '21
C# 2628/2763
https://github.com/Bpendragon/AdventOfCodeCSharp/blob/4b33d5/AdventOfCode/Solutions/Year2021/Day17-Solution.cs
Step 1, calculate minimum value of X that reaches the target zone (Using Gauss (which you may remember from day 7) in reverse)
Step 2, lob 100 probes into the "sky"
step 3, use the data from the above tests to determine the test space for part 2.
Step 4 ?????
Step 5 STARS
Edit: Euclid -> Euler
Also that code is slightly incorrect, see comment chain below.
Edit 2: Gauss
2
u/t-rkr Dec 17 '21
Perl
I know there is a way to calculate the maximum y-velocity (as with the minimum x-velocity), but I'll leave that for some quiet time on the weekend.
Link to Code
2
u/ElCholoGamer65r Dec 17 '21
TypeScript: https://github.com/ElCholoGamer/advent-of-code/blob/main/src/days/2021/17.ts
This one was pretty though. Surprisingly, I didn't use a brute-force solution (for the most part). Basically, for each shot, my program adjusts the initial velocity left, right or up based on the direction by which the probe missed the target area in the previous shot.
2
u/autid Dec 17 '21
FORTRAN
Pretty lame part 2. Gets max steps from part 1 answer. Steps through with all viable x/y velocities and marks the ones that finish a step in the area.
2
u/BradleySigma Dec 17 '21
matlab
2
u/satylogin Dec 17 '21
rust part 2
2
u/[deleted] Dec 17 '21
Rust
I used an infinite
Iteratorto plot out the trajectory of the probe, then collected it into a vector up to the point it conclusively hit or missed the target area. Havingsignum()around was nice too! I'm curious if there's a way to avoid the allocation for the vector though.Infinite trajectory iterator
Getting the maximum height of a trajectory
Full solution here.
2
u/WilkoTom Dec 17 '21
Rust
Very brute-forcy, and my first Part 2 answer was wrong because I didn't actually properly look at my real input and my hard coded search parameters weren't wide enough. Today's task gave me huge nostalgia for my wasted youth playing Scorched Earth in my school's computer labs back in the day.
2
u/gerolfscherr Dec 17 '21
Java
just brute force searching
https://github.com/gerolfscherr/aoc2021/blob/main/src/main/java/AOC17.java
2
u/allergic2Luxembourg Dec 17 '21
Python
I did some of it on paper and then just brute-force checked various trajectories.
I spent a little bit of time checking what ranges I needed to check for my velocities. I would love it if others took the time to check if these ranges worked for their inputs - they worked for the test input and my input.
It's a bit strange that the required velocities don't depend at all on the y-coordinates of the target - maybe I made a mistake there?
2
u/IdrisTheDragon Dec 17 '21
Python
A brute force solution:
https://github.com/IdrisTheDragon/Advent2021/blob/main/day_17/day_17.py
Some consideration into the min/max initial vx and vy but not too much.
There's probably a really nice mathematical solution for today that require simulating every step of time.
2
u/professoreyl Dec 17 '21
Python 3.9
Clean code, object-oriented, type-annotated, documented.
Brute forced solution
https://github.com/DenverCoder1/Advent-of-Code-2021/tree/main/Day-17
2
u/hqli Dec 17 '21 edited Dec 17 '21
TypeScript
First part just took me a bit to realize the probe will always hit y=0 coming down, because the Y positions are going to be symmetrical going up and down. Speed as well. And using that you can determine the max speed going down from y=0 that'll hit the bottom row of the target area. Which can be traced to the max possible height, and gives you max Ξy at launch.
Min Ξy and max Ξx are how hard can I shoot and still hit the bottom right corner of the target.
Min Ξx is reversing the gauss sum then ceiling the answer.
And that left me with ~56k possible values to simulate for part 2 answer
2
u/TheZigerionScammer Dec 17 '21
Python.
This day was really fun! For part one I thought that the maximum velocity would be the top minus the bottom for the Y direction but this turned out not to be the case, as I realized that the Y position will always return to zero on a step since it follows a parabolic arc, so the real maximum velocity is zero minus the bottom. After that, aside form my input, part 1 took two lines as the max height was just the triagonal number of the max velocity.
For part 2 I thought that since the Y position and X position are independent, I could just figure out the number of possible y values and number of possible x values and multiply them together, but then I thought that there would be edge cases that wouldn't be valid when paired together, dropping too fast on Y for X to reach it, etc. So I said "screw it" and tested all of the reasonable numbers together brute force style. After that it was just crushing bugs (including a nasty one where I assumed that the second Y value would be the limit where I should stop checking if the Y value went beyond it, it was the first.)
Paste
2
u/OrangeredStilton Dec 17 '21
Python3, your old friend bruteforce coming to play again...
2
u/encse Dec 17 '21
C#, That's a good one: https://github.com/encse/adventofcode/blob/master/2021/Day17/Solution.cs
2
u/veydar_ Dec 17 '21
Lua
Repository
Rewarding day! Very little code to express the necessary logic compared to yesterday. I simply check all possible velocities with a nested for loop from -500 to 500. Pragmatic, but enough for me.
2
u/DrSkookumChoocher Dec 17 '21 edited Dec 17 '21
Deno TypeScript
https://github.com/N8Brooks/deno_aoc/blob/main/year_2021/day_17.ts
Borrowed the clever math solution for part 1.
I feel like it could be expanded to part 2 as well to find a much more efficient solution. For example using the quadratic formula you can find the minimum x velocity with
Math.ceil((Math.sqrt(8 * x0) - 1) / 2). From there you could find the generally well connected blocks of xv and yvs that reach the target area somehow. Maybe a exponential binary search could be used to find the bounds of these boxes? I'm done for tonight though.Edit: revisited this problem to find a non brute force solution for part 2. Using two pointers this can be done. Thereβs still somewhat of a brute force element when it searches for a new left bound. Runs in ~10ms which as fast as it gets with the testing framework Iβm using.
If anyone has problem input and answer with nonnegative y can you send it to me? I want to see if this would still work.
2
u/francescored94 Dec 17 '21
Nim solution
2
u/Melocactus283 Dec 17 '21
R / Rlang .
Part 2 is slow, but I don't feel like optimizing for speed after yesterday's pain.
2
u/ethsgo Dec 17 '21
Solidity and Javascript - https://github.com/ethsgo/aoc
A preview
2
u/chkas Dec 17 '21
easylang
Solution
2
u/tomribbens Dec 17 '21
My solutions as per usual at my Github
I brute forced it, nothing special here I think.
2
u/GaloisGirl2 Dec 17 '21
COBOL brute force.
2
u/ragnar-brauner Dec 17 '21
Golang
brute forced my way through the positions..
2
u/BeamMeUpBiscotti Dec 17 '21
ReScript code
Simple brute force solution was adequate since the search space was very small.
Done completely sans mutable state using nested reduce operations and and recursion. Simulation code is a great use case for immutability since destructive state updates make code harder to reason about and debug, but in this case it was simple enough not to matter alot.
2
u/FordyO_o Dec 17 '21
Spent way too long today trying to work out why I was getting stupidly high results for the example in part 2, turns out I had written 10 instead of -10 :|
PHP
2
u/Static-State-2855 Dec 17 '21
Python 3. Part 1 is trivial. It's essentially the triangular number of the deepest y value.
Part 2 is easy enough to brute force. Again, not quite optimal, but it works.
I basically search for any points which are in both the trajectory and the target area:
Iterate this over all possible velocities, and then add them up.
2
u/karjonas Dec 17 '21
Rust GitHub
2
u/levital Dec 17 '21
Haskell
Meh, didn't enjoy this too much. Didn't have a good idea how to even approach this and so ended up just brute-forcing it, without even figuring out a good upper bound for the initial y-trajectory. Just chose 3000 and figured that's probably enough. Runtime is obviously terrible, and it really needs to be compiled with optimizations turned on. But at least I got part 2 for free...
2
u/[deleted] Dec 17 '21
Haskell, fairly readable code today I think
2
u/landimatte Dec 17 '21
Common Lisp
Like everybody else: bruteforce!
For the horizontal speed, I start from
x=0withv=0and keep on accelerating until I get in-range; this will be my the minimum horizontal speed to get on target; for the max one on the other end, I simply used the biggestxvalue of the target area -- starting form0, any value bigger than that, will miss the target.For the vertical speed instead I picked the smallest
yvalue of the target area (multiplied by-1of course); this represents the maximum vertical speed to get on target without overshooting; for the min one instead, I simply used its opposite value (that's because we have the gravity: if you shoot up, after some time, the probe will be back toy=0with vertical speed opposite in value of when it started).Once you have the ranges, the bruteforce is quite easy to implement:
Anyways, this was a fun one!
2
u/[deleted] Dec 17 '21
Nim
Today's task was quite a bit quicker for me than yesterday's, this works very well with nim, and using options in at the right times just are really nice for giving over values :)
I was thinking about nice ways to calculating the velocities at first, but brutforce just works really well with this :p
I keep on being impressed over how nice nim is to work with :)
https://github.com/sotolf2/aoc2021/blob/main/day17.nim
2
u/vulpine-linguist Dec 17 '21
AWK
Carries an unwritten assumption that target y-values be negative and target x-values be positive. Iterates over y-velocities, finding time-steps in which the probe will be in the target y-area. Then within these time-ranges, computes x-values to see if they are also in the target.
I'm sure there's a better method, but this runs in 95ms which feels vaguely fine for AWK.
2
u/AeroFlorian Dec 17 '21
My Python3 solution
I brute forced it :(
2
u/Dullstar Dec 17 '21
Python
Today I spent an hour or two trying to figure out why Part 2 passed the test input but not the example only for it to turn out that the regex I used to read the file was missing a +, resulting in one of the fields being read in with only 1 digit. In the example, that field was 1 digit, so it worked. But Part 1's answer wasn't affected by this missing digit, so that was... an adventure.
Like many others, it's a brute force approach, which is adequate for this problem. X and Y get treated independently to rule out values that will never work (some values will always overshoot, and some x values will always undershoot - once we've identified those values we don't need to try any x, y combinations with them), then the ones that could potentially work are tested together.
2
u/semicolonator Dec 17 '21
Python, 18 lines
2
u/piyushrungta Dec 17 '21
Nim
https://github.com/piyushrungta25/advent-of-code-2021/blob/master/day-17/main.nim
Was able to get the part1 without code but wrote bruteforce solution for part2, then added a variable to track maximum y we see for viable candidates. Can definitely reduce the search space for part2 but it is small enough as is.
2
u/wasi0013 Dec 17 '21
Elixir
Part 1 can be solved using a simple formula:
y2021/day_17.ex
2
u/MarcoDelmastro Dec 17 '21
Python
(brute force because life is short and I do real physics for a living)
https://github.com/marcodelmastro/AdventOfCode2021/blob/main/Day17.ipynb
2
u/mariushm Dec 17 '21
PHP
Here's my PHP solution : https://github.com/mariush-github/adventofcode2021/blob/main/17.php
2
u/supaman_dat_ho Dec 17 '21
Python brute force, part 2:
https://pastecode.io/s/2o7o3iky
2
u/mathsaey Dec 17 '21
Elixir
https://github.com/mathsaey/adventofcode/blob/master/lib/2021/17.ex
Figured I should figure out the math instead of brute forcing it. Took me than it should have and more googling for basic things then I care to admit, but I got there in the end.
Added a bunch of comments so I can still get how this works tomorrow, and so that people can point out my inevitable mistakes :).
2
u/iamflimflam1 Dec 17 '21
Typescript
Brute force like most people I think - kept wondering if there was going to be some horrible gotcha that meant brute force would not work, but it did.
2
u/e4ds Dec 17 '21
Python day 17 solution (GitHub). Not the fewest lines of code, but used dataclasses and modular functions to try improve readability -- I got very confused with keeping track of indices of velocities vs coordinates in other people's posted solutions. I find dataclasses in Python can be a great way to be descriptive about the quantities you are iterating