Javascript code to generate Pascal Triangle
To build a pascal triangle, start with “1” at the top, then continue placing numbers below it in a triangular pattern.
Each number is the sum of numbers directly above it.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | /* Function that takes number of rows as input. Output is a 2D array with the values. */ function generatePascal(n){ //2D array var arr = []; var tmp; for(var i=0;i<n;i++){ //Each element in array is in turn an array // The index is the row number and the array values are the row values arr[i]=[]; for(var j=0; j<=i; j++){ //If index is last element the value is always 1 if(j==i){ arr[i].push(1); }else{ //The following line adds up the two numbers directly above this element. tmp = (!!arr[i-1][j-1]?arr[i-1][j-1]:0)+(!!arr[i-1][j]?arr[i-1][j]:0); arr[i].push(tmp); } } } return arr; } |
Complete code with html,styles and JS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .container { margin: 0 auto; } .block { display: inline-block; position: relative; border: 1px solid grey; text-align: center; font-size: .8em; width: 2em; } .divblock { text-align: center; vertical-align: middle; } #pascal { margin: 0 auto; text-align: center; } .block:nth-child(odd) { background: cyan; } .block:nth-child(even) { background: grey; } </style> <script> function printPascalTriangle(){ document.getElementById("pascal").innerHTML = ""; var rows = document.getElementById("numRows").value; var arr = generatePascal(+rows); for(var i=0;i<arr.length;i++){ var div = document.createElement('div'); div.className ="divblock" for(var j=0;j<arr[i].length;j++){ var span = document.createElement('span'); span.innerHTML=arr[i][j]; span.className ="block"; div.appendChild(span); } document.getElementById("pascal").appendChild(div); } } function generatePascal(n){ var arr = []; var tmp; for(var i=0;i<n;i++){ arr[i]=[]; for(var j=0; j<=i; j++){ if(j==i){ arr[i].push(1); }else{ tmp = (!!arr[i-1][j-1]?arr[i-1][j-1]:0)+(!!arr[i-1][j]?arr[i-1][j]:0); arr[i].push(tmp); } } } return arr; } </script> </head> <body> <div class="container"> <input type="text" placeholder="Enter number of rows for pascal Triangle" style="width:80%" id="numRows"> <input type="button" " value="Go " name="Go " onClick="printPascalTriangle() "> <div id="pascal"></div> </div> </body> </html> |
Final Output for 15 rows:
“There is always something more to learn and understand.”
-Rushi
-Rushi
Jerry
kindly explain why the !! is mandatory in the code
when I removed one of it, the code didn’t run properly again