feat:add graycode algorithm

This commit is contained in:
Harsh Dev Pathak 2023-10-08 10:40:23 +05:30
parent 6376bf46af
commit 21d3875b48

View 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;
}