0

We can represent the probabilities using a line. The line length can correspond to the likelihood metric of each route. The metric values have been added for each point to represent all of the probabilities on the same line.

On a number line, make marks at arr[0], arr[0] + arr[1], arr[0] + arr[1] + arr[2], ...., arr[0] + arr[1] + … arr[n-1]. This results in n line segments each corresponding to one of the entries in the array. Let the last mark be at a value k. Now, if we draw a random value between 0 and k, it will lie on one of these line segments. If the random value lies on the ith line segment, we’ll say that the ith array value has been picked. The likelihood of a random value between 0 and k falling on a specific line segment depends on the length of the line segment, which equals the value of the corresponding array element. This means that we have picked an array element using probability determined by its value.

Each point on this prob line is a running sum of all the previous numbers in the metric array plus the current number itself. Our running sum array is sorted as it is increasing, so we only need to fit the random value in this sorted array. Wherever our random number gets fitted, we can return the index that represents our chosen route.

Here is how the implementation will take place:

Generate an array of running sums from the given array of metrics in the constructor so that we don’t have to compute it again at every call.

The largest number of the running sums array will give us the range for generating the random number.

Create a pick_route() method that will find and return the index value.

Generate a random number between 0 and k.

Use binary search to find the index of the first running sum that is greater than the random value.

Return the index so we can choose the route associated with it.

Let’s look at the code for the solution:

Source: Grepper

Continue with Google

By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.

Grepper Account Login Required