home about terms twitter

(React) Drawing Pascal's triangle in browser

date: 2021-05-01 | mod: 2021-05-01

Introduction

The binomial theorem is an algebraic expansion of powers of binominal like shown below;

$(a+b)^2 = a^2 + 2ab + b^2$

$(a+b)^3 = a^3 + 3a^2b + 3ab^2 + b^2$

In general, for the expansion (expansion formula) of polynomials such as

$(a+b)^n = {}_n\mathrm{C}_ra^n + _{n}\mathrm{C}_1a^{n+1}b … _{n}\mathrm{C}_nb^{n}$

is valid.

Related to the binomial theorem, there is an array of numbers called “Pascal’s triangle”.

This comes from the fact that when a polynomial is expanded, the coefficients are drawn like a triangle, and also that some coefficients are drawn in the sum of the coefficients.

The Python implementation can be found in my another article [(Python)Printing binomial theorems and Pascal’s triangle].

This time the triangle will be drawn only in the browser. If you want to use the output immediately, jump to result.

Method

import * as React from 'react'
import * as ReactDOM from 'react-dom'

// factorial function
function Fc(k){
    var j = 1
    for(var i = 1; i <= k; i++){
        j *= i
    }
    return j
}

// Pascal's Triangle
function PascalTri() {
  const [size, setSize] = React.useState(10) // char size
  const [number, setNumber] = React.useState(10) // calculate num
  // when -1 button clicked
  const clickMinus = () => {
    if (number >=1) {
      setSize(size + 1)
      setNumber(number - 1)
    }
  }
  // when +1 button clicked
  const clickPlus = () => {
    if (number <= 15) {
      setSize(size - 1)
      setNumber(number + 1)
    }
  }
  // array for output [[1], [1,1], [1,2,1] ...]
  var array = []
  for (var i = 0; i <= number; i++) {
    loopArray = []
    for(var j = 0; j <= i; j++) {
        loopArray += parseInt(Fc((i))/(Fc((i-j))*Fc(j)))
        loopArray += ' ';
    }
    array += loopArray
    array += '**' // char for split
  }

  return (
    <div>
      {/* + num, - size*/}
      <button
        onClick={clickMinus}
        style={{ marginRight: '20px' }}
      >
      -1
      </button>
      {/* - num, + size*/}
      <button
        onClick={clickPlus}
      >
      +1
      </button>
      <div
        style={{ fontSize: `${size}px` }}
        align='center'
      >
        {/* split array */}
        {array.split('**').map(x => (<div>{x}</div>))}
      </div>

    </div>
  )
}

function App() {
  return <PascalTri />
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
)

Result

Let’s change the number by pushing +1 or -1 button.

(241010: omitted)