|
是不是又是什么面试亚?以前国内面试人家的时候出过类似的题。这里给你一个c++的解决方法吧,思路是一样的。在matlab里面,你只要将下面的代码存成myCYCLE.cpp,然后用mex myCYCLE.cpp然后就可以运行了;结果如下:
>>mex myCYCLE.cpp
>>myCYCLE(5)
ans =
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
>> A = myCYCLE(4)
A =
7 8 9 10
6 1 2 11
5 4 3 12
16 15 14 13
>>
- //---------------------------------------------------------------------------
- //File Name: myCYCLE.cpp
- //---------------------------------------------------------------------------
- #include "mex.h"
- #define MY_LCC
- //---------------------------------------------------------------------------
- #define MY_RIGHT 0
- #define MY_DOWN 1
- #define MY_LEFT 2
- #define MY_UP 3
- //---------------------------------------------------------------------------
- void myFill(double *pData, int n){
- int nX, nY, nLen, nNum, i, j=n*n;
- int nCount = 0;
- int nDir = MY_RIGHT;
- nNum = nLen = 1;
- nX = nY = (n - 1) / 2;
- pData[nX + nY*n] = nNum++; // position of 1
- while(nNum <= j ){
- for(i = 0; i < nLen; i++){
- switch(nDir){
- case MY_LEFT: nY--; break;
- case MY_RIGHT: nY++; break;
- case MY_UP: nX--; break;
- case MY_DOWN: nX++; break;
- default: break;
- }
- pData[nX + nY*n] = nNum++;
- }
- nCount++;
- if((nCount&1)== 0)nLen++;
- nDir = (nDir + 1) & 3;
- }
- }
- //---------------------------------------------------------------------------
- #ifndef MY_LCC
- //---------------------------------------------------------------------------
- //#pragma argsused
- //int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void* lpReserved)
- //{
- // return 1;
- //}
- //---------------------------------------------------------------------------
- void _export mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
- #else
- void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
- #endif
- {
- int n = 13;
- double pOut;
- if (1!=nrhs && 0!=nrhs) mexErrMsgTxt("Using: aOut = myCYCLE( n ); Default or In case any error in the input value, n=13");
- if (1==nrhs)
- if (!mxIsDouble(prhs[0])|| mxIsComplex(prhs[0]) || mxGetN(prhs[0]) * mxGetM(prhs[0]) != 1 ){
- printf("Using: aOut = myCYCLE( n ); and n must be a Scalar, now 13 is used !");
- }else n = (int) mxGetScalar(prhs[0]);
- if(n<1)n = 13;
- plhs[0] = mxCreateDoubleMatrix(n , n, mxREAL);
- myFill((double *)mxGetPr(plhs[0]), n);
- }
复制代码
[ 本帖最后由 recbio 于 2007-9-19 16:58 编辑 ] |
评分
-
1
查看全部评分
-
|