 # binupaul's solution

## to Wordy in the Java Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

#### Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

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

What is 5 plus 13?

Evaluates to 18.

Handle large numbers and negative numbers.

## Iteration 2 — Subtraction, Multiplication and Division

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

## Iteration 3 — Multiple Operations

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)

## Bonus — Exponentials

If you'd like, handle exponentials.

What is 2 raised to the 5th power?

32

# Running the tests

You can run all the tests for an exercise by entering

``````\$ gradle test
``````

## Source

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

## Submitting Incomplete Solutions

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

### WordProblemSolverTest.java

``````import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.Before;
import org.junit.rules.ExpectedException;

import static org.junit.Assert.assertEquals;

public class WordProblemSolverTest {

@Rule
public ExpectedException expectedException = ExpectedException.none();

WordProblemSolver solver;

@Before
public void setup() {
solver = new WordProblemSolver();
}

@Test
assertEquals(2, solver.solve("What is 1 plus 1?"));
}

@Ignore("Remove to run test")
@Test
assertEquals(55, solver.solve("What is 53 plus 2?"));
}

@Ignore("Remove to run test")
@Test
assertEquals(-11, solver.solve("What is -1 plus -10?"));
}

@Ignore("Remove to run test")
@Test
assertEquals(45801, solver.solve("What is 123 plus 45678?"));
}

@Ignore("Remove to run test")
@Test
public void testSingleSubtraction() {
assertEquals(16, solver.solve("What is 4 minus -12?"));
}

@Ignore("Remove to run test")
@Test
public void testSingleMultiplication() {
assertEquals(-75, solver.solve("What is -3 multiplied by 25?"));
}

@Ignore("Remove to run test")
@Test
public void testSingleDivision() {
assertEquals(-11, solver.solve("What is 33 divided by -3?"));
}

@Ignore("Remove to run test")
@Test
assertEquals(3, solver.solve("What is 1 plus 1 plus 1?"));
}

@Ignore("Remove to run test")
@Test
assertEquals(8, solver.solve("What is 1 plus 5 minus -2?"));
}

@Ignore("Remove to run test")
@Test
public void testMultipleSubtractions() {
assertEquals(3, solver.solve("What is 20 minus 4 minus 13?"));
}

@Ignore("Remove to run test")
@Test
assertEquals(14, solver.solve("What is 17 minus 6 plus 3?"));
}

@Ignore("Remove to run test")
@Test
public void testMultipleMultiplications() {
assertEquals(-12, solver.solve("What is 2 multiplied by -2 multiplied by 3?"));
}

@Ignore("Remove to run test")
@Test
assertEquals(-8, solver.solve("What is -3 plus 7 multiplied by -2?"));
}

@Ignore("Remove to run test")
@Test
public void testMultipleDivisions() {
assertEquals(2, solver.solve("What is -12 divided by 2 divided by -3?"));
}

@Ignore("Remove to run test")
@Test
public void testUnknownOperation() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("I'm sorry, I don't understand the question!");

solver.solve("What is 52 cubed?");
}

@Ignore("Remove to run test")
@Test
public void testInvalidQuestionFormat() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("I'm sorry, I don't understand the question!");

// See https://en.wikipedia.org/wiki/President_of_the_United_States if you really need to know!
solver.solve("Who is the President of the United States?");
}

}``````
``````import java.util.ArrayList;
import java.util.List;

public class WordProblemSolver {

public int solve(String input) {
int currentResult = 0;
List<Token> tokens = getTokens(input);
TokenType expected = TokenType.QUESTION;
TokenType previous = null;

for (int i = 0; i < tokens.size(); i++) {
Token token = tokens.get(i);
if (token.type != expected) {
doException();
}

switch (token.type) {
case QUESTION:
expected = TokenType.OPERAND;
previous = TokenType.QUESTION;
break;
case OPERATOR:
expected = TokenType.OPERAND;
previous = TokenType.OPERATOR;
break;
case OPERAND:
if (previous == TokenType.QUESTION) {
currentResult = Integer.parseInt(token.value);
} else if (previous == TokenType.OPERATOR) {
currentResult = eval(token, tokens.get(i - 1), currentResult);
}

if (i == tokens.size() - 2) {
expected = TokenType.END;
} else {
expected = TokenType.OPERATOR;
}
previous = TokenType.OPERAND;
break;
case END:
break;
}
}
return currentResult;
}

public class Token {
public TokenType type;
public String value;
public int nextIndex;
}

public enum TokenType {
QUESTION,
OPERATOR,
OPERAND,
END
}

public List<Token> getTokens(String input) {
List<Token> tokens = new ArrayList<>();

String[] words = input.split("\\s+|\\?{1}\$");
int current = 0;
while (current < words.length) {
Token token = new Token();
if (isQuestion(current, words, token) ||
isOperand(current, words, token) ||
isOperator(current, words, token)) {
current = token.nextIndex;
} else {
doException();
}
}

if (input.endsWith("?")) {
Token token = new Token();
token.type = TokenType.END;
} else {
doException();
}
}

private boolean isQuestion(int current, String[] words, Token token) {
if ((current + 1 < words.length) &&
(words[current].equalsIgnoreCase("What")) &&
(words[current + 1].equals("is"))) {
token.nextIndex = current + 2;
token.type = TokenType.QUESTION;
return true;
}
return false;
}

private boolean isOperand(int current, String[] words, Token token) {
String word = words[current];
boolean negative = false;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (ch == '-' && i == 0) {
negative = true;
continue;
}
if (ch < '0' || ch > '9') {
return false;
}
}

if (negative && word.length() == 1) {
return false;
}
token.nextIndex = current + 1;
token.type = TokenType.OPERAND;
token.value = word;
return true;
}

private boolean isOperator(int current, String[] words, Token token) {
String word = words[current];
if (word.equals("plus")) {
token.nextIndex = current + 1;
token.type = TokenType.OPERATOR;
token.value = "+";
return true;
} else if (word.equals("minus")) {
token.nextIndex = current + 1;
token.type = TokenType.OPERATOR;
token.value = "-";
return true;
} else if (current + 1 < words.length) {
if (word.equals("multiplied") &&
words[current + 1].equals("by")) {
token.nextIndex = current + 2;
token.type = TokenType.OPERATOR;
token.value = "*";
return true;
} else if (word.equals("divided") &&
words[current + 1].equals("by")) {
token.nextIndex = current + 2;
token.type = TokenType.OPERATOR;
token.value = "/";
return true;
}
}
return false;
}

private void doException() {
throw new IllegalArgumentException("I'm sorry, I don't understand the question!");
}

private int eval(Token current, Token previous, int currentResult) {
String symbol = previous.value;
int currentVal = Integer.parseInt(current.value);
switch (symbol) {
case "+": return currentResult + currentVal;
case "-": return currentResult - currentVal;
case "*": return currentResult * currentVal;
case "/": return currentResult / currentVal;
}
return currentResult;
}
}``````