# 如何在Swift中打印Pascal三角形

## 直接在控制台中打印

``````// Function that generates the pascals triangle with a specific number of rows
func generatePascalTriangle(numRows: Int){
var results = [[Int]]()

if (numRows == 0) {
return
}

for i in 0..<numRows {
var currentResults = [Int]()

// Print spaces
for _ in 0..<(numRows - i - 1) {
print(" ", terminator:"")
}

// Print values
for j in 0...i {
if (i > 1 && j > 0 && j < i) {
let value = results[i-1][j] + results[i-1][j-1]
currentResults.append(value)

print("\(value) ", terminator: "")
} else {
currentResults.append(1)
print("\(1) ", terminator: "")
}
}

results.append(currentResults)
print("\n")
}
}

// Prompt the user for the number of rows through the console e.g "10"
print("Insert the number of rows for the triangle:")
let numberOfRows:Int? = Int(readLine()!)

// Print the pascals triangle in the console with the given number of rows
generatePascalTriangle(numRows: numberOfRows!)
// Or force the value directly:
// generatePascalTriangle(numRows: 10)``````

## 检索数组中的三角形数据

``````// Function that generates the pascals triangle with a specific number of rows
func generate(numRows: Int) -> [[Int]] {
var results = [[Int]]()

if (numRows == 0) {
return results
}

for i in 0..<numRows {
var currentResults = [Int]()

for j in 0...i {
if (i > 1 && j > 0 && j < i) {
let value = results[i-1][j] + results[i-1][j-1]
currentResults.append(value)
} else {
currentResults.append(1)
}
}

results.append(currentResults)
}

return results
}

let triangleContent = generate(numRows: 10)

print(triangleContent)``````

``````let triangleContent = generate(numRows: 10)

for i in 0..<triangleContent.count {
let row = triangleContent[i]

for i in 0..<row.count {
let value = row[i]
print("\(value) ", terminator:"")
}

print("\n")
}``````

• 回顶