贪吃蛇
有条蛇它长度不固定,蛇头朝北顺时针盘旋着,请打印出如下图的蛇形矩阵。答题时间40分钟。
9 9 9 9 9 9 9
8 6 6 6 6 6 9
8 6 3 3 4 7 9
8 5 3 1 4 7
8 5 2 2 4 7
8 5 5 5 4 7
8 8 8 7 7 7
我的答案(ps:没考虑优化,但是明显数学能力不够,囧,原文见:http://bbs.51js.com/viewthread.php?tid=85907&extra=page%3D1) 引用
function draw(n) {
count = n * (n + 1) / 2;
m = Math.ceil(Math.sqrt(count));
var a = [],b = [];
for (i = 0; i < m; i++) {
a[i] = [];
for (j = 0; j < m; j++) {
a[i][j] = " ";
}
};
for (i = 0; i < n; i++) {
for (j = 0; j < i + 1; j++) {
b.push(i+1);
}
};
//判断第一个
t = Math.ceil(m / 2);
x = t-1;
y = t - 1;
if (m % 2 == 0) {
y = t;
};
x1 = x;
y1 = y;
//开始画
to = 1; //向下 2左 3上 4右
for (i = 0; i < count; i++) {
try {
a[x][y] = b[i] ;
} catch (e) {
};
n = Math.ceil(Math.sqrt(i + 1+1));
if (n % 2 == 0) {
n1 = n / 2+1;
n2 = n / 2+1;
} else {
n1 = Math.ceil(n / 2) - 1;
n2 = Math.ceil(n / 2)
}
if (to == 1) {//向下
if (Math.abs(x + 1 - x1) < n2) {
x = x + 1;
} else {//向左
y = y - 1;
to = 2;
}
} else if (to == 2) {//向左
if (Math.abs(y1 - (y - 1)) < n2 && (y-1) >=0) {
y = y - 1;
} else {//向上
x = x - 1;
to = 3;
}
} else if (to == 3) {//向上
if (Math.abs(x1 - (x - 1)) <= n1 && (x-1) >= 0 ) {
x = x - 1;
} else {//向右
y = y + 1;
to = 4;
}
} else if (to == 4) {//向右
if (Math.abs(y + 1 - y1) <= n1) {
y = y + 1;
} else {//向下
x = x + 1;
to = 1;
}
}
}
var s = "";
for (i = 0; i < m; i++) {
s += a[i].join(" ");
s += "\n";
};
return s;
}
console.log(draw(9));