π Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io π

jsteen-mpr's solution

to Wordy in the Ruby 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

For installation and learning resources, refer to the exercism help page.

For running the tests provided, you will need the Minitest gem. Open a terminal window and run the following command to install minitest:

``````gem install minitest
``````

If you would like color output, you can `require 'minitest/pride'` in the test file, or note the alternative instruction, below, for running the test file.

Run the tests from the exercise directory using the following command:

``````ruby wordy_test.rb
``````

To include color from the command line:

``````ruby -r minitest/pride wordy_test.rb
``````

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.

wordy_test.rb

``````require 'minitest/autorun'
require_relative 'wordy'

# Common test data version: 1.0.0 5b8ad58
class WordyTest < Minitest::Test
# skip
question = 'What is 1 plus 1?'
end

skip
question = 'What is 53 plus 2?'
end

skip
question = 'What is -1 plus -10?'
end

skip
question = 'What is 123 plus 45678?'
end

def test_subtraction
skip
question = 'What is 4 minus -12?'
end

def test_multiplication
skip
question = 'What is -3 multiplied by 25?'
end

def test_division
skip
question = 'What is 33 divided by -3?'
end

skip
question = 'What is 1 plus 1 plus 1?'
end

skip
question = 'What is 1 plus 5 minus -2?'
end

def test_multiple_subtraction
skip
question = 'What is 20 minus 4 minus 13?'
end

skip
question = 'What is 17 minus 6 plus 3?'
end

def test_multiple_multiplication
skip
question = 'What is 2 multiplied by -2 multiplied by 3?'
end

skip
question = 'What is -3 plus 7 multiplied by -2?'
message = "You should ignore order of precedence. -3 + 7 * -2 = -8, not #{answer}"
end

def test_multiple_division
skip
question = 'What is -12 divided by 2 divided by -3?'
end

def test_unknown_operation
skip
question = 'What is 52 cubed?'
assert_raises ArgumentError do
end
end

def test_non_math_question
skip
question = 'Who is the President of the United States?'
assert_raises ArgumentError do
end
end

# Problems in exercism evolve over time, as we find better ways to ask
# questions.
# The version number refers to the version of the problem you solved,
#
# Define a constant named VERSION inside of the top level BookKeeping
# module, which may be placed near the end of your file.
#
# In your file, it will look like this:
#
# module BookKeeping
#   VERSION = 1 # Where the version number matches the one in the test.
# end
#
# http://ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/constants.html

def test_bookkeeping
skip
assert_equal 1, BookKeeping::VERSION
end
end``````
``````class WordProblem
NUMBER_REGEXP = /(?<operand>-?\d+)/

OPERATION_RULES = [
['plus N', /(?:plus|added to) #{NUMBER_REGEXP}/, :+],
['minus N', /(?:minus|subtract|take away) #{NUMBER_REGEXP}/, :-],
['multiplied by N', /(?:multiplied by|times) #{NUMBER_REGEXP}/, :*],
['divided by N', /divided by #{NUMBER_REGEXP}/, :/],
[
'raised to the Nth power',
/(?:raised )?to the #{NUMBER_REGEXP}(?:th|st|nd|rd) power/,
:**
]
].freeze

def initialize(question)
@starting_value, @operations = parse_question(question.to_s)
if @starting_value.nil? || @operations.empty?
raise ArgumentError, "Invalid question.\n#{instructions}"
end
end

@operations.reduce(@starting_value) do |result, operation|
result.public_send(operation[:method], operation[:argument])
end
end

private

def parse_question(question)
return [] unless /\AWhat is #{NUMBER_REGEXP} (?<operations>.+)\?\Z/ =~ question
starting_value = Regexp.last_match[:operand].to_i
parsed_operations = parse_operations(Regexp.last_match[:operations])
[starting_value, parsed_operations]
end

def parse_operations(operations_phrase)
tries_since_last_match = 0
OPERATION_RULES.cycle.each_with_object([]) do |rule, parsed|
operations_phrase = operations_phrase.sub(/\A\s*#{rule[1]}/) do
parsed.push({ method: rule[2], argument: Regexp.last_match[:operand].to_i })
tries_since_last_match = 0
''
end

break parsed if operations_phrase.strip.empty? # succeeded
tries_since_last_match += 1
break [] if tries_since_last_match > OPERATION_RULES.size # failed
end
end

def instructions
"Try: 'What is OPERATION?', where OPERATION is one or more of:\n\t" +
OPERATION_RULES.map(&:first).join("\n\t") +
"\nand N is an integer."
end
end

module BookKeeping
VERSION = 1
end``````