簡體   English   中英

對角處理二維陣列

[英]Processing a 2D Array Diagonally

我正在為我的計算機科學課開發一個Cipher項目,我們應該將一個字符串放入一個方形2D數組中,用星號填充剩余的空間,然后通過對角遍歷該數組來打印出已編碼的消息。

例如,使用消息“ testcipher”,該數組將為

[t,e,s,t]

[c,i,p,h]

[e,r,*,*]

[*,*,*,*]

然后,該數組將被處理為“ ti * * ep * * she * tcr *”

我真的可以為此提供一些幫助。 提前致謝!

讓我們逐步進行:

1)我們需要找到2D數組的尺寸。 由於必須平方,所以我們必須找到大於或等於字符串長度的第一個平方數。

小修改:我假設密碼是一個字符串。

int arrayDimension = 0;
while (arrayDimension * arrayDimension < cipher.length())
{
    arrayDimension++;
}

2)現在我們將密碼逐字符放置在數組中。

int currentCharacterIndex = 0;
for (int i = 0; i < arrayDimension; i++)
{
    for (int j = 0; j < arrayDimension; j++)
    {
        if (currentCharacterIndex < cipher.length()) 
            array[i][j] = cipher.charAt(currentCharacterIndex++);
        else
            array[i][j] = '*';
    }
}

我想這可以簡化,但是這段代碼的目的是讓您理解這個想法,並希望編寫出更好的版本。

3)我們有數組,因此最簡單的方法是將所有行(第一行除外)向左rowIndex次移動。

因此,基本上,對於一排ciph我們將以iphc結尾。 結果,我們現在必須打印每列,並且我們的工作已經完成。

代碼應如下所示(非常簡單,因此我將其留給您):

//Shift each row
char firstColumnChar;
for (int rowIndex = 0; rowIndex < arrayDimension; rowIndex++)
{
    //We shift rowIndex times
    for (int timesToShift = rowIndex; timesToShift > 0; timesToShift--)
    {
        firstColumnChar = array[rowIndex][0]; //We keep the first char in some variable
        //We shift all elements to the left - except for the first one
        for (int i = 0; i < rowIndex - 1; i++)
            array[rowIndex][i] = array[rowIndex][i+1];

        //We now shift the first character to the last column
        array[rowIndex][arrayDimension - 1] = firstColumnChar;
    }
}

//Print columns
for (int columnIndex = 0; columnIndex < arrayDimension; columnIndex++)
{
    for (int rowIndex = 0; rowIndex < arrayDimension; rowIndex++)
        System.out.print(array[rowIndex][columnIndex] + " ");
    //You can print a '\n' here if you want to
}

暫無
暫無

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

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