Skip to content

Instantly share code, notes, and snippets.

@mizhi
Created January 2, 2019 15:54
Show Gist options
  • Select an option

  • Save mizhi/daa58278891b75708f3295741a576fdd to your computer and use it in GitHub Desktop.

Select an option

Save mizhi/daa58278891b75708f3295741a576fdd to your computer and use it in GitHub Desktop.
# Happy New Year! Here are some simple recursion exercises to get the year
# started! These are great questions for someone learning how to code. Try to
# understand exactly what is happening when you solve these.
# *[Ice Cream Shop]*
# Write a function `hasFlavor(flavors, favorite)` that takes in an array of ice
# cream flavors available at the ice cream shop, as well as the user's favorite
# ice cream flavor. *Recursively* find out whether or not the shop offers their
# favorite flavor.
# ```hasFlavor(['vanilla', 'strawberry'], 'blue moon') # => returns false
# hasFlavor(['pistachio', 'green tea', 'chocolate', 'mint chip'], 'green tea') # => returns true
# hasFlavor(['cookies n cream', 'blue moon', 'superman', 'honey lavender', 'sea salt caramel'], 'pistachio') # => returns false
# hasFlavor(['moose tracks'], 'moose tracks') # => returns true
# hasFlavor([], 'honey lavender') # => returns false```
# *[String Reverse]*
# Write a function `reverse(string)` that takes in a string and returns it
# reversed.
#
# ```reverse("house") # => "esuoh"
# reverse("dog") # => "god"
# reverse("atom") # => "mota"
# reverse("q") # => "q"
# reverse("id") # => "di"
# reverse("") # => ""```
defmodule NewYear do
def has_flavor?([], _favorite), do: false
def has_flavor?([first_flavor | other_flavors], favorite) do
(first_flavor == favorite) || has_flavor?(other_flavors, favorite)
end
def reverse(s), do: List.to_string(reverse(String.to_charlist(s), []))
def reverse([], accum), do: accum
def reverse([h|t], accum), do: reverse(t, [h|accum])
end
IO.puts NewYear.has_flavor?([], "chocolate")
IO.puts NewYear.has_flavor?(["chocolate"], "chocolate")
IO.puts NewYear.has_flavor?(["vanilla", "chocolate"], "chocolate")
IO.puts NewYear.has_flavor?(["vanilla", "rocky-road"], "chocolate")
IO.puts NewYear.reverse("")
IO.puts NewYear.reverse("foo")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment