簡體   English   中英

數組的多維數

[英]Multi Dimentional Number of Array

我必須制作一個2維數組,其中包含從1到height ^ 2迭代的數字。 如果高度為5,則輸入為height,而輸出為此類:

[ [ 21, 22, 23, 24, 25 ],
  [ 20, 19, 18, 17, 16 ],
  [ 11, 12, 13, 14, 15 ],
  [ 10, 9, 8, 7, 6 ],
  [ 1, 2, 3, 4, 5 ] ]

我已經在這里編寫了代碼:

function snakeLadder(height) {

  for (var i = 1; i <= height; i++) {
    var output = [];
    for (var j = 1; j < height; j++) {
      output.push(i + j);
    }
  }
  return output;
}

輸出結果是這樣的:

[ 6, 7, 8, 9, 10 ]
[ 4, 5, 6 ]
[ 3, 4 ]

誰能在我的代碼中查明問題?

您需要一個外部數組,在該數組中可以不移動行。

然后,最好從零循環到小於height並乘以高度和偏移量1以獲得正確的值。

 function snakeLadder(height) { var temp, result = [] for (var i = 0; i < height; i++) { temp = []; for (var j = 0; j < height; j++) { temp.push(i * height + j + 1); } if (i & 1) { temp.reverse(); } result.unshift(temp); } return result; } console.log(snakeLadder(5).map(a => a.join(' '))); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

 function snakeLadder(height) { var result = [] for(var i = height-1; i >= 0; i--) { var row = []; for(var j = 1; j <= height; j++) { // if it's odd rows, increase(push), otherwise decrease(unshift) if((height-i-1)%2 == 0) row.push(height*i + j); else row.unshift(height*i + j); } result.push(row); } return result; } console.log(snakeLadder(5)); 

代碼的主要問題是沒有將行添加到最終的結果數組中。 其次,您需要反轉奇數行以匹配您的預期輸出。

這是一個簡潔的ES6版本,它使用Array構造函數上的... spread運算符來創建行和列,這些行和列被映射到二維結果數組。 使用二進制& 1在行索引j上測試奇偶校驗,以反轉設置了最低有效位的行:

 const snakeLadder = (h, i=h*h) => [...Array(h)].map((r, j) => { const row = [...Array(h)].map(c => i--) return j & 1 ? row : row.reverse(); }) ; console.log(snakeLadder(5)); 

嘗試這個:

  for (var i = 0; i < height; i++) {
      var output = [];
          if((i+2)%2 ==0){
                for (var j = 1; j <=height; j++) {
                          output.push( (i * height ) + j );
                }
          }
          else if( (i%2) ==1){
                 for (var j = height; j>0; j--) {
                           output.push( (i * height) + j );
                }
          }
     }
            return output;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM