DEV Community 👩‍💻👨‍💻

Cover image for Road to Genius: smart #17
Ilya Nevolin
Ilya Nevolin

Posted on

Road to Genius: smart #17

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.

coding challenge

We have encountered similar code before in "beginner" rank, but this time the challenge asks us to solve it. Fortunately for us it's not that complicated.

The challenge starts with two arrays a1 and a2 which contain five random numbers each, and an empty array arr. Following is a while-loop that executes as long as both a1 and a2 are not empty. If you analyze the body of the loop, it's removing numbers using pop (from the end of the array) and compares those numbers. Depending on the condition of x and y those numbers are added to arr. Below is some pseudo-code that to help us analyze the code:

a1.pop  ->  x=4
a2.pop  ->  y=6
push    ->  arr=[6, 4]

a1.pop  ->  x=4
a2.pop  ->  y=9
push    ->  arr=[..., 9, 4]

a1.pop  ->  x=3
a2.pop  ->  y=4
push    ->  arr=[..., 4, 3]

a1.pop  ->  x=0
a2.pop  ->  y=9
push    ->  arr=[..., 9, 0]

a1.pop  ->  x=7
a2.pop  ->  y=3
push    ->  arr=[..., 7, 3]

arr = [6, 4, 9, 4, 4, 3, 9, 0, 7, 3]
Enter fullscreen mode Exit fullscreen mode

Now that we know the final value of arr, the challenge asks us to solve R = arr[4], which is the value in arr at 4th index, which is 4 in this case.

Important note: we've analyzed the whole code above, but keep in mind that we should've stopped once we found arr's value at index 4, because that's the only thing that matters here.

coding challenge answer


Join me on the Road to Genius and upgrade your programming skills, at https://nevolin.be/codr/

Top comments (0)

Must read:

"I made 10x faster JSON.stringify() functions, even type safe"