Class PascalsTriangle
Private Class triRow
Property value As Integer = 0
Property aboveRow As Integer = -1
Property aboveColLeft As Integer = -1
Property aboveColRight As Integer = -1
Public Function ValueStringLength() As Integer
Return Me.value.ToString.Length
End Function
End Class
Private Property triRows As New List(Of List(Of triRow))
Public Sub New(numberOfRows As Integer)
For rowNum As Integer = 0 To numberOfRows - 1
Me.addRow(rowNum)
Next
End Sub
Private Sub addRow(rowNum As Integer)
Dim aRow As New List(Of triRow)
If rowNum > 0 Then
For col As Integer = 0 To rowNum
Dim aCol As New triRow
aCol.aboveRow = rowNum - 1
aCol.aboveColLeft = col - 1
aCol.aboveColRight = rowNum - (col + 1)
If aCol.aboveColLeft >= 0 Then
aCol.value = Me.triRows(aCol.aboveRow)(aCol.aboveColLeft).value
End If
If aCol.aboveColRight >= 0 Then
aCol.value += Me.triRows(aCol.aboveRow)(aCol.aboveColRight).value
End If
aRow.Add(aCol)
Next
Else
Dim aCol As New triRow
aCol.value = 1
aRow.Add(aCol)
End If
Me.triRows.Add(aRow)
End Sub
Private Function maxColWidth() As Integer
Dim rv As Integer = 0
For Each r As triRow In Me.triRows(Me.triRows.Count - 1)
Dim colL As Integer = r.ValueStringLength
If colL > rv Then
rv = colL
End If
Next
Return rv
End Function
Public Overrides Function ToString() As String
Dim pad As Integer = Me.maxColWidth + 2
Dim rv As New System.Text.StringBuilder
Dim lines As New List(Of String)
For r As Integer = 0 To Me.triRows.Count - 1
rv.Length = 0
For Each rw As triRow In Me.triRows(r)
rv.AppendFormat("{0}", rw.value.ToString.PadRight(pad, " "c))
Next
lines.Add(rv.ToString.Trim)
Next
'make it look like triangle
'max string length
Dim maxL As Integer = lines(lines.Count - 1).Length
For x As Integer = 0 To lines.Count - 1
'pad left
Dim ldif As Integer = (maxL - lines(x).Length) \ 2
Dim s As String = New String(" "c, ldif)
lines(x) = lines(x).Insert(0, s)
Next
Return String.Join(Environment.NewLine, lines)
End Function
End Class