Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

coding challenge solution with a hidden bug

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading