簡體   English   中英

將數組拆分為大塊的麻煩

[英]Trouble with splitting an array into chunks

我有一個數組:

private static int[] array = {5, 2, 1, 6, 3, 7, 8, 4};

我正在嘗試將其拆分為帶有x個塊的二維數組,其中所有塊的長度相等(在我的情況下為2),然后將原始數組的每個值分配給數組。 然后,它將增加塊編號的索引,並重置遍歷單個數組的索引長度為1的索引。

問題是,我編寫的執行所有未輸出內容的代碼:

public class Debug 
{
     private static int[] array = {5, 2, 1, 6, 3, 7, 8, 4};

     private static void chunkArray(int chunkSize) 
     {
         int chunkNumIndex = 0;
         int chunkIndex = 0;
         int numOfChunks = (int)Math.ceil((double)array.length / chunkSize);
         int[][] twoDimensionalArray = new int[numOfChunks][chunkSize];

         for (int i = 0; i < array.length; i++)
         {
             twoDimensionalArray[chunkNumIndex][chunkIndex] = array[i];
             chunkIndex++;

             while(chunkNumIndex < numOfChunks)
             {
                 if (chunkIndex == chunkSize)
                 {
                     chunkNumIndex++;
                     chunkIndex = 0;
                 }
             }
         }

         for(int i = 0; i < chunkNumIndex; i++)
         {
             for(int j = 0; j < chunkIndex; j++)
             {
                 System.out.printf("%5d ", twoDimensionalArray[i][j]);
             }

             System.out.println();
         }
     }

     public static void main(String args[])
     {
         chunkArray(2);
     }
  }

有人可以協助調試我的程序嗎?

問題是您有不必要的while(chunkNumIndex < numOfChunks) ,這沒有任何意義。 if語句足以正確地迭代變量:

    for (int i = 0; i < array.length; i++) {
        twoDimensionalArray[chunkNumIndex][chunkIndex] = array[i];
        chunkIndex++;
        if (chunkIndex == chunkSize) {
            chunkNumIndex++;
            chunkIndex = 0;
        }
    }

另外,請記住, chunkNumIndexchunkIndex的值是動態的,因此對於最后一個for循環,請改用twoDimensionalArray.lengthtwoDimensionalArray[0].length

    for(int i = 0; i < twoDimensionalArray.length; i++) {
        for(int j = 0; j <  twoDimensionalArray[0].length; j++) {
            System.out.printf("%5d ", twoDimensionalArray[i][j]);
        }
    }

您正在使此操作變得不必要地困難,無需保留chunkIndex和chunkNumIndex的計數器,我們只需div和mod i即可。

int numOfChunks = (array.length / chunkSize) + (array.length % chunkSize == 0 ? 0 : 1);
int[][] twoDimensionalArray = new int[numOfChunks][chunkSize];
for (int i = 0; i < array.length; i++) {
    twoDimensionalArray[i / chunkSize][i % chunkSize] = array[i];
}

這樣的事情應該已經做好了。

暫無
暫無

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

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