Visualize Pascal's triangle and other triangle shaped lists
My modest attempt:
With[{n = 7},
Graphics[Table[Text[Style[Binomial[n - j, n - i], Large], {Sqrt[3] (i - j/2), 3 j/2}],
{i, n}, {j, i}]]]
Here's a more general function:
triangularArrayLayout[triArray_List, opts___] := Module[{n = Length[triArray]},
Graphics[MapIndexed[
Text[Style[#1, Large], {Sqrt[3] (n - 1 + #2.{-1, 2}), 3 (n - First[#2] + 1)}/2] &,
triArray, {2}], opts]]
Use it on the Stirling subset numbers $\left\{{n \atop k}\right\}$:
triangularArrayLayout[Table[StirlingS2[n, k], {n, 0, 5}, {k, 0, n}]]
Here is another way:
pascalTriangle[n_] :=
NestList[{1, Sequence @@ Plus @@@ Partition[#, 2, 1], 1} &, {1},
n - 1];
Column[Grid[{#}, ItemSize -> 3] & /@ (pascalTriangle[7] /.
x_Integer :>
Text[Style[x, Large, If[x == 2, Red, Black]]]), Center]
To address your question about visualizing a triangular list, let's use the following list:
t = Table[Binomial[n, k], {n, 0, 8}, {k, 0, n}]
(*out *)
{{1}, {1, 1}, {1, 2, 1}, {1, 3, 3, 1}, {1, 4, 6, 4, 1}, {1, 5, 10, 10, 5, 1},
{1, 6, 15, 20, 15, 6, 1}, {1, 7, 21, 35, 35, 21, 7, 1}, {1, 8, 28, 56, 70, 56, 28, 8, 1}}
You can format the list as a matrix:
MatrixForm[t]
You can insert tabs between the items and print each row, literally as a Row
, in a grid.
{Row[#, "\t"]} & /@ t // Grid
By using Row
, we are sending Grid
one item for each gridrow. (If Row
were not employed, Grid
would treat each item of a sublist as requiring its own column. That will lead to a triangle skewed from left to right. )
Here are a couple of ideas on how to style the 2
as large and red. The following will make any entry of 2
red (it will not color the 2 in 20
).
t1 = Table[Binomial[n, k], {n, 0, 8}, {k, 0, n}] /. {2 -> Style[2, Red, 18]}
You may then format t1
as a matrix or as a grid.
The following makes the 2
in the center of a sublist with 3 elements red. It's not necessary to do this because 2
only shows up once in Pascal's triangle. But you get the idea...
t2 = Table[Binomial[n, k], {n, 0, 8}, {k, 0, n}] /. {a_, 2, c_} :> {a, Style[2, Red, 18], c}