mirror of
https://hub.njuu.cf/TheAlgorithms/C-Plus-Plus.git
synced 2023-10-11 13:05:55 +08:00
feat:add graycode algorithm
This commit is contained in:
parent
6376bf46af
commit
21d3875b48
60
bit_manipulation/gray_code.cpp
Normal file
60
bit_manipulation/gray_code.cpp
Normal file
@ -0,0 +1,60 @@
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
|
||||
/**
|
||||
* Function to generate Gray code sequence for 'n' bits.
|
||||
*
|
||||
* @param n - The number of bits for which to generate Gray code.
|
||||
* @return A vector of strings representing the Gray code sequence.
|
||||
*/
|
||||
vector<string> generateGrayCode(int n) {
|
||||
if (n == 1) {
|
||||
vector<string> grayCode;
|
||||
grayCode.push_back("0");
|
||||
grayCode.push_back("1");
|
||||
return grayCode;
|
||||
}
|
||||
vector<string> prevGrayCode = generateGrayCode(n - 1);
|
||||
|
||||
vector<string> grayCode;
|
||||
for (int i = 0; i < prevGrayCode.size(); i++) {
|
||||
grayCode.push_back("0" + prevGrayCode[i]);
|
||||
}
|
||||
for (int i = prevGrayCode.size() - 1; i >= 0; i--) {
|
||||
grayCode.push_back("1" + prevGrayCode[i]);
|
||||
}
|
||||
|
||||
return grayCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test function for Gray code generation.
|
||||
*
|
||||
* This function tests the generateGrayCode function with various test cases
|
||||
* and uses the assert function to check if the generated sequence matches
|
||||
* the expected sequence.
|
||||
*/
|
||||
|
||||
void testGrayCodeGeneration() {
|
||||
vector<pair<int, vector<string>>> testCases = {
|
||||
{1, {"0", "1"}},
|
||||
{2, {"00", "01", "11", "10"}},
|
||||
{3, {"000", "001", "011", "010", "110", "111", "101", "100"}},
|
||||
};
|
||||
|
||||
for (const auto& testCase : testCases) {
|
||||
int n = testCase.first;
|
||||
const vector<string>& expected = testCase.second;
|
||||
vector<string> result = generateGrayCode(n);
|
||||
assert(result == expected);
|
||||
cout << "Test for " << n << " bits passed!" << endl;
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
testGrayCodeGeneration();
|
||||
return 0;
|
||||
}
|
Loading…
Reference in New Issue
Block a user