Is there a better way to swap elements in a list?
Any inbuilt function or a library?
defmodule SwapElements do
def swap(list, first_index, second_index) do
{a, b} = split(list, first_index + 1)
{x, y} = split(b, second_index - first_index)
[h1 | t1] = a
[h2 | t2] = x
y
|> reverse_append([h1])
|> reverse_append(t2)
|> reverse_append([h2])
|> reverse_append(t1)
end
def split(list, n) do
split([], list, n)
end
def split(a, b, 0) do
{a, b}
end
def split(list, [h|t], n) do
split([h | list], t, n - 1)
end
def reverse_append(list, []) do
list
end
def reverse_append(list, [h | t]) do
reverse_append([h | list], t)
end
end
iex(27)> SwapElements.swap(Enum.to_list(0..10), 1, 4)
[0, 4, 2, 3, 1, 5, 6, 7, 8, 9, 10]