KitchenSink v1.1.0 KitchenSink.Algorithms View Source

This is a collection of algorithms.

The binary search fit function

The search is controlled by the fit function which is passed the value to test and returns :ok if the value is good enough, :high if the next value to test should be higher, or :low if the next value should be lower.

Link to this section Summary

Link to this section Types

Link to this type binary_interval_search_fit_func() View Source
binary_interval_search_fit_func() :: (binary_interval_search_position, any -> :ok | :high | :low)
Link to this type binary_interval_search_position() View Source
binary_interval_search_position() :: number
Link to this type binary_search_fit_func() View Source
binary_search_fit_func() :: (binary_search_position, any -> :ok | :high | :low)
Link to this type binary_search_position() View Source
binary_search_position() :: integer
Link to this type binary_search_result() View Source
binary_search_result() :: {:ok, binary_search_position} | :not_found

Link to this section Functions

Link to this function binary_interval_search(interval_start, interval_finish, fit, target \\ nil) View Source

binary_interval_search can search in an interval.

Examples

To see where y = 10 + x³ and y = 1000 + x² intersect

iex> solve = fn(position, _) ->
...>   y1 = 10 + :math.pow(position, 3)
...>   y2 = 1000 + :math.pow(position, 2)
...>   difference = y1 - y2
...>
...>   epsilon = 0.0001
...>
...>   cond do
...>     abs(difference) < epsilon -> :ok
...>     difference > 0.0 -> :low
...>     difference < 0.0 -> :high
...>   end
...> end
iex>
iex> {:ok, result} = Algorithms.binary_interval_search(1, 100, solve, 0.0)
iex> Float.round(result, 6)
10.311285
Link to this function binary_search(range_start, range_finish, fit, target, calculate_mid \\ &binary_search_midpoint/2) View Source

binary_search performs a binary search over a range.

Examples

iex> names = ~w(Adrian Bill Robert Tony) # Sorted!
iex> search_names = fn(position, target) ->
...>   current = Enum.at(names, position)
...>   cond do
...>     current < target -> :high
...>     current == target -> :ok
...>     current > target -> :low
...>   end
...> end
iex>
iex> Algorithms.binary_search(0, 3, search_names, "Tony")
{:ok, 3}
iex> Algorithms.binary_search(0, 3, search_names, "Phil")
:not_found

It is possible to override the calculation of the midpoint for the binary search, and that is “…left as an exercise for the reader.”