Skip to content

Instantly share code, notes, and snippets.

@andeemarks
Created February 24, 2018 04:01
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 andeemarks/332b2e7a78f87d95053ca2c904e0699a to your computer and use it in GitHub Desktop.
Save andeemarks/332b2e7a78f87d95053ca2c904e0699a to your computer and use it in GitHub Desktop.
Exercises from Day 1 of Elixir from 7 More Languages in 7 Days
defmodule Day1 do
def hypotenuse(side1, side2) do
:math.sqrt((side1 * side1) + (side2 * side2))
end
def word_count(atom_list), do: word_count(atom_list, %{})
def word_count([], map_of_atom_counts), do: map_of_atom_counts
def word_count([head|tail], map_of_atom_counts) do
word_count(tail, Map.put(map_of_atom_counts, head, Map.get(map_of_atom_counts, head, 0) + 1))
end
def list_stats([]), do: %{:size => 0, :max => 0, :min => 0}
def list_stats(num_list) do list_stats(num_list, %{:size => 0, :max => 0, :min => 0}) end
def list_stats([], stats), do: stats
def list_stats([head|tail], stats) do
new_min = if head < Map.get(stats, :min), do: head, else: Map.get(stats, :min)
new_max = if head > Map.get(stats, :max), do: head, else: Map.get(stats, :max)
new_size = Map.get(stats, :size, 0) + 1
list_stats(tail, %{:size => new_size, :max => new_max, :min => new_min})
end
def list_max([]), do: 0
def list_max([head|tail]) do list_max(tail, head) end
def list_max([], current_max), do: current_max
def list_max([head|tail], current_max) do
new_max = if head > current_max, do: head, else: current_max
list_max(tail, new_max)
end
def list_min([]), do: 0
def list_min([head|tail]) do list_min(tail, head) end
def list_min([], current_min), do: current_min
def list_min([head|tail], current_min) do
list_min(tail, (if head < current_min, do: head, else: current_min))
end
def list_length([]), do: 0
def list_length([_|tail]) do
1 + list_length(tail)
end
end
IO.puts Day1.hypotenuse(3, 4)
IO.puts Day1.hypotenuse(1, 1)
IO.puts String.to_atom("atom")
IO.puts is_atom(3)
IO.puts is_atom("hi")
IO.puts is_atom(nil)
IO.puts is_atom("atom")
IO.puts is_atom(:atom)
IO.inspect Day1.word_count([])
IO.inspect Day1.word_count([:first])
IO.inspect Day1.word_count([:first, :second, :third])
IO.inspect Day1.word_count([:first, :second, :second, :third])
IO.puts Day1.list_length([1, 2, 3, 4, 5, 4, 3, 2, 1])
IO.puts Day1.list_length([])
IO.puts Day1.list_max([1, 2, 3, 4, 5, 4, 3, 2, 1])
IO.puts Day1.list_max([1, 1, 0])
IO.puts Day1.list_max([])
IO.puts Day1.list_min([1, 2, 3, 4, 5, 4, 3, 2, 1])
IO.puts Day1.list_min([1, 1, 0])
IO.puts Day1.list_min([])
IO.inspect Day1.list_stats([1, 2, 3, 4, 5, 4, 3, 2, 1])
IO.inspect Day1.list_stats([1, 1, 0])
IO.inspect Day1.list_stats([])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment