Skip to content

Commit d27e987

Browse files
committed
exercism-72 Wordy
1 parent 50f2967 commit d27e987

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,7 @@ solution of many challenges of [Leetcode](https://leetcode.com/), [Exercism](htt
293293
69. [Robot Simulator](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/robot_simulator.rb)
294294
70. [Beer Song](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/beer_song.rb)
295295
71. [Protein Translation](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/protein_translation.rb)
296+
72. [Wordy](https://github.com/kumar91gopi/Algorithms-and-Data-Structures-in-Ruby/blob/master/exercism/wordy.rb)
296297

297298
<a name="leetcode"/>
298299

exercism/wordy.rb

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# Problem: https://exercism.org/tracks/ruby/exercises/wordy
2+
3+
# Solution
4+
class WordProblem
5+
REPLACEMENTS = {
6+
"plus" => "+",
7+
"minus" =>"-",
8+
"divided by" => "/",
9+
"multiplied by" => "*",
10+
"what is" =>""
11+
}
12+
OPERATIONS = {
13+
"+" => lambda{|a,b| a+b},
14+
"-" =>lambda{|a,b| a-b },
15+
"/" => lambda{|a,b| a/b },
16+
"*" => lambda{|a,b| a*b }
17+
}
18+
def initialize(word_prob)
19+
word_prob = word_prob.strip.gsub(/\b(?:#{REPLACEMENTS.keys.join('|')})\b/i, REPLACEMENTS)
20+
@word_prob = word_prob[-1]=="?" ? word_prob[0...-1] : word_prob
21+
end
22+
23+
def answer
24+
words = @word_prob.split(" ")
25+
result = 0
26+
i=0
27+
prev_num = nil
28+
prev_op = nil
29+
while i<words.length
30+
if words[i].match?(/^-?\d+$/)
31+
unless prev_num.nil? and prev_op.nil?
32+
result = prev_op.call(prev_num,words[i].to_i)
33+
prev_op = nil
34+
prev_num = result
35+
else
36+
prev_num = words[i].to_i
37+
end
38+
elsif OPERATIONS.keys.include?(words[i])
39+
prev_op = OPERATIONS[words[i]]
40+
else
41+
raise ArgumentError
42+
end
43+
i+=1
44+
end
45+
result
46+
end
47+
end
48+
49+
# Solution
50+
class WordProblem
51+
attr_reader :question
52+
OPERATIONS = {
53+
'plus' => :+,
54+
'minus' => :-,
55+
'divided' => :/,
56+
'multiplied' => :*
57+
}
58+
def initialize(question)
59+
@question = question
60+
end
61+
62+
def answer
63+
numbers = question.scan(/(-?\d+)/).flatten.map(&:to_i)
64+
operations = question.scan(/(plus|minus|multiplied|divided)/).flatten.
65+
map { |op| OPERATIONS[op] }
66+
raise ArgumentError if numbers.empty? || operations.empty?
67+
equation = operations.unshift(:+).zip(numbers).flatten.compact
68+
equation.each_slice(2).inject(0) do |sum, (operation, number)|
69+
sum.send(operation, number)
70+
end
71+
end
72+
end

0 commit comments

Comments
 (0)