From 21d3875b481cce42c361400143d0421192e84497 Mon Sep 17 00:00:00 2001 From: Harsh Dev Pathak Date: Sun, 8 Oct 2023 10:40:23 +0530 Subject: [PATCH] feat:add graycode algorithm --- bit_manipulation/gray_code.cpp | 60 ++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 bit_manipulation/gray_code.cpp diff --git a/bit_manipulation/gray_code.cpp b/bit_manipulation/gray_code.cpp new file mode 100644 index 000000000..1359075e8 --- /dev/null +++ b/bit_manipulation/gray_code.cpp @@ -0,0 +1,60 @@ +#include +#include +#include + +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 generateGrayCode(int n) { + if (n == 1) { + vector grayCode; + grayCode.push_back("0"); + grayCode.push_back("1"); + return grayCode; + } + vector prevGrayCode = generateGrayCode(n - 1); + + vector 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>> 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& expected = testCase.second; + vector result = generateGrayCode(n); + assert(result == expected); + cout << "Test for " << n << " bits passed!" << endl; + } +} + +int main() { + testGrayCodeGeneration(); + return 0; +}