mirror of
https://hub.njuu.cf/TheAlgorithms/C-Plus-Plus.git
synced 2023-10-11 13:05:55 +08:00
Update gray_code.cpp
This commit is contained in:
parent
21d3875b48
commit
08da689eff
@ -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]);
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user