Generating Pascal's Triangle

This is my first function in Typst. It prints a Pascal Triangle and was the result of an experiment initially involved a trailing spaces issue.

This in the original post

A function to print Pascal's Triangle
#let pascal_triangle(n) = {
    set align(center)
    let row = ()
    for r in range(0, n) {
      // step the row
      for i in range(row.len() - 1, 0, step: -1) {
        row.at(i) = row.at(i) + row.at(i - 1)
      }
      row.push(1)
      // print the row
      grid(
        columns: row.len() * (32pt,),
        align: center,
        //stroke : 0.2pt,
        ..row.map(str)
      )
    }
  }

#pascal_triangle(13)

The result:

Thanks to @bluss and @janekfleper

6 Likes

A better second version of the function with vertical spacing control:

The `pascal_triangle()` 2.0 function
#let pascal_triangle(n, width:28pt, height:16pt) = {
  set text(weight: "bold")
  let row = ()
  let rows = ()
  for r in range(0, n+1) {
    // step the row
    for i in range(row.len() - 1, 0, step: -1) {
      row.at(i) = row.at(i) + row.at(i - 1)
    }
    row.push(1)
    // save the row
    rows.push(
      grid(
        columns: row.len() * (width,),
        rows: height,
        align: center + horizon,
        //stroke : 0.2pt,
        ..row.map(str)
      )
    )
  }
  grid(align: center, ..rows)
}

Here the result where the bounding box of each cell is activeted for clearness.
immagine

3 Likes