Elixir Stone Blocks
defmodule StoneBlocks do
def stone_blocks(h) do
{_stack, blocks} =
Enum.reduce(h, {[], 0}, fn height, {stack, blocks} ->
stack = Enum.drop_while(stack, &(&1 > height))
case stack do
[^height | _] -> {stack, blocks}
_ -> {[height | stack], blocks + 1}
end
end)
blocks
end
end
This uses a stack of active heights and only counts a new block when the wall needs a new height segment.
Elixir Tape Equilibrium
defmodule TapeEquilibrium do
def tape_equilibrium(a) do
total = Enum.sum(a)
size = length(a)
{_first, _second, min} =
Enum.reduce(0..(size - 2)//1, {0, total, :infinity}, fn i, {first, second, min} ->
first = first + i
second = second - i
diff = abs(first - second)
min = if min == :infinity or diff < min, do: diff, else: min
{first, second, min}
end)
min
end
end
This keeps left and right running sums and updates the smallest difference at each split point.
Elixir Triangle
defmodule Triangle do
def triangle(a) when length(a) < 3, do: 0
def triangle(a) do
sorted = Enum.sort(a)
c = length(sorted)
found =
Enum.any?(0..(c - 3), fn i ->
v = Enum.at(sorted, i)
v > 0 and v > Enum.at(sorted, i + 2) - Enum.at(sorted, i + 1)
end)
if found, do: 1, else: 0
end
end
This sorts the values and checks nearby triples, because a valid triangle only needs one local match after sorting.