我正在計算n維數組轉換爲平面1d數組的索引。行主要訂單地址計算
private int toFlatindex(int... dimensionIndices){
int index = 0;
for (int k = dimensionIndices.length - 1; k >= 0; k--) {
// Check if the specified index is within the bounds of the array
if(dimensionIndices[k] < 0 || dimensionIndices[k] >= dimensionSizes[k]) {
return -1;
}
// get the index in the flat array using the formula from https://en.wikipedia.org/wiki/Row-major_order#Address_calculation_in_general
int start = 1;
for (int l = dimensionSizes.length - 1; l >= k+1; l--) {
start = start * dimensionSizes[l];
}
index += dimensionIndices[k]*start;
}
return index;
}
我寫了這個代碼,這似乎和測試正確的。雖然我編寫了維基百科的公式,但我並不完全理解發生了什麼。我希望有人解釋這一點,或者甚至更好地鏈接地址計算中的視頻教程/講座。