everycode
everycode copied to clipboard
2014年12月3日 D5
今天的题目,我怎么可能告诉你们,这是我小学的时候的家庭作业。
/*
* 根据传入的参数,返回一个构成杨辉三角形的数组
* PS:如果你不知道杨辉三角形是什么的话,那为什么不去问问神奇海螺呢!
* 当然,你如果能在console里面输出出来那就更棒了!
* param Number
* return Array
* [1]
* [1 1]
* [1 2 1]
* [1 3 3 1]
*/
function pascal(depth) {
//code here
}
pascal(1) // => [[1]]
pascal(5) // => [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
性能测试代码
// 执行opt();函数获取性能指标
function opt() {
var timeStart = new Date();
pascal(10000);
var timeEnd = new Date();
console.log('1万次耗时' + (timeEnd - timeStart) / 1000 + 's');
}
function pascal(depth) {
var result = [[1],[1, 1]];
if(depth==1){ return result.splice(0,1)};
if(depth==2){ return result};
for(var i = 2 ; i< depth; i++){
result[i] = [1];
result[i-1].reduce(function(prev, current){result[i].push(prev+current);return current;});
result[i].push(1);
}
return result;
}
----for替换reduce
function pascal(depth) {
var result = [[1],[1, 1]], prev, tmp, i , j, len;
if(depth==1){ return result.splice(0,1)};
if(depth==2){ return result};
for(i = 2 ; i < depth; i++){
tmp = [1];
prev = result[i-1];
for(j = 1, len = prev.length; j < len; j++){
tmp.push(prev[j]+prev[j-1]);
}
tmp.push(1);
result[i] = tmp;
}
return result;
}
function pascal(depth) {
var l = [[1]];
for (var i = 1; i < depth; i++) {
var s = [];
var last = l[l.length - 1];
for (var j = -1; j < last.length; j++)
(j === -1 || j === last.length - 1) ? s.push(1) : s.push(last[j] + last[j + 1]);
l.push(s);
}
return l;
}
function pascal(depth) {
return (new Array(depth - 1)).join("€").split("€").reduce(function(arr) {
return arr.push((new Array(arr.length + 1)).join("囍").split("囍").map(function(_, idx) {
return idx || idx !== arr[arr.length - 1].length ? arr[arr.length - 1][idx - 1] + arr[arr.length - 1][idx] : 1;
})), arr;
}, [[1]]);
}
function pascal(depth) {
var arr = [[1]]
for(var i=1;i<depth;i++){
arr[i] = []
for(var j=0;j<=i;j++){
arr[i][j] = (arr[i-1][j] || 0) + (arr[i-1][j-1] || 0);
}
}
return arr;
}
function pascal(n) {
if (n > 1) {
return recursive(pascal(n - 1));
} else {
return [1];
}
}
function recursive(arr) {
var newArr = [1];
arr.sort(function(a, b) {
newArr.push(a + b);
});
newArr.push(1);
return newArr;
}
function pascal(depth) {
var i= 1,res=[[1]], j,len,tarr;
if(depth == 1){
return res
}
for(;i<depth;i++){
res[i]=[1];
tarr=res[i-1];
for(j=1,len=tarr.length;j<len;j++){
res[i].push(tarr[j]+tarr[j-1]);
}
res[i].push(1);
}
return res
}