Published at Jul 13 2018
·
1 comment

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

You can run all the tests for an exercise by entering

```
$ gradle test
```

in your terminal.

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.

```
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
public void testSingleAddition1() {
assertEquals(2, solver.solve("What is 1 plus 1?"));
}
@Ignore("Remove to run test")
@Test
public void testSingleAddition2() {
assertEquals(55, solver.solve("What is 53 plus 2?"));
}
@Ignore("Remove to run test")
@Test
public void testSingleAdditionWithNegativeNumbers() {
assertEquals(-11, solver.solve("What is -1 plus -10?"));
}
@Ignore("Remove to run test")
@Test
public void testSingleAdditionOfLargeNumbers() {
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
public void testMultipleAdditions() {
assertEquals(3, solver.solve("What is 1 plus 1 plus 1?"));
}
@Ignore("Remove to run test")
@Test
public void testAdditionThenSubtraction() {
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
public void testSubtractionThenAddition() {
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
public void testAdditionThenMultiplication() {
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.regex.Matcher;
import java.util.regex.Pattern;
public class WordProblemSolver {
final static String NUMBER = "-?[0-9]+";
final static String POWER = NUMBER + "\\^" + NUMBER;
final static String MULTIPLY = NUMBER + "\\*" + NUMBER;
final static String DIVIDE = NUMBER + "/" + NUMBER;
final static String ADD = NUMBER + "\\+" + NUMBER;
//use underscores for subtraction to distinguish from negatives
final static String SUBTRACT = NUMBER + "_" + NUMBER;
final static String OPERANDS = "[+_*/^]";
public int solve(String input){
input = input.replaceAll("(What is |\\?|(th|rd|nd|st) power)", "");
input = input.replaceAll(" plus ", "+");
input = input.replaceAll(" minus ", "_");
input = input.replaceAll(" multiplied by ", "*");
input = input.replaceAll(" divided by ", "/");
input = input.replaceAll(" raised to the ", "^");
if(!input.matches(NUMBER + "+([+_*/^]" + NUMBER + "+)*")){ //do you see the robot?
throw new IllegalArgumentException("I'm sorry, I don't understand the question!");
}
return Integer.parseInt(firstGradeMath(input));
//real solution
//return Integer.parseInt(pemdas(input));
//I wrote it, too, but removed for submission's readability
}
private String firstGradeMath(String input){
Matcher m = Pattern.compile(NUMBER + OPERANDS + NUMBER).matcher(input);
while(!input.matches("-?[0-9]+")){
if(m.find()){
String operation = input.substring(m.start(), m.end());
if(operation.matches(ADD)){
input = add(operation) + input.substring(m.end());
}
else if(operation.matches(SUBTRACT)){
input = subtract(operation) + input.substring(m.end());
}
else if(operation.matches(MULTIPLY)){
input = multiply(operation) + input.substring(m.end());
}
else if(operation.matches(DIVIDE)){
input = divide(operation) + input.substring(m.end());
}
else if(operation.matches(POWER)) {
input = pow(operation) + input.substring(m.end());
}
}
m = Pattern.compile(NUMBER + OPERANDS + NUMBER).matcher(input);
}
return input;
}
//operations
private String add(String input){
String[] operands = input.split("\\+");
return "" + (Integer.parseInt(operands[0]) + Integer.parseInt(operands[1]));
}
private String subtract(String input){
String[] operands = input.split("_");
return "" + (Integer.parseInt(operands[0]) - Integer.parseInt(operands[1]));
}
private String multiply(String input){
String[] operands = input.split("\\*");
return "" + (Integer.parseInt(operands[0]) * Integer.parseInt(operands[1]));
}
private String divide(String input){
String[] operands = input.split("/");
return "" + (Integer.parseInt(operands[0]) / Integer.parseInt(operands[1]));
}
private String pow(String input){
String[] operands = input.split("\\^");
return "" + (int)(Math.pow(Integer.parseInt(operands[0]), Integer.parseInt(operands[1])));
}
}
```

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,394 exercises across 50 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments

Whoops, forgot to actually put OPERANDS into the initial check... well, whatever