选择格雷码中的一些数字编码

问题描述 投票:1回答:2

我必须编写一个程序,显示一些用格雷码编码的数字。我已经在这个页面中找到了用C ++编写的算法(qazxsw poi)。

但是我想创建一种新的方法来删除连续两个“1”并且在其末端(左和右)具有“1”的数字。

示例:对于n = 3,我们得到这个数字:

https://www.geeksforgeeks.org/given-a-number-n-generate-bit-patterns-from-0-to-2n-1-so-that-successive-patterns-differ-by-one-bit/

现在我要删除这些数字:011,110,111,101并显示列表中提醒的其他数字。

我的想法是创建一个矢量矢量。例如,当n = 3时:{{000},{001},{011},{010},{110},{111},{101},{100}}。

对于大小,它将是这样的:

000
001
011
010
110
111
101
100

例如:vector [0] [1] = {0}和vector [1] [2] = {1}如果我的大小正确的话。

现在要删除连续两个“1”并且在其末端有“1”的数字,我可以使用以下代码:

int m = pow(2,n);
int vector[m][n];

现在的问题是我不知道如何将结果存储在我的向量中用C ++编写的格雷码中,或者可能有一种方法可以在不使用向量的情况下比较此代码中的两个数字。

c++ algorithm vector gray-code
2个回答
0
投票

当你使用更大的字符串时,这将是额外的工作,并且代码阅读起来并不容易。如何创建一个简单的面具?将一对连续的1位移位数字(num)的长度。

while (i < m){
for (j=0; j<n-1; j++){
if (vector[i][j]==vector[i][j+1]==1 && vector[i][0]==vector[i][n-1]==1 ) 
    i=i+1; //Don't show this number
else { cout <<vector[i][j] << endl; i=i+1; }
}
}

0
投票

不使用位操作,这肯定会更快,因为你有一个矢量矢量,执行删除的一种方法是使用mask = 0b11000 // fill in the correct quantity of 0s end_mask = 0b10001 while mask > 1 if (num && mask) == mask remove num from array mask = mask >> 1 if num && end_mask == end_mask remove num from array 使用谓词来查找相邻的1,并使用std::adjacent_find删除那些符合标准的矢量相邻的1。

这是一个例子:

std::remove_if

#include <algorithm> #include <vector> #include <iostream> #include <iterator> bool findOnes(const std::vector<int>& v) { // less than 2 digits, so can't do anything if ( v.size() < 2 ) return false; // test extremes if ( v.front() == 1 && v.back() == 1 ) return true; // check if there are adjacent 1's return std::adjacent_find(v.begin(), v.end(), [&](int n1, int n2) { return n1 == 1 && n2 == 1; }) != v.end(); } int main() { //test std::vector<std::vector<int>> vect = {{0,0,0},{0,0,1},{0,1,1},{0,1,0},{1,1,0},{1,1,1},{1,0,1},{1,0,0}}; // erase the vectors that match the criteria vect.erase(std::remove_if(vect.begin(), vect.end(), findOnes), vect.end()); // show the final results for ( auto& i : vect ) { std::copy(i.begin(), i.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; } }

基本上,如果Live Example找不到相邻的1,则返回的迭代器将是adjacent_find。因此,在end()谓词函数中,在对大小和极值进行简单测试之后,findOne接管并完成其余的工作。

© www.soinside.com 2019 - 2024. All rights reserved.