DEV Community

Cover image for Road to Genius: beginner #2
Ilya Nevolin
Ilya Nevolin

Posted on

Road to Genius: beginner #2

Each day I solve several 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, but you will learn a ton of new and interesting things as you go.

programming challenge

This challenge is slightly more complex than the previous one. Don't be fooled by the amount of code, let's dissect the challenge.

As you can see at the bottom comments, there is only one bug we need to solve 💚 (a number), and we get a list of answers to choose from.

The code starts by creating 3 arrays, the first two (a1 and a2) are filled with numbers, the third arr is empty. Then we have a while loop, whose condition is the length of a1 and a2. This means, as long as those two arrays are not empty, it will execute the code inside the loop {...}.

This inner code pops from a1 and a2 respectively into x and y variables. Then it compares x with y, if x is greater than y it first adds x into arr then y, in the other case it adds first y then x. This is all we need to know.

The challenge also states that R should be 6. R is some value from arr at an unknown position (=index) represented by our bug 💚 (a number). So all we need is to find an index of arr such that the value at that index is 6.

Here's an example:
let demo = [2, 4, 6]
an array is zero-indexed, meaning the first element is at position (index) 0, the second element is at index 1, and so on...
In this example the value 6 is at index 2.

Now back to our challenge. We know that the loop takes elements from two different arrays, and adds them to a new array, all we need is find the position (index) of a value 6. Notice that there are 2 possible answers, because number 6 appears twice in a2. But we are very lucky since one of these numbers appears at the very end of a2. All we need is evaluate the inner loop just once to find the index, like this:

x = 1   (pop from a1)
y = 6   (pop from a2)
if (x > y)    this is false
...
else {        here we go
  arr.push(y)
  arr.push(x)
}

'arr' is now [6, 1]
Enter fullscreen mode Exit fullscreen mode

value 6 is at index/position 0 in 'arr'
this means that 💚 should be 0.

programming challenge answer


If you feel inspired and motivated to upgrade your coding + debugging skills, join me on the Road to Genius at https://nevolin.be/codr/

Top comments (0)