Skip to content

Instantly share code, notes, and snippets.

@dhalai
Created December 14, 2016 08:10
Show Gist options
  • Save dhalai/dd436feab35cebbc66a48e8d6d8e1769 to your computer and use it in GitHub Desktop.
Save dhalai/dd436feab35cebbc66a48e8d6d8e1769 to your computer and use it in GitHub Desktop.
defmodule Inversion do
def run(filename) do
{sorted, count} = File.read!(filename)
|> String.split("\r\n", trim: true)
|> Enum.map(fn(x) -> String.to_integer(x) end)
|> devide_and_conquer
count
end
defp devide_and_conquer(data) do
case data do
[] -> {[], 0}
[x] -> {[x], 0}
[x,y] when x > y -> {[y,x], 1}
[x,y] when x <= y -> {[x,y], 0}
list ->
count = length(list)
half_index = div(count, 2)
{sorted_x, x} = devide_and_conquer(Enum.slice(list, (0..half_index-1)))
{sorted_y, y} = devide_and_conquer(Enum.slice(list, half_index..count-1))
{sorted_z, z} = merge(sorted_x, sorted_y, [], 0)
{Enum.reverse(sorted_z), x + y + z}
end
end
defp merge(a, b, acc_list, acc_inversions) do
case {a, b} do
{[], []} -> {acc_list, acc_inversions}
{a, []} -> {Enum.reverse(a) ++ acc_list, acc_inversions}
{[], b} -> {Enum.reverse(b) ++ acc_list, acc_inversions}
{a, b} when hd(a) > hd(b) -> merge(a, tl(b), [hd(b) | acc_list], length(a) + acc_inversions)
{a, b} when hd(a) <= hd(b) -> merge(tl(a), b, [hd(a) | acc_list], acc_inversions)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment