Skip to content

Instantly share code, notes, and snippets.

@kracekumar
Last active December 22, 2025 21:08
Show Gist options
  • Select an option

  • Save kracekumar/e3acbf021ef3fce77524e5a793d545f6 to your computer and use it in GitHub Desktop.

Select an option

Save kracekumar/e3acbf021ef3fce77524e5a793d545f6 to your computer and use it in GitHub Desktop.
An alternating array is a list of any length in which two (not necessarily different) values are alternating (all even-indexed items are equal, and all odd-indexed items are equal). Given an array, return true if it is alternating. Examples -------- [] -> True [1] -> True [1,1] -> True [1,2,1] -> True [10,5,10,5,10] -> True [2,2,3,3] -> False [5…
defmodule AlternatingArray do
@moduledoc """
An alternating array is a list of any length in which two (not necessarily different)
values are alternating (all even-indexed items are equal, and all odd-indexed items are equal).
Given an array, return true if it is alternating.
Examples
--------
[] -> True
[1] -> True
[1,1] -> True
[1,2,1] -> True
[10,5,10,5,10] -> True
[2,2,3,3] -> False
[5,4,3,5,4,3] -> False
Link: https://buttondown.com/cassidoo/archive/you-only-get-one-life-so-you-might-as-well-feel/
"""
def is_alternating(arr) do
check_positions(arr, 0)
end
defp check_positions([], _index), do: true
defp check_positions([_], _index), do: true
defp check_positions([_first, _second], _index), do: true
defp check_positions([first, second, third | rest], index) do
if first == third do
check_positions([second, third | rest], index + 1)
else
false
end
end
end
test_cases = [
{[], true},
{[1], true},
{[1, 1], true},
{[1, 2, 1], true},
{[10, 5, 10, 5, 10], true},
{[2, 2, 3, 3], false},
{[5, 4, 3, 5, 4, 3], false}
]
Enum.each(test_cases, fn {arr, expected} ->
result = AlternatingArray.is_alternating(arr)
passed = result == expected
IO.inspect("Array: #{inspect(arr)}, Expected: #{expected}, Got: #{result}, Passed: #{passed}")
end)
$iex alternate_array.ex
Erlang/OTP 27 [erts-15.2.6] [source] [64-bit] [smp:10:10] [ds:10:10:10] [async-threads:1] [jit] [dtrace]
"Array: [], Expected: true, Got: true, Passed: true"
"Array: [1], Expected: true, Got: true, Passed: true"
"Array: [1, 1], Expected: true, Got: true, Passed: true"
"Array: [1, 2, 1], Expected: true, Got: true, Passed: true"
"Array: [10, 5, 10, 5, 10], Expected: true, Got: true, Passed: true"
"Array: [2, 2, 3, 3], Expected: false, Got: false, Passed: true"
"Array: [5, 4, 3, 5, 4, 3], Expected: false, Got: false, Passed: true"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment