- function print_number(x)
- {
- var n=x; //input number
- var tmp = [];
- var i=0;
- var j=0;
- for (i=0; i<n; i++)
- tmp[i] = [];
-
- i=0;
- var v=1;
- tmp[i][j] = v; //base case: size=1
- j++;
- v++;
- while ((i!=0) || (j!=0 && j<n)) //if not returning to the starting point, loop it
- {
- if ((i == 0) && (j<n-1)) //top edge
- {
- tmp[i][j] = v;
- j++;
- }
- else if ((j==n-1) && (i<n-1)) //right edge
- {
- tmp[i][j] = v;
- i++;
- }
- else if ((i==n-1) && (j>0)) //bottom edge
- {
- tmp[i][j] = v;
- j--;
- }
- else if ((j==0) && (i>0)) //left edge
- {
- tmp[i][j] = v;
- i--;
- }
-
- //increment v
- if (v == 9)
- v = 0;
- else
- v++;
- }
- //output
- var out_str;
- for (i=0; i<n; i++)
- {
- out_str = "";
- for (j=0; j<n; j++)
- {
- if (i==0 || i==n-1 || j==0 || j==n-1) //if it is the edge, print the value, else print a space
- out_str += tmp[i][j];
- else
- out_str += " ";
- }
- console.log(out_str);
-
- }
- };
複製代碼 Javascript, 可直接開chrome F12 去run, 簡單快捷
路過見到個post, 冇諗過數學pattern, 好直觀咁跟住4條邊順時針寫落個array 再output返出黎
都只係一個while loop就寫左落個array, 加一個nested for loop 黎output
睇返頭幾樓d ching 有point out 個pattern
跟返個pattern既話, 寫array 個loop 都可以慳返, 直接print d value出黎都仲得 |