How to resolve the algorithm Pascal's triangle step by step in the Nim programming language
How to resolve the algorithm Pascal's triangle step by step in the Nim programming language
Table of Contents
Problem Statement
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row of the triangle would be: So the triangle now looks like this: Each row n (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)n.
Write a function that prints out the first n rows of the triangle (with f(1) yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for n ≤ 0 does not need to be uniform, but should be noted.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Pascal's triangle step by step in the Nim programming language
Source code in the nim programming language
import sequtils, strutils
proc printPascalTriangle(n: int) =
## Print a Pascal triangle.
# Build the triangle.
var triangle: seq[seq[int]]
triangle.add @[1]
for _ in 1..<n:
triangle.add zip(triangle[^1] & @[0], @[0] & triangle[^1]).mapIt(it[0] + it[1])
# Build the lines to display.
let length = len($max(triangle[^1])) # Maximum length of number.
var lines: seq[string]
for row in triangle:
lines.add row.mapIt(($it).center(length)).join(" ")
# Display the lines.
let lineLength = lines[^1].len # Length of largest line (the last one).
for line in lines:
echo line.center(lineLength)
printPascalTriangle(10)
const ROWS = 10
const TRILEN = toInt(ROWS * (ROWS + 1) / 2) # Sum of arth progression
var triangle = newSeqOfCap[Natural](TRILEN) # Avoid reallocations
proc printPascalTri(row: Natural, result: var seq[Natural]) =
add(result, 1)
for i in 2..row-1: add(result, result[^row] + result[^(row-1)])
add(result, 1)
echo result[^row..^1]
if row + 1 <= ROWS: printPascalTri(row + 1, result)
printPascalTri(1, triangle)
You may also check:How to resolve the algorithm Perfect numbers step by step in the LabVIEW programming language
You may also check:How to resolve the algorithm Accumulator factory step by step in the Astro programming language
You may also check:How to resolve the algorithm Four is magic step by step in the J programming language
You may also check:How to resolve the algorithm Sockets step by step in the Elixir programming language
You may also check:How to resolve the algorithm Cartesian product of two or more lists step by step in the PicoLisp programming language