C++将矩阵列映射到秩 - 位操作

C++ map matrix column into rank - bit manipulations

本文关键字:位操作 映射 阵列 C++      更新时间:2023-10-16

我有用uint64_t表示的(二进制)矩阵(从C++11开始)。我希望能够有效地从任何列映射到第一列。例如

0 1 0 0 0 0 0 0
0 1 0 0 0 0 0 0
0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0
0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0
uint64_t matrice = 0x4040400040400040uLL;
uint64_t matrice_2 = map(matrice, ColumnEnum::Column2);
1 1 1 0 1 1 0 1
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0

matrice_2包含 0xED00000000000000uLL;

好问题。我真的很喜欢黑客攻击。 这是我的解决方案:

uint64_t map(uint64_t x, int column)
{
  x = (x >> (7 - column)) & 0x0101010101010101uLL;
  x = (x | (x >> 7)) & 0x00FF00FF00FF00FFuLL;
  x = (x | (x >> 14))& 0x000000FF000000FFuLL;
  x = (x | (x >> 28))& 0x00000000000000FFuLL;
  return x << 56;
}

一个工作示例可以在 ideone 中找到,其中调用确实map(matrice, ColumnEnum::Column2) .

一个不错的小谜语。这是一个相当可读的版本:

matrice = (matrice >> (8ull - column)) & 0x0101010101010101ull;
uint64_t result((  ((matrice >>  0ul)  & 0x01ull)
                 | ((matrice >>  7ul)  & 0x02ull)
                 | ((matrice >> 14ull) & 0x04ull)
                 | ((matrice >> 21ull) & 0x08ull)
                 | ((matrice >> 28ull) & 0x10ull)
                 | ((matrice >> 35ull) & 0x20ull)
                 | ((matrice >> 42ull) & 0x40ull)
                 | ((matrice >> 49ull) & 0x80ull)) << 56ull);

首先为每一列定义位掩码:

uint64_t columns[8] = {
  0x8080808080808080uLL,
  0x4040404040404040uLL,
  //...
  0x0101010101010101uLL
};

通过将列位掩码应用于"矩阵",您只能获得此列:

uint64_t col1 = matrice & columns[1]; // second column - rest is empty

通过移动,您只能获得第一列大小写:

uint64_t col0 = (col1 << 1); // second column - rest is empty
//                       ^ this number is just zero based index of column,,,

现在第一个位在正确的位置 - 只需设置接下来的 7 位:

 col0 |= (col0 & (1 << 55)) << 7; // second bit...
 // ....

或者只是使用std::bitset<64>,我会做的。