Expand the Sequence

You are given an array numbers. Expand the numbers into an a palindrome landscape of mountains. For numbers = [2,3,2,4], palindromeMountains = [1,2,1,2,3,1,2,1,2,3,4,3,2,1]

Example

Input:

numbers = [2,3,2,4]

Expected value:

palindromeMountains = [1, 2, 1, 2, 3, 2, 1, 2, 1, 2, 3, 4, 3, 2, 1]

[collapse]
Hint

Iterate from 1 to number and then back to 1, in decreasing order. Do this for each number and avoid adding 1 twice consecutively.

[collapse]
Solution

let numbers = [2,3,2,4]
func palindromeSequence(numbers:[Int]) -> [Int] {
    var mountains = [Int]()
    for i in 0..<numbers.count {
        var j = 1
        if i != 0 {j = 2}
        while j <= numbers[i] {
            mountains.append(j)
            j += 1
        }
        j -= 1
        repeat {
            j -= 1
            mountains.append(j)
        } while j > 1

    }
    return mountains
}

var palindromeMountains = palindromeSequence(numbers: numbers)

[collapse]
Subscribe
We send about one email per week with our latest tutorials and updates
Never display this again :)