loading...
Cover image for Road to Genius: advanced #48

Road to Genius: advanced #48

codr profile image Codr ・2 min read

Each day I solve several coding challenges and puzzles from Codr's ranked mode. The goal is to reach genius rank, along the way I explain how I solve them. You do not need any programming background to get started, and you will learn a ton of new and interesting things as you go.

function RPN(tokens) {
  const stack = [];
  for (let index = 0; index < tokens.length; index++) {
    const token = tokens[index];
    if (!Number.isNaN(Number(token))) {
      stack.push(token);
    } else {
      const a = Number(stack.pop());
      const b = Number(stack.pop());
      if (token === '*') {
        stack.push(b * a);
      } else if (token === '/') {
        stack.push(b / a);
      } else if (token === '+') {
        stack.push(b + a);
      } else if (token === '-') {
        stack.push(b - a);
      }
    }
  }
  return stack.pop();
}

let arr = ['1', '6', '9', '/', '+']
let A = RPN(arr);
A = Math.floor(A)

// A = ? (number)

We meet our old friend Reverse Polish Notation (RPN) again. We haven't analyzed it the previous time, since we have solve it completely we'll have to do it this time.

The input that RPN takes is:

arr = ['1', '6', '9', '/', '+']

The function starts with declaring an empty array stack. Then it iterates over all input tokens using a for-loop. Let's go over the process using pseudo-code:

stack = []

token = 1 --> is number --> push
stack = [1]

token = 6 --> is number --> push
stack = [1, 6]

token = 9 --> is number --> push
stack = [1, 6, 9]

token = / --> non number
a = 9
b = 6
push(6 / 9)
stack = [1, 0.66667]

token = + --> non number
a = 0.66667
b = 1
push(0.66667 + 1)
stack = [1.666667]

return stack.pop() --> 1.666667

A = Math.floor(1.66667) = 1

Well that wasn't so hard, was it? :)
coding challenge answer

We finally made it to the next rank "superior", I'm excited for the next challenge!
coding challenge extra

By solving these challenges you train yourself to be a better programmer. You'll learn newer and better ways of analyzing, debugging and improving code. As a result you'll be more productive and valuable in business. Get started and become a certified Codr today at https://nevolin.be/codr/

Posted on by:

codr profile

Codr

@codr

Improve your coding skills with Codr. A free educational platform founded by Ilya Nevolin.

Discussion

markdown guide