
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
A backtracking approach to generate n bit Gray Codes ?
In this section we will see how we can generate the gray codes of n bits using backtracking approach? The n bit gray code is basically bit patterns from 0 to 2^n – 1 such that successive patterns differ by one bit. So for n = 2, the gray codes are (00, 01, 11, 10) and decimal equivalent is (0, 1, 3, 2). The program will generate the decimal equivalent of the gray code values.
Algorithm
generateGray(arr, n, num)
begin if n = 0, then insert num into arr return end if generateGray(arr, n-1, num) num := num XOR (1 bit left shift of n-1) generateGray(arr, n-1, num) end
Example
#include<iostream> #include<vector> using namespace std; void generateGray(vector<int>&arr, int n, int &num){ if(n==0){ arr.push_back(num); return; } generateGray(arr, n-1, num); num = num ^ (1 << (n-1)); generateGray(arr, n-1, num); } vector<int> gray(int n){ vector<int> arr; int num = 0; generateGray(arr, n, num); return arr; } main() { int n; cout << "Enter number of bits: "; cin >> n; vector<int> grayCode = gray(n); for(int i = 0; i<grayCode.size(); i++){ cout << grayCode[i] << endl; } }
Output
Enter number of bits: 3 0 1 3 2 6 7 5 4
- Related Articles
- Python Program to Generate Gray Codes using Recursion
- JavaScript to generate random hex codes of color
- Conversion of Binary to Gray Code\n
- Conversion of Gray Code to Binary\n
- What is Gray code?\n
- How to generate a random 128 bit strings using Python?
- Introduction to Backtracking
- Introduction to Backtracking Algorithms
- What is the difference between Backtracking and Non- Backtracking?
- How to gray out (disable) a Tkinter Frame?
- Error Correcting Codes - Hamming codes
- Java Program to generate n distinct random numbers
- How to generate an UnsupportedOperationException in Java?\n
- Error Correcting Codes - Reed-Solomon codes
- 8085 program to convert gray to binary

Advertisements