Created
November 15, 2018 06:51
-
-
Save fay-jai/fd6f2940edb4014e64c7e29d3e57a0d6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# FizzBuzz - Write a program that prints the numbers from 1 to 100. But for multiples of 3, print "Fizz" instead of the number and for the multiples of 5, print "Buzz". For numbers which are multiples of both 3 and 5, print "FizzBuzz". | |
# First, the JavaScript implementation | |
const fizzBuzz = (num) => { | |
if (num % 3 === 0 && num % 5 === 0) return "FizzBuzz"; | |
if (num % 3 === 0) return "Fizz"; | |
if (num % 5 === 0) return "Buzz"; | |
return num; | |
}; | |
const range = (num) => [ ...Array(num).keys() ].map(num => num + 1); # This helper function simply creates an array of numbers - i.e range(100) == [1, 2, 3, ..., 100] | |
console.log(range(100).map(fizzBuzz)); | |
# Next, the Elixir implementation | |
fizz_buzz_result = fn | |
(0, 0, _) -> "FizzBuzz" | |
(0, _, _) -> "Fizz" | |
(_, 0, _) -> "Buzz" | |
(_, _, num) -> num | |
end | |
fizz_buzz = fn (num) -> fizz_buzz_result.(rem(num, 3), rem(num, 5), num) end | |
IO.puts(Enum.map(1..100, fizz_buzz)) | |
# I think one of the most interesting aspects of the Elixir implementation is that there is NO conditional logic involved. | |
# Instead of using `if / else` logic, Elixir takes advantage of pattern matching and multiple clauses to produce the same effect! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment