Skip to content

Instantly share code, notes, and snippets.

@qhwa
Created August 15, 2021 23:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qhwa/1d3f5c4a41bb41fb6d26d7e596806377 to your computer and use it in GitHub Desktop.
Save qhwa/1d3f5c4a41bb41fb6d26d7e596806377 to your computer and use it in GitHub Desktop.
Sum of owest two numbers
defmodule TwoLowest do
def sum_of_two_lowest(numbers) do
numbers
|> lowest_two()
|> IO.inspect(label: :lowest_two)
|> sum()
|> IO.inspect(label: :sum)
end
defp lowest_two(numbers, found \\ [])
# If we reach the end, return what we have found
defp lowest_two([], found),
do: found
# This is at the beginning of the recursion when
# we have not found anything
defp lowest_two([n | rest], []),
do: lowest_two(rest, [n])
# When we have already found one, we put the
# number at cursor into the right place,
# keeping the `found` in an asc order, which
# means the first element of `found` is always
# less.
defp lowest_two([n | rest], [x]) when n >= x,
do: lowest_two(rest, [x, n])
defp lowest_two([n | rest], [x]) when n < x,
do: lowest_two(rest, [n, x])
# If we have already found two low numbers,
# we compare the current cursor number to
# what we have found. Keeping the `found`
# as the lowest two of `[x, y, n]` and the
# asc order.
defp lowest_two([n | rest], [x, _y]) when n < x,
do: lowest_two(rest, [n, x])
defp lowest_two([n | rest], [x, y]) when n < y,
do: lowest_two(rest, [x, n])
# If n is greater than y (hence x), we ignore
# it and move on.
defp lowest_two([_n | rest], [x, y]),
do: lowest_two(rest, [x, y])
defp sum([]), do: 0
defp sum([n | rest]), do: n + sum(rest)
end
TwoLowest.sum_of_two_lowest([10, 343_445_353, 3_453_445, 3_453_545_353_453])
TwoLowest.sum_of_two_lowest([19, 5, 42, 2, 77])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment