Skip to content

Instantly share code, notes, and snippets.

@pmarreck
Last active December 4, 2021 04:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmarreck/197ffbaded92573571b29137aa573aa8 to your computer and use it in GitHub Desktop.
Save pmarreck/197ffbaded92573571b29137aa573aa8 to your computer and use it in GitHub Desktop.
possible AOC #1 solution in Elixir
defmodule Increases do
def count_increases(string) when is_binary(string) do
string
|> String.split("\n")
|> Enum.map(fn x -> Integer.parse(x) end)
|> Increases.count_increases
end
def count_increases(list) when is_list(list), do: count_increases(list, 0)
def count_increases([a, b | tail], acc) when b > a, do: count_increases([b | tail], acc + 1)
def count_increases([_a, b | tail], acc), do: count_increases([b | tail], acc)
def count_increases(_, acc), do: acc
def count_from_file(filename) when is_binary(filename), do: count_increases(File.read!(filename))
end
# run the inline suite with "elixir #{__ENV__.file} test"
case hd(System.argv) do
"test" ->
ExUnit.start
defmodule IncrementCountTest do
use ExUnit.Case, async: true
test "sanity check" do
test_data = [1, 5, 4, 6, 2, 199, 202, 50, 45, 90]
assert Increases.count_increases(test_data) == 5
end
test "binary input" do
test_data = "1\n5\n4\n6\n2\n199\n202\n50\n45\n90"
assert Increases.count_increases(test_data) == 5
end
end
filename ->
IO.puts(Increases.count_from_file(filename))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment