我正在進行一項作業,其中我必須逐行填寫一個二維數組。如果該行的索引值爲,甚至(0,2,4等),則該行必須從填充,從右到左。如果該行的索引值爲不均勻(1,3,5等...),那麼它必須從左至右填充。我應該在我的if語句中填入什麼條件才能以這種方式填充行?如何確定數組索引是否均勻?
謝謝!
我正在進行一項作業,其中我必須逐行填寫一個二維數組。如果該行的索引值爲,甚至(0,2,4等),則該行必須從填充,從右到左。如果該行的索引值爲不均勻(1,3,5等...),那麼它必須從左至右填充。我應該在我的if語句中填入什麼條件才能以這種方式填充行?如何確定數組索引是否均勻?
謝謝!
您需要使用模或餘數操作。假設i是不均勻的數字,因此i%2將評估爲。對於偶數i%2將導致。正如評論中指出的那樣,使用條件 if (row_index % 2 == 0) {*do right to left thing*} else {do right to left thing}
。
作爲用戶與奇怪的名字,我不知道如何引用(對不起,請隨時編輯你的名字在這裏)指出,我%2 == 0應該解決這個問題。
%(模)運算符返回整數除法的餘數,因此,如果行數爲偶數則可以除以2,並具有沒有餘數(I%2 == 0)
int[][] toBeFilled = new int[width][height];
for(int i=0;i<width;i++) {
if(i%2==0)
//Fill toBeFilled[i] from Right to Left
else
//Fill toBeFilled[i] from from Left to Right
}
以下是可能有所幫助的代碼示例。請注意,這是C#(我現在沒有坐在Java編譯器前面),所以有一些很小的語法差異,但它應該仍然非常易讀。
private static int[][] BuildArrays()
{
Random random = new Random();
// Whatever size you want
int[][] array = new int[random.Next(1, 100)][];
for (int i = 0; i < array.Length; i++)
{
// Make an array of whatever size you want
array[i] = new int[random.Next(1, 50)];
// % is the modulo operator
// Basically, this means "remainder when the index is divided by 2"
// By definition, even numbers are evenly divisible by 2 and odd numbers aren't
if (i % 2 == 0)
{
// Even - we fill right to left
for (int j = array[i].Length - 1; j >= 0; j--)
{
// Enter whatever you want
array[i][j] = random.Next();
}
}
else
{
// Odd - we fill left to right
for (int j = 0; j < array[i].Length; j++)
{
array[i][j] = random.Next();
}
}
}
return array;
}
i%2 == 0會檢查 –
或者if(index&1){/ *它很奇怪* /}' –