Published at Jul 13 2018
·
0 comments

Instructions

Test suite

Solution

Parse and evaluate simple math word problems returning the answer as an integer.

Add two numbers together.

What is 5 plus 13?

Evaluates to 18.

Handle large numbers and negative numbers.

Now, perform the other three operations.

What is 7 minus 5?

2

What is 6 multiplied by 4?

24

What is 25 divided by 5?

5

Handle a set of operations, in sequence.

Since these are verbal word problems, evaluate the expression from
left-to-right, *ignoring the typical order of operations.*

What is 5 plus 13 plus 6?

24

What is 3 plus 2 multiplied by 3?

15 (i.e. not 9)

If you'd like, handle exponentials.

What is 2 raised to the 5th power?

32

Execute the tests with:

```
$ elixir wordy_test.exs
```

In the test suites, all but the first test have been skipped.

Once you get a test passing, you can unskip the next one by
commenting out the relevant `@tag :pending`

with a `#`

symbol.

For example:

```
# @tag :pending
test "shouting" do
assert Bob.hey("WATCH OUT!") == "Whoa, chill out!"
end
```

Or, you can enable all the tests by commenting out the
`ExUnit.configure`

line in the test suite.

```
# ExUnit.configure exclude: :pending, trace: true
```

For more detailed information about the Elixir track, please see the help page.

Inspired by one of the generated questions in the Extreme Startup game. https://github.com/rchatley/extreme_startup

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

```
if !System.get_env("EXERCISM_TEST_EXAMPLES") do
Code.load_file("wordy.exs", __DIR__)
end
ExUnit.start()
ExUnit.configure(exclude: :pending, trace: true)
defmodule WordyTest do
use ExUnit.Case
test "addition" do
assert Wordy.answer("What is 1 plus 1?") == 2
end
@tag :pending
test "more addition" do
assert Wordy.answer("What is 53 plus 2?") == 55
end
@tag :pending
test "addition with negative numbers" do
assert Wordy.answer("What is -1 plus -10?") == -11
end
@tag :pending
test "large addition" do
assert Wordy.answer("What is 123 plus 45678?") == 45801
end
@tag :pending
test "subtraction" do
assert Wordy.answer("What is 4 minus -12?") == 16
end
@tag :pending
test "multiplication" do
assert Wordy.answer("What is -3 multiplied by 25?") == -75
end
@tag :pending
test "division" do
assert Wordy.answer("What is 33 divided by -3?") == -11
end
@tag :pending
test "multiple additions" do
assert Wordy.answer("What is 1 plus 1 plus 1?") == 3
end
@tag :pending
test "addition and subtraction" do
assert Wordy.answer("What is 1 plus 5 minus -2?") == 8
end
@tag :pending
test "multiple subtraction" do
assert Wordy.answer("What is 20 minus 4 minus 13?") == 3
end
@tag :pending
test "subtraction then addition" do
assert Wordy.answer("What is 17 minus 6 plus 3?") == 14
end
@tag :pending
test "multiple multiplication" do
assert Wordy.answer("What is 2 multiplied by -2 multiplied by 3?") == -12
end
@tag :pending
test "addition and multiplication" do
assert Wordy.answer("What is -3 plus 7 multiplied by -2?") == -8
end
@tag :pending
test "multiple division" do
assert Wordy.answer("What is -12 divided by 2 divided by -3?") == 2
end
@tag :pending
test "unknown operation" do
assert_raise ArgumentError, fn ->
Wordy.answer("What is 52 cubed?")
end
end
@tag :pending
test "Non math question" do
assert_raise ArgumentError, fn ->
Wordy.answer("Who is the President of the United States?")
end
end
end
```

```
defmodule Wordy do
@doc """
Calculate the math problem in the sentence.
"""
@spec answer(String.t) :: integer
def answer(question) do
# scan for hits composed of:
# any string of non-digits (and stash it), a space,
# and an optional minus sign followed by digits (and stash it and them).
# at this point we're not bothering to validate the non-number part.
pieces = Regex.scan(~r/([^\d]*) (-?\d+)/, question)
# if we got no hits, or there is more (or less!) left over than a "?",
# then the question is malformed. it may be malformed in other ways,
# that will raise no-matching-clause errors below.
if pieces == nil || remove_pieces(pieces, question) != "?" do
raise ArgumentError
end
fixed = pieces |> Enum.map(&fixup/1)
do_answer(fixed, nil)
end
defp remove_pieces([[whole_hit|_]|more], question) do
remove_pieces(more, question |> String.replace(whole_hit, ""))
end
defp remove_pieces([], question), do: question
# match on nil means it must be the very first thing.
# anything else as first thing will also produce error
# when we try to do math with it in the other defps.
defp do_answer([["What is"|[number]]|more], nil) do
do_answer(more, number)
end
defp do_answer([["plus"|[number]]|more], acc) do
do_answer(more, acc + number)
end
defp do_answer([["minus"|[number]]|more], acc) do
do_answer(more, acc - number)
end
defp do_answer([["multiplied by"|[number]]|more], acc) do
do_answer(more, acc * number)
end
defp do_answer([["divided by"|[number]]|more], acc) do
do_answer(more, acc / number)
end
defp do_answer([], acc), do: acc
defp do_answer(_, _), do: raise ArgumentError
defp fixup([_|[words|[number]]]) do
[String.trim(words), String.to_integer(number)]
end
end
```

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

- What compromises have been made?
- Are there new concepts here that you could read more about to improve your understanding?

Level up your programming skills with 3,107 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments