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)
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);
}
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 -
.
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)