Recently I took a coding challenge on turing. The question was :
You will be given a string list(ops) as input.
- If its an integer you have to keep a record of it
- If it’s a character ‘C’, you have to remove the last recorded element
- If it’s a character ‘D’, you have to double the last element and record it
- If it’s a character ‘+’, you have to add the last two elements and record it
Return the final sum of records.
Example input,
ops = ["5", "2", "C", "D", "+"]
output = 30
I was able to write the code, however it did not pass. In retrospective, I am just trying to find what went wrong. Please find my code below:
def score_calculator
scores = []
ops.each do |rec|
scores << rec.to_i if rec.is_a?(Integer)
scores << scores.last(2).sum if rec == '+'
scores << (scores.last.to_i * 2) if rec = 'D'
scores.pop if rec == 'C'
end
return scores.sum
end
>Solution :
Here’s how you could still run your code with a little improvement..
def score_calculator
scores = []
ops.each do |rec|
scores << rec.to_i if rec.match?(/[[:digit:]]/)
scores << scores.last(2).sum if rec == '+'
scores << (scores.last.to_i * 2) if rec == 'D'
scores.pop if rec == 'C'
end
return scores.sum
end