Skip to content

Commit

Permalink
Update gray_code.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
Harshdev098 authored Oct 9, 2023
1 parent 21d3875 commit 08da689
Showing 1 changed file with 12 additions and 11 deletions.
23 changes: 12 additions & 11 deletions bit_manipulation/gray_code.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,24 @@
#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) {

std::vector<std::string> generateGrayCode(int n) {
// Base case
if (n == 1) {
vector<string> grayCode;
std::vector<std::string> grayCode;
grayCode.push_back("0");
grayCode.push_back("1");
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++) {
grayCode.push_back("0" + prevGrayCode[i]);
}
Expand All @@ -39,18 +39,19 @@ vector<string> generateGrayCode(int n) {
*/

void testGrayCodeGeneration() {
vector<pair<int, vector<string>>> testCases = {
std::vector<std::pair<int, std::vector<std::string>>> testCases = {
{1, {"0", "1"}},
{2, {"00", "01", "11", "10"}},
{3, {"000", "001", "011", "010", "110", "111", "101", "100"}},
// Add more test cases as needed
};

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;
const std::vector<std::string>& expected = testCase.second;
std::vector<std::string> result = generateGrayCode(n);
assert(result == expected);
std::cout << "Test for " << n << " bits passed!" << std::endl;
}
}

Expand Down

0 comments on commit 08da689

Please sign in to comment.