Subscribe RSS

叶子

叶子的阳光和天堂
  • Index
  • Tag
  • Link
  • Archiver
  • Guestbook
  • About
Home » 手 » 51js一贴

51js一贴

November 4, 2009 Posted by 叶子 under 手
No Comments

有条蛇它长度不固定,蛇头朝北顺时针盘旋着,请打印出如下图的蛇形矩阵。答题时间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;
}
alert(draw(9));

Tags: 51js, javascript

Leave a Reply Cancel reply

You must be logged in to post a comment.

« jquery 在maxthon和ie6下的一个小bug
maxthon的css mode »
Search
Tag
51js alcatel android apple apps audio barbone d510mo droid x g450 godaddy google hosting html5 ie6 interview ipod javascript jquery lunarpages me811 motorola ot-c123 QQ shuffle sony ericsson thinkpad toshiba x10i 世纪公园 东芝 域名 天台山 小帅 拙政园 摩托罗拉 日志 浙江 猫 索尼爱立信 网络 苏州 阿尔卡特 面试 龙穿峡
Category
  • 好 (12)
  • 手 (7)
  • 游 (4)
  • 闲 (211)
Calendar
November 2009
S M T W T F S
« Oct   Dec »
1234567
891011121314
15161718192021
22232425262728
2930  
Recent Posts
  • 测试下关联博客
  • 2012来了
  • ipad2 3g 64G
  • 上海车展
  • 随拍
  • android的html5之audio
  • apple magic mouse
  • godaddy的org续费2年起?
Recent Comments
    Meta
    • Register
    • Log in
    • Entries RSS
    • Comments RSS
    • WordPress.org
    叶子 powered by WordPress and The Clear Line Theme