Matrix迭代的按位移位?

时间:2015-09-18 05:09:33

标签: c++ matrix bitwise-operators bit-shift

确定一些背景

我一直致力于这个项目,我在大学时就开始了这个项目(不再在学校但是想扩展它以帮助我提高对C ++的理解)。我离题了...问题是通过矩阵找到最佳路径。我生成一个填充了整数值的矩阵,假设为9.然后,我沿着外边创建一条路径(第0行,第1行,第1行),以便沿着它的所有值都是1.

目标是我的程序将遍历所有可能的路径并确定最佳路径。为了简化问题,我决定只计算路径SUM,然后将其与应用程序计算的SUM进行比较。

enter image description here

(标题是未命中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]

1 个答案:

答案 0 :(得分:1)

右位移相当于将2除以移位的位数的幂。 IE 1&gt;&gt; 2 = 1 /(2 ^ 2)= 1/4

左移位相当于将2乘以移位的位数。 IE 1&lt;&lt; 2 = 1 * 2 ^ 2 = 1 * 4

我不完全确定该算法的作用以及为什么需要乘以2 ^(num rows - 1)然后逐渐除以2。

相关问题