FizzBuzz
Mix.install([
{:jason, "~> 1.4"},
{:kino, "~> 0.9", override: true},
{:youtube, github: "brooklinjazz/youtube"},
{:hidden_cell, github: "brooklinjazz/hidden_cell"}
])
Navigation
Home Report An Issue EnumNamed Number ListsFizzBuzz
In the Elixir cell below create a Module FizzBuzz
with a function run/1
which takes in a range.
Enumerate through the integers and return a new list where
-
integers divisible by
3
are replaced withfizz
-
integers divisible by
5
are replaced withbuzz
-
integers divisible by
3
and5
are replaced withfizzbuzz
- integers not matching the above stay the same.
For example,
FizzBuzz.run(1..15)
[1, 2, "fizz", 4, "buzz", "fizz", 7, 8, "fizz", "buzz", 11, "fizz", 13, 14, "fizzbuzz"]
Example Solution
defmodule FizzBuzz do
def run(range) do
Enum.map(range, fn int ->
cond do
rem(int, 3) == 0 and rem(int, 5) == 0 -> "fizzbuzz"
rem(int, 3) == 0 -> "fizz"
rem(int, 5) == 0 -> "buzz"
true -> int
end
end)
end
end
FizzBuzz.run(1..100)
Enter your solution below.
YouTube.new("https://www.youtube.com/watch?v=QPZ0pIK_wsc&ab_channel=TomScott")
defmodule FizzBuzz do
@doc """
FizzBuzz.
## Examples
iex> FizzBuzz.run(1..15)
[1, 2, "fizz", 4, "buzz", "fizz", 7, 8, "fizz", "buzz", 11, "fizz", 13, 14, "fizzbuzz"]
iex> FizzBuzz.run(10..15)
["buzz", 11, "fizz", 13, 14, "fizzbuzz"]
"""
def run(range) do
Enum.map(range, &do_fizzbuzz/1)
end
defp do_fizzbuzz(n) do
cond do
fizz?(n) && buzz?(n) -> "fizzbuzz"
fizz?(n) -> "fizz"
buzz?(n) -> "buzz"
true -> n
end
end
defp buzz?(n), do: rem(n,5)==0
defp fizz?(n), do: rem(n,3)==0
end
Commit Your Progress
DockYard Academy now recommends you use the latest Release rather than forking or cloning our repository.
Run git status
to ensure there are no undesirable changes.
Then run the following in your command line from the curriculum
folder to commit your progress.
$ git add .
$ git commit -m "finish FizzBuzz exercise"
$ git push
We’re proud to offer our open-source curriculum free of charge for anyone to learn from at their own pace.
We also offer a paid course where you can learn from an instructor alongside a cohort of your peers. We will accept applications for the June-August 2023 cohort soon.