From 1457fe4cc45fe81e42d4cb7b988eb7b141c4bc53 Mon Sep 17 00:00:00 2001 From: Subhradeep Saha Date: Fri, 1 May 2020 15:02:42 +0530 Subject: [PATCH] Gray Code generation of any input bit length (#2005) --- Gray_Code/Gray_Code.cpp | 53 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Gray_Code/Gray_Code.cpp diff --git a/Gray_Code/Gray_Code.cpp b/Gray_Code/Gray_Code.cpp new file mode 100644 index 0000000000..2c349500b2 --- /dev/null +++ b/Gray_Code/Gray_Code.cpp @@ -0,0 +1,53 @@ +//C++ program to generate the Gray Code for any input bit length + +#include +#define pb push_back +using namespace std; + +// Function to generate the Gray Code sequence +void Gray(int n){ + //If input size is less than or equal to 0 + if(n <= 0){ + cout << "Invalid input"; + return; + } + + vector v; + v.pb("0"); + v.pb("1"); + + for(int i = 2; i < (1 << n); i <<= 1){ + for(int j = i - 1; j >= 0; j--) + v.pb(v[j]); + + for(int j = 0; j < i; j++) + v[j] = "0" + v[j]; + + for(int j = i; j < 2 * i; j++) + v[j] = "1" + v[j]; + } + + cout << "Gray Code for bit length = " << n << " : " << endl; + + for(int i = 0; i < v.size(); i++) + cout << v[i] << endl; +} + +int main(){ + int n; + cout << "Enter the bit length for Gray Code generation : "; + cin >> n; + Gray(n); +} + +/* Sample input-output +Enter the bit length for Gray Code generation : 3 +Gray Code for bit length = 3 : +000 +001 +011 +010 +110 +111 +101 +100 */