Created
July 18, 2016 09:28
-
-
Save sashang/91ead48d2a5c51103279600c8759112b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Inversion do | |
def summarize(a, b, acc, list_acc) do | |
case {a, b} do | |
{[], []} -> {list_acc, acc} | |
{a, []} -> {list_acc ++ a, acc} | |
{[], b} -> {list_acc ++ b, acc} | |
{a,b} when hd(a) > hd(b) -> summarize(a, tl(b), length(a) + acc, list_acc ++ [hd(b)]) | |
{a,b} when hd(a) <= hd(b) -> summarize(tl(a), b, acc, list_acc ++ [hd(a)]) | |
end | |
end | |
def count_inversion(a) do | |
case a do | |
[] -> {[], 0} | |
[x] -> {[x], 0} | |
[x,y] when x > y -> {[y,x], 1} | |
[x,y] when x <= y -> {[x,y], 0} | |
a -> | |
n = length(a) | |
half = div(n, 2) | |
{sorted_b, x} = count_inversion(Enum.slice(a, (0 .. half-1))) | |
{sorted_c, y} = count_inversion(Enum.slice(a, half..n-1)) | |
{sorted_a, z} = summarize(sorted_b, sorted_c, 0, []) | |
{sorted_a, x + y + z} | |
end | |
end | |
def read(filename) do | |
data = File.read!(filename) | |
l = String.split(String.trim(data), "\n") | |
l = Enum.map(l, fn(x) -> String.to_integer(x) end) | |
{sorted, ans} = count_inversion(l) | |
ans | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment