cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External CSS

These stylesheets will be added in this order and before the code you write in the CSS editor. You can also add another Pen here, and it will pull the CSS from it. Try typing "font" or "ribbon" below.

Quick-add: + add another resource

Add External JavaScript

These scripts will run in this order and before the code in the JavaScript editor. You can also link to another Pen here, and it will run the JavaScript from it. Also try typing the name of any popular library.

Quick-add: + add another resource

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

            
              <!DOCTYPE html>
<html>
<head>
	<title>Pascal's Triangle</title>
</head>
<body>
	<h1>Pascal's Triangle</h1>
  <strong>Code:</strong>
  <code>pascal(8, 3,'|','pascal-container')</code>
  <p><strong>Result:</strong></p>
	<div id="pascal-container"></div>
</body>
</html>
            
          
!
            
              /**
 * Pascal’s Triangle
 * @author Arthur Khachatryan <arthurk55@gmail.com>
 * @version 1.0.0
 * @description Function that takes in number of rows, the number to use, the empty character and DOM container (if results are to be output on page) and returns an instance of Pascal’s Triangle.
 * @param {number}		rows 			the number of rows to display
 * @param {number} 		numToUse 		the base number to be used in triangle
 * @param {[string]} 	emptyChar 		the empty character to use (for console only, not relevant for use on page)
 * @param {[string]} 	DOMContainer 	the element ID of the container to be used to display the triangle on the page 
 */
function pascal(rows, numToUse, emptyChar, DOMContainer) {
	var aRows = []
      , aCols = []
	  , iR = 0
	  , iC = 0
	  , num = numToUse || 1
	  , ins = null
	  , empty = emptyChar || null
	  , columns = rows + (rows - 1)
	  , startCol = Math.floor(columns / 2)
	  , topLeft
	  , topRight
	;

	// builds rows
	for (; iR < rows; iR++) {
		// build columns
		for (; iC < columns; iC++) {

			// if first row, we need a starting position (middle of table)
			if (iR === 0) {
				if (iC === startCol) {
					ins = num;
				} else {
					ins = null;
				}

			// not first row
			} else {
					topLeft = aRows[iR - 1][iC - 1];
					topRight = aRows[iR - 1][iC + 1];

					// checkered null cell
					if (topLeft == null && topRight == null) {
						ins = null;
					// right side cell with 1-sided value
					} else if (topLeft == null && topRight != null) {
						ins = topRight;
					// left side cell with 1-sided value
					} else if (topLeft != null && topRight == null) {
						ins = topLeft;
					// inside cell with value
					} else {
						ins = topLeft + topRight;
					}
			}
			aCols.push(ins);
		}

		aRows.push(aCols);

		// clear column data for new row
		aCols = [];
        iC = 0;
	}

	iR = 0;
	iC = 0;

	// loop through again and replace null with prescribed empty char
	for (; iR < rows; iR++) {
		for (; iC < columns; iC++) {
			if (aRows[iR][iC] == null) {
				aRows[iR][iC] = empty;
			}
		}
		iC = 0;
	}

	// if a DOM container is passed in use it to constrct an HTML table inside
	if (DOMContainer) {
		iR = 0;
		iC = 0;

		//var container = document.getElementById(DOMContainer);

		var container = document.getElementById(DOMContainer)
			, tr
			, td
			, tdVal
			, table = _appendChild({
	            elParent: container,
	            newTag:   'table',
	            newElID:  'pascal-table',
	            attribs: [
                    { aName: 'border', aVal: '0' },
                    { aName: 'cellspacing', aVal: '1' },
                    { aName: 'cellpadding', aVal: '3' }
                ]
	        })
	    ;

		// loop through again and replace null with prescribed empty char
		for (; iR < rows; iR++) {
			tr = _appendChild({
	            elParent: table,
	            newTag:   'tr',
	            newElID:  'pascal-tr-' + iR
	        });
			for (; iC < columns; iC++) {
				if (aRows[iR][iC] == empty) {
					aRows[iR][iC] = '';
				}
				td = _appendChild({
		            elParent: tr,
		            newTag:   'td',
		            newElID:  'pascal-td-' + iC,
		            attribs: [
	                    { aName: 'align', aVal: 'center' }
	                ],
		            sText:    aRows[iR][iC]
		        });
			}
			iC = 0;
		}

	}
  
    console.table(aRows);

    /**
     * Append DOM element with its own features to parent element
     * @param       {object}        args                the arguments object
     * @property    {DOMElement}    args.elParent       the parent DOM element   
     * @property    {string}        args.newTag         the new HTML tag to be created  
     * @property    {string}        args.newElID        the new ID to be applied to the element being created  
     * @property    {array}         args.newElClasses   the list of classes to be added to the element being created 
     * @property    {array}         args.attribs        the list of attribute object for name and value to be added to the element being created
     * @property    {string}        args.sText          the text to be added to the DOM node 
     * @return      {DOMElement}                        the newly created DOM element 
     */
    function _appendChild (args) {
        var elParent       = args.elParent
            , newTag       = args.newTag
            , newElID      = args.newElID
            , newEl        = document.createElement(newTag)
            , newElClasses = args.elClasses
            , newElAttr    = args.attribs || null
            , i = 0
        ;

        newEl.id = newElID;

        if (args.sText) {
            var newContent = document.createTextNode(args.sText);
            //add the text node to the newly created div.
            newEl.appendChild(newContent);
        }
        if (newElClasses) {
            newEl.className = newElClasses;
        }

        // if attribute(s), iterate and add all
        if (newElAttr) {
            var newAttr
                , newElAttrLen = newElAttr.length
            ;

            for (; i < newElAttrLen; i++) {
                newAttr = document.createAttribute(newElAttr[i].aName);
                newAttr.value = newElAttr[i].aVal;
                newEl.setAttributeNode(newAttr); // set attribute
            }
        }

        elParent.appendChild(newEl);
        
        return newEl;
    }

}

// run function and embed results onto page
pascal(8, 3,'|','pascal-container')
            
          
!
999px
Loading ..................

Console