Introduction
In Day 17 brings us some physics simulation of free-falling probe that has some initial velocity. Our goal is to properly write the rules of the described world and look at the statistics from the simulations to get the problem solution. Let’s see how we can deal with it in Kotlin and why immutability rocks when performing some data transformations.
Solution
We create the representation of current state of the world and use it as immutable data in simulation -
named State
. It’s the most common approach to create some function in immutable class that returns
this state after transformation as new object. The step
method does all of this by transforming
some state to another, according to described rules in the problem.
We run the simulation for the whole range of initial velocities that makes sense to do. They are limited, as target area is limited and time in our problem is discrete, so we have to worry only about the situations, in which we have a chance to hit target area. The key observation here is
The probe has no chance of hitting target area iff after single second it missed this area and is behind it.
As we know that after the first second the probe will be at distance $(v_x, v_y)$, we can set the ranges for initial velocities to be smaller than the distances to target are, to make sure that we checked all reasonable states in our simulations.
Day17.kt
|
|
Extra notes
Notice how do we store the history of State
locations with some list structure. It’s important to use
List<T>
instead of MutableList<T>
to make sure that the State
is effectively immutable. That’s one
of the rules that we have to always remember - all the fields of immutable classes have to be immutable,
not only final.
It’s worth noticing that some cool properties from kotlin.math
were used in presented solution. We have
used the sign
value of number to simulate the drag on the probe with simple expression. Additionally, the
absoluteValue
property was used to calculate the actual range of searching for our simulation.