From 08da689effa9ffe641b466061ed3ea9457143e52 Mon Sep 17 00:00:00 2001 From: Harsh Dev Pathak <118347330+Harshdev098@users.noreply.github.com> Date: Mon, 9 Oct 2023 09:23:45 +0530 Subject: [PATCH] Update gray_code.cpp --- bit_manipulation/gray_code.cpp | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/bit_manipulation/gray_code.cpp b/bit_manipulation/gray_code.cpp index 1359075e8..3f07a4a9c 100644 --- a/bit_manipulation/gray_code.cpp +++ b/bit_manipulation/gray_code.cpp @@ -2,24 +2,24 @@ #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) { + +std::vector generateGrayCode(int n) { + // Base case if (n == 1) { - vector grayCode; + std::vector grayCode; grayCode.push_back("0"); grayCode.push_back("1"); return grayCode; } - vector prevGrayCode = generateGrayCode(n - 1); + std::vector prevGrayCode = generateGrayCode(n - 1); - vector grayCode; + std::vector grayCode; for (int i = 0; i < prevGrayCode.size(); i++) { grayCode.push_back("0" + prevGrayCode[i]); } @@ -39,18 +39,19 @@ vector generateGrayCode(int n) { */ void testGrayCodeGeneration() { - vector>> testCases = { + std::vector>> 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& expected = testCase.second; - vector result = generateGrayCode(n); - assert(result == expected); - cout << "Test for " << n << " bits passed!" << endl; + const std::vector& expected = testCase.second; + std::vector result = generateGrayCode(n); + assert(result == expected); + std::cout << "Test for " << n << " bits passed!" << std::endl; } }