Published
Edited
Jul 25, 2019
1 fork
4 stars
Insert cell
Insert cell
Insert cell
{
const [[n, _, fontSize]] = values;
const height = width;
const context = DOM.context2d(width, height);
context.font = `${fontSize}px sans-serif`;
context.translate(width / 2, width / 4);

pascalTriangle(n, context);

return context.canvas;
}
Insert cell
function pascalTriangle(n, context) {
const [[_, spacing], [showNumbers, showOdd]] = values;

for (let i = 0; i < n; ++i) {
for (let j = 0; j <= i; ++j) {
const x = -(i / 2) * spacing + j * spacing;
const y = i * (spacing / 2);
const binom = binomial(i, j);
if (showOdd && binom % 2 !== 0) {
circle([x + 5, y - 5, 5], context, { color: "red", fill: false });
context.fillStyle = "black";
}
if (showNumbers) {
context.fillText(binom, x, y);
}
}
}
}
Insert cell
function binomial(n, k) {
return Math.floor(factorial(n) / (factorial(k) * factorial(n - k)));
}
Insert cell
function factorial(n) {
let res = 1;
for (let i = 2; i <= n; ++i) {
res *= i;
}
return res;
}
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more