[英]Bit-wise shift for Matrix iteration?
我一直在從事這個項目,該項目是我從大學開始的(不再在學校學習,但想擴展它以幫助我提高對C ++的理解)。 我離題了……問題是通過矩陣找到最佳路徑。 我生成一個矩陣,該矩陣填充有一個設置為9的整數值。然后,沿着外邊緣(行0,列長1)創建一條路徑,這樣沿其所有值均為1。
目標是我的程序將通過所有可能的路徑運行並確定最佳路徑。 為了簡化問題,我決定只計算路徑SUM,然后將其與應用程序計算出的SUM相比較。
(標題是前導S =單線程P =多線程)
在一節中,該算法進行了一些簡單的按位移位,以得出迭代的界限。 我的問題是這些移位如何精確地起作用,以便整個矩陣(或MxN數組)被完全遍歷?
void AltitudeMapPath::bestPath(unsigned int threadCount, unsigned int threadIndex) {
unsigned int tempPathCode;
unsigned int toPathSum, toRow, toCol;
unsigned int fromPathSum, fromRow, fromCol;
Coordinates startCoord, endCoord, toCoord, fromCoord;
// To and From split matrix in half along the diagonal
unsigned int currentPathCode = threadIndex;
unsigned int maxPathCode = ((unsigned int)1 << (numRows - 1));
while (currentPathCode < maxPathCode) {
tempPathCode = currentPathCode;
// Setup to path iteration
startCoord = pathedMap(0, 0);
toPathSum = startCoord.z;
toRow = 0;
toCol = 0;
// Setup from path iteration
endCoord = pathedMap(numRows - 1, numCols - 1);
fromPathSum = endCoord.z;
fromRow = numRows - 1;
fromCol = numCols - 1;
for (unsigned int index = 0; index < numRows - 1; index++) {
if (tempPathCode % 2 == 0) {
toCol++;
fromCol--;
}
else {
toRow++;
fromRow--;
}
toCoord = pathedMap(toRow, toCol);
toPathSum += toCoord.z;
fromCoord = pathedMap(fromRow, fromCol);
fromPathSum += fromCoord.z;
tempPathCode = tempPathCode >> 1;
}
if (toPathSum < bestToPathSum[threadIndex][toRow]) {
bestToPathSum[threadIndex][toRow] = toPathSum;
bestToPathCode[threadIndex][toRow] = currentPathCode;
}
if (fromPathSum < bestFromPathSum[threadIndex][fromRow]) {
bestFromPathSum[threadIndex][fromRow] = fromPathSum;
bestFromPathCode[threadIndex][fromRow] = currentPathCode;
}
currentPathCode += threadCount;
}
}
我簡化了代碼,因為所有多余的東西都無濟於事。 同樣,如果人們想知道我編寫了大多數應用程序,但是我以前的老師就給了我使用按位運算符的想法。
我添加了每個線程執行的整個算法。 整個項目仍然是一個進步,但是如果有興趣的話,這里是整個事情的源代碼[GITHUB]
向右移位等於將移位后的比特數除以2。 IE 1 >> 2 = 1 /(2 ^ 2)= 1/4
左移位等效於將移位的位數乘以2。 IE 1 << 2 = 1 * 2 ^ 2 = 1 * 4
我不完全確定該算法的作用,為什么還要將其乘以2 ^(行數-1),然后逐步除以2。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.