Avatar of AlKYala

AlKYala's solution

to Wordy in the Java Track

Published at Oct 03 2019 · 0 comments
Instructions
Test suite
Solution

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

Iteration 0 — Numbers

Problems with no operations simply evaluate to the number given.

What is 5?

Evaluates to 5.

Iteration 1 — Addition

Add two numbers together.

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)

Iteration 4 — Errors

The parser should reject:

  • Unsupported operations ("What is 52 cubed?")
  • Non-math questions ("Who is the President of the United States")
  • Word problems with invalid syntax ("What is 1 plus plus 2?")

Bonus — Exponentials

If you'd like, handle exponentials.

What is 2 raised to the 5th power?

32

Setup

Go through the setup instructions for Java to install the necessary dependencies:

https://exercism.io/tracks/java/installation

Running the tests

You can run all the tests for an exercise by entering the following in your terminal:

$ gradle test

Use gradlew.bat if you're on Windows

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

Once you get a test passing, you can enable the next one by removing the @Ignore("Remove to run test") annotation.

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
    public void testJustANumber() {
        assertEquals(5, solver.solve("What is 5?"));
    }

    @Ignore("Remove to run test")
    @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 testNonMathQuestion() {
        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?");
    }

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

        solver.solve("What is 1 plus?");
    }

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

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

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

        solver.solve("What is 1 plus plus 2?");
    }

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

        solver.solve("What is 1 plus 2 1?");
    }

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

        solver.solve("What is 1 2 plus?");
    }

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

        solver.solve("What is plus 1 2?");
    }
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Queue;

public class WordProblemSolver {

	public WordProblemSolver() {}
	
	
	public ArrayList<Object> getProblem(String s) {
		s = s.replaceAll("by ", "");
		String[] sa = s.split(" ");
		s = s.replaceAll("by ", ""); //Delete by
		//s = s.replaceAll("?", ""); //Delete ?
		System.out.println(Arrays.toString(sa)); //debug
		//Queue<Object> operations = new Queue<Object>(); this is acting up
		ArrayList<Object> elements = new ArrayList<Object>();
		
		for(int i = 2; i < sa.length; i++) { //first 2 are "What is", last is question mark
			
			if(i == sa.length -1) { //delete question mark
				sa[i] = sa[i].replace("?", "");
			}
		
			if(isNumber(sa[i])) {
				
				if(elements.size() >= 1 && !isOperation(sa[i-1])){ //weird notation thing
					throw new IllegalArgumentException("I'm sorry, I don't understand the question!");
				}
				
				elements.add(Integer.parseInt(sa[i]));
			}
			else if(isOperation(sa[i])) {
				if(!isNumber(sa[i-1])) {
					throw new IllegalArgumentException("I'm sorry, I don't understand the question!");
				}
				elements.add(giveOperation(sa[i]));
			}
			else { //not valid so throw!
				throw new IllegalArgumentException("I'm sorry, I don't understand the question!");
			}
		}
		if(elements.size() == 0) { //no real question
			throw new IllegalArgumentException("I'm sorry, I don't understand the question!"); 
		}
		else if(elements.size() % 2 == 0) { //obviously missing an element
			throw new IllegalArgumentException("I'm sorry, I don't understand the question!"); 
		}
		
		return elements;
	}
	
	public int solve(String s) {
		ArrayList<Object> values = this.getProblem(s); //well formed at this point
		
		int result = (int) values.get(0);
		
		for(int i = 1; i < values.size(); i++) {
			if(values.get(i) == Operations.ADD) {
				i++;
				int n = (int) values.get(i);
				result += n;
			}
			else if(values.get(i) == Operations.SUBTRACT) {
				i++; //to access next number
				int n = (int) values.get(i);
				result -= n;
			}
			else if(values.get(i) == Operations.MULTIPLY) {
				i++; //to access next number
				int n = (int) values.get(i);
				result *= n;
			}
			else if(values.get(i) == Operations.DIVIDE) {
				i++; //to access next number
				int n = (int) values.get(i);
				result /= n;
			}
		}
		return result;
	}
	
	public static boolean isNumber(String s) {
		try 
		{
			Integer.parseInt(s);
		} catch(NumberFormatException e) {
			return false; //is not a number
		}
		return true; //was
	}
	
	public static boolean isOperation(String s) {
		return s.equals("plus") || s.equals("minus") || s.equals("multiplied") || s.equals("divided");
	}
	
	public static Operations giveOperation(String s){
		if(s.equals("plus")) {
			return Operations.ADD;
		}
		else if(s.equals("minus")) {
			return Operations.SUBTRACT;
		}
		else if(s.equals("multiplied")) {
			return Operations.MULTIPLY;
		}
		else { //thats okay because we first check if we get a division
			return Operations.DIVIDE;
		}
	}
	
	/*public static void main(String args[]) {
		System.out.println(WordProblemSolver.isNumber("A"));
		System.out.println(WordProblemSolver.isNumber("28"));
		WordProblemSolver a = new WordProblemSolver();
		System.out.println(a.solve("What is 1 2 plus?"));
	}*/
}




enum Operations{
	
	ADD,
	SUBTRACT,
	MULTIPLY,
	DIVIDE
	
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

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?