Posted By

hand4ever on 07/02/10


Tagged


Versions (?)

环绕数组,螺旋数组


 / Published in: JavaScript
 

  1. Number.prototype.padding = function(length){
  2. return '0'.times(length-(this.toString().length)) + this.toString();
  3. };
  4.  
  5. var N = 20;
  6. var a = [];
  7. var x = y = m = 0;
  8. for(var i = 1;i < N*N+1;i++){
  9. a[x+y*N] = i;
  10. x += ((m+1)&1)*(1-m);
  11. y += ((m+0)&1)*(2-m);
  12. if((x==y)||(x+y==N-1)){
  13. m = (++m)&3;
  14. if(!m){
  15. x = ++y;
  16. }
  17. }
  18. }
  19. var display = "";
  20. for(var j = 0;j < N*N;j++){
  21. if(j%N==0){
  22. display += "<br />"
  23. }
  24. display += " " + a[j].padding(3);
  25. }
  26. document.write(display);
  27.  
  28.  
  29. 其中用到的padding是我自己添加的。

Report this snippet  

You need to login to post a comment.