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 PES(nums) {
const ret = [];
for (let i = 0, temp = 1; i < nums.length; i++) {
ret[i] = temp;
temp *= nums[i];
}
for (let i = nums.length - 1, temp = 1; i >= 0; i--) {
ret[i] *= temp;
temp *= nums[i];
}
return ret;
}
let A = PES([1, 4, 5]);
A = A[0]
// A = ? (number)
In today's challenge we need to figure out A[0]
's value, where A
is an array and output of the function PES([1,4,5])
.
On first sight I have no clue what PES
does, except that it contains two for-loops and a couple of multiplications; looks like some basic math, so it shouldn't be too hard.
The quickest way to solve this is brute-force, we only have 3 input numbers, so let's do that in pseudo-code:
--- first for-loop (forwards)
ret = []
temp = 1
ret = [1]
temp = 1*1 = 1
ret = [1, 1]
temp = 1*4 = 4
ret = [1, 1, 4]
temp = ... // I don't care
--- second for-loop (backwards)
ret = [1, 1, 4]
temp = 1
ret = [1, 1, 4*1]
temp = 1*5 = 5
ret = [1, 1*5, 4]
temp = 5*4 = 20
ret = [1*20, 5, 4]
temp = ... // I don't care
return ret=[20, 5, 4] = A
We find that A[0] == 20
.
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 (2)
Good app !
hehe yeah :D