RosettaCodeData/Task/Pascals-triangle/Bait/pascals-triangle.bait
2024-03-06 22:25:12 -08:00

52 lines
1.1 KiB
Text

// Create a Pascal's triangle with a given number of rows.
// Returns an empty array for row_nr <= 0.
fun pascals_triangle(row_nr i32) [][]i32 {
mut rows := [][]i32
// Iterate over all rows
for r := 0; r < row_nr; r += 1 {
// Store the row above the current one
mut above := rows[r - 1]
// Fill the current row. It contains r + 1 numbers
for i := 0; i <= r; i += 1 {
// First number is always 1
if i == 0 {
rows.push([1]) // Push new row
}
// Last number is always 1
else if i == r {
rows[r].push(1)
}
// Other numbers are the sum of the two numbers above them
else {
rows[r].push(above[i - 1] + above[i])
}
}
}
return rows
}
// Helper function to pretty print triangles.
// It still get's ugly once numbers have >= 2 digits.
fun print_triangle(triangle [][]i32) {
for i, row in triangle {
// Create string with leading spaces
mut s := ' '.repeat(triangle.length - i - 1)
// Add each number to the string
for n in row {
s += n.str() + ' '
}
// Print and trim the extra trailing space
println(s.trim_right(' '))
}
}
fun main() {
print_triangle(pascals_triangle(7))
}