Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var pascalsTriangle = function () {
- "use strict";
- var tri = [[1]];
- var nextRow = function (prevRow) {
- var ary = [];
- // // more efficient for loop
- // prevRow = [0].concat(prevRow);
- // ary = new Array(prevRow.length);
- // for (var i = 0, j = ((prevRow.length + prevRow.length % 2) / 2) ; i < j ; i += 1 ) {
- // ary[i] = prevRow[i] + prevRow[i + 1];
- // }
- // for (j = prevRow.length - 1 ; i <= j ; i += 1) {
- // ary[i] = ary[j - i];
- // }
- ary = [0].concat(prevRow).map((v,i,a)=> v + (i + 1 < a.length ? a[i+1] : 0));
- return ary;
- };
- var triangle = function self(n) {
- if (n <= tri.length) {
- return tri.slice(0, n);
- }
- tri = self(n - 1);
- var prevRow = tri[tri.length - 1];
- tri.push(nextRow(prevRow));
- return tri;
- };
- var row = function (n) {
- if (tri.length < n) {
- tri = [].concat(triangle(n));
- }
- return tri[n - 1];
- };
- return {
- triangle: triangle,
- row: row,
- reset: function(){tri = [[1]];}
- };
- };
- var algorithm = pascalsTriangle();
- var start_time;
- var end_time;
- var result;
- start_time = performance.now();
- result = algorithm.triangle(5);
- end_time = performance.now();
- console.log("calculate 5 rows", result[4], end_time - start_time);
- test(100);
- result = algorithm.triangle(999);
- start_time = performance.now();
- result = algorithm.triangle(999);
- end_time = performance.now();
- console.log("retrieve 999 rows from cache", result[4], end_time - start_time);
- function rep(x,f){
- while (x > 0) {
- f();
- x -= 1;
- }
- }
- function test(x) {
- start_time = performance.now();
- rep(x, function(){ result = 0; result = algorithm.triangle(999); algorithm.reset(); });
- end_time = performance.now();
- console.log("Avg time to calculate 999 rows, tested " + x + " times", result[4], (end_time - start_time)/x);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement