Thursday, 7 January 2016

Kata Day 42: Alternating Loops


Problem Description: Write a function combine()that combines arrays by alternately taking elements passed to it.

E.g

combine(['a', 'b', 'c'], [1, 2, 3]) == ['a', 1, 'b', 2, 'c', 3]
combine(['a', 'b', 'c'], [1, 2, 3, 4, 5]) == ['a', 1, 'b', 2, 'c', 3, 4, 5]
combine(['a', 'b', 'c'], [1, 2, 3, 4, 5], [6, 7], [8]) == ['a', 1, 6, 8, 'b', 2, 7, 'c', 3, 4, 5]
Arrays can have different lengths.


Level:6kyu

Link To Kata:  Alternating Loops

We put all the input arrays in a single array using the slice function of Javascript. We declare a variable max_len and initialize it to zero. We loop through the input merged array 
and find the max_len value by comparing it with length of every sub array and comparing it with the max_len value. 

We initialize an empty array as ans. Then we loop from 0 to max_len and push 1 element from every subarray by keeping a check if the array has reached its last element or not.

In the end we output ans array as the solution to this Kata.

Please go through the code for a better understanding. 

Here is a link to the code: Kata Day 42

Please mention your suggestions or your doubts in the comment below.

Happy coding. :)

No comments:

Post a Comment