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', '8', '5', '6', '+', '5', '*', '/', '*', '6', '+', '7', '+']
let A = RPN(arr);
A = Math.floor(A)
// A = ? (number)
Our good old friend the Reverse Polish Notation (RPN) is back again. To complete the challenge we have to solve the notation, let's do that in pseudo-code:
arr = 1 8 5 6 + 5 * / * 6 + 7 +
stack = []
index: 0, 1, 2 & 3
stack = [1 8 5 6]
index: 4
token: +
push(5 + 6 = 11)
stack = [1 8 11]
index: 5
stack = [1 8 11 5]
index: 5
token: *
push(11 * 5 = 55)
stack = [1 8 55]
index: 6
token: /
push(8 / 55 = 0.145)
stack = [1 0.145]
index: 7
token: *
push(0.145 * 1 = 0.145)
stack = [0.145]
index: 8
stack = [0.145 6]
index: 9
token: +
push(0.145 + 6 = 6.145)
stack = [6.145]
index: 10
stack = [6.145 7]
index: 11
token: +
push(6.145 + 7 = 13.145)
stack = [13.145]
A = Floor(stack.pop())
A == 13
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)