Skip to content

Instantly share code, notes, and snippets.

@davidcalhoun
Last active December 14, 2017 17:38
Show Gist options
  • Save davidcalhoun/5f2622837eb0ca93e7e6 to your computer and use it in GitHub Desktop.
Save davidcalhoun/5f2622837eb0ca93e7e6 to your computer and use it in GitHub Desktop.

Revisions

  1. davidcalhoun renamed this gist Nov 6, 2015. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. davidcalhoun created this gist Nov 6, 2015.
    42 changes: 42 additions & 0 deletions pascal's triangle in javascript
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    function pt(lineLimit, lines) {
    // Seed the first value.
    if(!lines || lines.length === 0) return pt(lineLimit, [[1]]);

    var newLine = [];
    var lastLine = lines[lines.length - 1];

    // Fill out inner values
    for(var i=1, len=lastLine.length; i<len; i++) {
    newLine.push(lastLine[i - 1] + lastLine[i]);
    }

    // Add 1s border to both sides.
    newLine.unshift(1);
    newLine.push(1);

    // Add the new line to the lines array.
    lines.push(newLine);

    if(lineLimit === lines.length) {
    // Finished!
    return lines;
    } else {
    // Generate the next line.
    return pt(lineLimit, lines);
    }
    }

    pt(5);

    /*

    Output:
    [
    [ 1 ],
    [ 1, 1 ],
    [ 1, 2, 1 ],
    [ 1, 3, 3, 1 ],
    [ 1, 4, 6, 4, 1 ]
    ]

    */