DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 968,873 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Road to Genius: advanced #43
Ilya Nevolin
Ilya Nevolin

Posted on

Road to Genius: advanced #43

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 = ['5', '4', '1', '2', '+', '7', '*', '/', '*', '2', '+', '4', '+'];
let A = RPN(arr);
A = Math.floor(A);

// ๐ŸŽ = ? (string)
// such that A = 6 (number)
Enter fullscreen mode Exit fullscreen mode

Here's an interesting challenge where we only have to fix one bug ๐ŸŽ. It's an easy challenge. To solve it we have to look at the environment surrounding the bug:

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);
}
Enter fullscreen mode Exit fullscreen mode

Notice that the token is some string that represents an operation (*, /, + and ๐ŸŽ), the push operation below it reveals its actual operation, so ๐ŸŽ has to be -.

coding challenge answer

A bit more info about this code; The function RPN stands for Reverse Polish Notation, it's a way of representing a series of mathematical operations to be computed. You can Google it for more details, since we might encounter it again later I'll leave it at this.

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/

Top comments (0)

Visualizing Promises and Async/Await ๐Ÿคฏ

async await

โ˜๏ธ Check out this all-time classic DEV post