js实现杨辉三角
function yanghui(hang) {
//创建一维数组
var arr = new Array(hang);
//在一维数组中插入二维数组
for (let i = 0; i < arr.length; i++) {
arr[i] = new Array(i + 1);
}
//1
//1 1
//1 2 1
//1 3 3 1
//1 4 6 4 1
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
if (j == 0 || j == i) {
arr[i][j] = 1;
// console.log("\n");
} else {
arr[i][j] = arr[i - 1][j] + arr[i - 1][j - 1];
}
}
}
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) {
document.write(arr[i][j] + " ")
}
document.write("<br/>")
}
}
数组旋转
function rightMoveOne(arr) {
var temp = arr[arr.length - 1];
for (let i = arr.length - 2; i >= 0; i--) {
arr[i + 1] = arr[i];
}
arr[0] = temp;
}
function leftMoveOne(arr) {
var temp = arr[0];
for (let i = 0; i <arr.length; i++) {
arr[i] = arr[i+1];
}
arr[arr.length-1] = temp;
}
/**
*
* @param times 移动位数
* @param dir 移动方向 1右 -1左
* @returns {number}
* @constructor
*/
function Move(times,dir) {
if (dir == null){
return 0;
}else if(dir > 0){
for (let i = 0; i < times; i++) {
rightMoveOne(arr);
}
}else {
for (let i = 0; i <times ; i++) {
leftMoveOne(arr);
}
}
}