在群里看到一道题目, 按一定的方式打印矩阵中相应位置的值
看到题目直接写的代码草稿:
function getNum(n, type, arr) { var exp = ["i", "i * (n-1) +1", "(n-1)*n+i", "n*(n-i-1) + (n-i)"]; var temp = []; for(var i = 1; i<=n; i++) { if(type === 1){ arr.push(eval(exp[type])); } if(type === 0 && i !== n) { arr.push(eval(exp[type])); } if(type === 2 && i !== 1) { arr.push(eval(exp[type])); } if(type === 3 && i !== n) { arr.push(eval(exp[type])); } } } (function(n) { var arr = []; for(var i = 0; i < 4; i++) { getNum(n, i, arr); } console.log(arr.join(',')); })(5);
代码解耦:
function getNum(n, type) { var exp = ["i", "i * (n-1) +1", "(n-1)*n+i", "n*(n-i-1) + (n-i)"]; var temp = []; for(var i = 1; i<=n; i++) { if(type === 1){ temp.push(eval(exp[type])); } if(type === 0 && i !== n) { temp.push(eval(exp[type])); } if(type === 2 && i !== 1) { temp.push(eval(exp[type])); } if(type === 3 && i !== n) { temp.push(eval(exp[type])); } } return temp; } (function(n) { var arr = []; var temp = null; for(var i = 0; i < 4; i++) { temp = getNum(n, i); arr = arr.concat(temp); } console.log(arr.join(',')); })(5);
代码最终优化后:
function getNum(n, type) { var exp = ["i", "i * (n-1) +1", "(n-1)*n+i", "n*(n-i-1) + (n-i)"]; var temp = []; for(var i = 1; i<=n; i++) { if(type === 1 || ((type === 0 || type === 3) && i !== n) || (type === 2 && i !== 0)) { temp.push(eval(exp[type])); } } return temp; } (function(n) { var arr = []; for(var i = 0; i < 4; i++) { arr = arr.concat(getNum(n, i)); } console.log(arr.join(',')); })(5);
当然目前这个code只能满足从1开始递增的数据, 当然如果是随意的矩阵, 只需要将n维矩阵转换为一维数组,同时结果作为数组下标即可得到输出;
end!