DEV Community

Cesar Del rio
Cesar Del rio

Posted on

#37 - Row of the odd triangle - CodeWars Kata (6 kyu)

Instructions

Given a triangle of consecutive odd numbers:

 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 
Enter fullscreen mode Exit fullscreen mode

find the triangle's row knowing its index (the rows are 1-indexed), e.g.:

odd_row(1) == [1]
odd_row(2) == [3, 5]
odd_row(3) == [7, 9, 11]

Note: your code should be optimized to handle big inputs.


My solution:

function oddRow(n) { let first = 1; for(let i = 1; i<n; i++){ first+=i*2 } let r = [first]; for(let i = 1; i<n; i++){ r.push(first+=2) } return r } 
Enter fullscreen mode Exit fullscreen mode

Explanation

First I got the first value of the row that I'm searching on, I did this by using a for loop that will iterate the number of rows, and in every iteration I changed the value of the var "first" by adding 2 to it and revaluing it.

 for(let i = 1; i<n; i++){ first+=i*2 } 
Enter fullscreen mode Exit fullscreen mode

After that with that value I made the variable "r" that will contain the result that will be returned, inside of it I stored the first number of the row

let r = [first]; 
Enter fullscreen mode Exit fullscreen mode

After that I used another loop and inside of it, I pushed every value after the first plus 2, and at the end I just returned "r"

for(let i = 1; i<n; i++){ r.push(first+=2) } return r 
Enter fullscreen mode Exit fullscreen mode

What do you think about this solution? 👇🤔

My Github
My twitter
Solve this Kata

Top comments (0)