How to create Pascal’s Triangle in swift

[Link] In Pascal’s triangle, each element is the sum of the two numbers directly above it.

func generate(_ numRows: Int) -> [[Int]] {
    var pascalObject = [[Int]](repeating: [Int](), count: numRows)
    
    for firstElement in 0..<numRows {
        pascalObject[firstElement] = [Int](repeating: 0, count: firstElement+1)
        
        for secondElement in 0..<firstElement+1 {
            if secondElement == 0 || secondElement == firstElement {
                pascalObject[firstElement][secondElement] = 1
            } else {
                let addition = pascalObject[firstElement-1][secondElement-1] + pascalObject[firstElement-1][secondElement]
                pascalObject[firstElement][secondElement] = addition
            }
        }
    }
    
    return pascalObject
}

Leave a Comment

Your email address will not be published. Required fields are marked *