javascript实现螺旋数组

javascript版本,可直接粘贴到chrome控制台下运行,
二维数组方式实现最后是一行一行打印的;
支持顺时针和逆时针旋转;
不大喜欢递归,时间空间开销都大,而且还不易修改,算位置的话就纯数学了,我的数学不大好
[img]http://dl.iteye.com/upload/attachment/232550/26fbb66e-5294-3d98-9e42-5ddbc5ef0256.png[/img]

(function(){
var RIGHT = 0, DOWN = 1, LEFT = 2, UP = 3;//闭包常量
//初始化参数
positonManager = function(length,clockwise){
this.length = length;
this.clockwise=clockwise;
this.cx = 0;//当前x坐标
this.cy = 0;//当前y坐标
this.cn = 1;//当前数值
this.cm = clockwise?RIGHT:DOWN;//当前移动方向
this.positions = new Array(length);//空的二维数组
for (var i = 0; i < length; i++) {
this.positions[i] = new Array(length);
}
this.positions[0][0] = ' 1';
}

positonManager.prototype = {
moveNext: function(){
if (this.addNewNum(this.cm)) {//继续上次方向
return true;
}
else
if (this.addNewNum((this.cm + (this.clockwise?1:3))%4)) {//因为是个螺旋,转向只能按照固定次序进行循环!
return true;
}
return false;//无路可走了!
},
//根据方向获取下一地点后判断是否已占位,未占位则赋值,已占位返回false
addNewNum: function(m){
var xy = this.getNewPosition(m);
if (xy !== false && this.positions[xy[1]][xy[0]] == undefined) {
this.cn++;
this.positions[xy[1]][xy[0]] = this.cn < 10 ? ' ' + this.cn : '' + this.cn;
this.cx = xy[0];
this.cy = xy[1];
this.cm = m;
return true;
}
return false;
},
//根据方向获取下一地点,越界返回false
getNewPosition: function(dir){
switch (dir) {
case RIGHT:
return (this.cx + 1 == this.length ? false : [this.cx + 1, this.cy]);
case DOWN:
return (this.cy + 1 == this.length ? false : [this.cx, this.cy + 1]);
case LEFT:
return (this.cx == 0 ? false : [this.cx - 1, this.cy]);
case UP:
return (this.cy == 0 ? false : [this.cx, this.cy - 1]);
}
},
printAll: function(){
var i, j,line;
while (this.moveNext()){}
for (i=0; i < this.length; i++) {
line='';
for (j=0; j < this.length; j++) {
line+=this.positions[i][j]+' ';
}
console.log(line);
}
}
}
})()

console.log('int i=5;');
var thread1 = new positonManager(5,false);
thread1.printAll();
console.log('int i=6;');
var thread = new positonManager(6,true);
thread.printAll();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值