Update gray_code.cpp

This commit is contained in:
Harsh Dev Pathak 2023-10-09 09:23:45 +05:30 committed by GitHub
parent 21d3875b48
commit 08da689eff
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -2,24 +2,24 @@
#include <iostream> #include <iostream>
#include <vector> #include <vector>
using namespace std;
/** /**
* Function to generate Gray code sequence for 'n' bits. * Function to generate Gray code sequence for 'n' bits.
* *
* @param n - The number of bits for which to generate Gray code. * @param n - The number of bits for which to generate Gray code.
* @return A vector of strings representing the Gray code sequence. * @return A vector of strings representing the Gray code sequence.
*/ */
vector<string> generateGrayCode(int n) {
std::vector<std::string> generateGrayCode(int n) {
// Base case
if (n == 1) { if (n == 1) {
vector<string> grayCode; std::vector<std::string> grayCode;
grayCode.push_back("0"); grayCode.push_back("0");
grayCode.push_back("1"); grayCode.push_back("1");
return grayCode; return grayCode;
} }
vector<string> prevGrayCode = generateGrayCode(n - 1); std::vector<std::string> prevGrayCode = generateGrayCode(n - 1);
vector<string> grayCode; std::vector<std::string> grayCode;
for (int i = 0; i < prevGrayCode.size(); i++) { for (int i = 0; i < prevGrayCode.size(); i++) {
grayCode.push_back("0" + prevGrayCode[i]); grayCode.push_back("0" + prevGrayCode[i]);
} }
@ -39,18 +39,19 @@ vector<string> generateGrayCode(int n) {
*/ */
void testGrayCodeGeneration() { void testGrayCodeGeneration() {
vector<pair<int, vector<string>>> testCases = { std::vector<std::pair<int, std::vector<std::string>>> testCases = {
{1, {"0", "1"}}, {1, {"0", "1"}},
{2, {"00", "01", "11", "10"}}, {2, {"00", "01", "11", "10"}},
{3, {"000", "001", "011", "010", "110", "111", "101", "100"}}, {3, {"000", "001", "011", "010", "110", "111", "101", "100"}},
// Add more test cases as needed
}; };
for (const auto& testCase : testCases) { for (const auto& testCase : testCases) {
int n = testCase.first; int n = testCase.first;
const vector<string>& expected = testCase.second; const std::vector<std::string>& expected = testCase.second;
vector<string> result = generateGrayCode(n); std::vector<std::string> result = generateGrayCode(n);
assert(result == expected); assert(result == expected);
cout << "Test for " << n << " bits passed!" << endl; std::cout << "Test for " << n << " bits passed!" << std::endl;
} }
} }