一道网易笔试题

如图:
 
 
 
设“1”的坐标为(0,0) “7”的坐标为(-1,-1) 编写一个小程序,使程序做到输入坐标(X,Y)之后显示出相应的数字。

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


/*
    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
}


posted @ 2012-09-26 18:45  blong2010  阅读(138)  评论(0编辑  收藏  举报