您的位置:首页 > 其它

一道网易笔试题

2012-09-26 18:45 239 查看
如图:



 
设“1”的坐标为(0,0) “7”的坐标为(-1,-1) 编写一个小程序,使程序做到输入坐标(X,Y)之后显示出相应的数字。
原题的讨论见如下链接
/article/2410341.html

下面贴出我自己的解法,与大家分享:

/*
7 8 9 10
6 1 2 11
5 4 3 12
16 15 14 13

as the matrix shows, we set 1 with pos(0, 0), 2 with pos(1, 0)
3 with pos(1, 1), 4 with pos(0, 1) ....
I found that pos(1, 1) = 3 = 2*2-2+1, pos(2, 2) = 13 = 4*4-4+1
so the solution based on this is showed below
*/
//for input x, y, we return pos(x, y), pos(0, 0) = 1 ...
int GetVal(int x, int y)
{
//r means half of the width of the matrix,
// for 1 2
// 4 3, r = 2/2 = 1 ,
int r = max(abs(x), abs(y));
if(r == 0) return 1;
//rb means right and bottom number, here we mean 1, 3, 13 ...
//first we get the right and bottom number, then get others are easy
int rb = (2*r)*(2*r)-2*r+1;
if(x == r && y > -r ){ // the number over, eg. for rb = 13, number over // is 12 11 10 ...
return rb-(r-y);
}
if(y == -r){ //top level
return rb+4*r+(x-(-r));
}
if(y == r) //bottom level
return rb+r-x;
return rb+2*r+r-y;//left
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: