Exercises
Modules and Functions - Sum
Write functions sum(n)
that uses recursion to calculate the sum of integers from 1 to n.
defmodule Recursive do
def sum(_n) do
# Your code here
end
end
1 = Recursive.sum(1)
6 = Recursive.sum(3)
10 = Recursive.sum(4)
FizzBuzz
Write a function that returns the numbers from 1 to n
. But for multiples of:
-
three replaces a number with an atom
:fizz
instead of the number -
five replaces a number with an atom
:buzz
-
both three and five replaces a number with an atom
:fizzbuzz
.
Tip: see How to use div/2 and/or rem/2?
defmodule FizzBuzz do
def fizzbuzz(_n) do
# Your code here
end
end
[] = FizzBuzz.fizzbuzz(0)
[1] = FizzBuzz.fizzbuzz(1)
[1, 2] = FizzBuzz.fizzbuzz(2)
[1, 2, :fizz] = FizzBuzz.fizzbuzz(3)
[
1,
2,
:fizz,
4,
:buzz,
:fizz,
7,
8,
:fizz,
:buzz,
11,
:fizz,
13,
14,
:fizzbuzz,
16,
17,
:fizz,
19,
:buzz,
:fizz,
22,
23,
:fizz,
:buzz,
26,
:fizz,
28,
29,
:fizzbuzz,
31
] = FizzBuzz.fizzbuzz(31)
Scrabble Score
Given a word, compute the Scrabble score of that word.
Letter Values
Letter | Value |
---|---|
A, E, I, O, U, L, N, R, S, T | 1 |
D, G | 2 |
B, C, M, P | 3 |
F, H, V, W, Y | 4 |
K | 5 |
J, X | 8 |
Q, Z | 10 |
Tip: You may find String.graphemes/1 useful.
defmodule Scrabble do
def calculate_score(_word) do
# Your code here
end
end
13 = Scrabble.calculate_score("elixir")
2 = Scrabble.calculate_score("is")
6 = Scrabble.calculate_score("fun")