Generate Gray Code

Gray Code is a binary code where each successive value differs in only one bit, as well as when wrapping around. Gray code is common in hardware so that we don't see temporary spurious values during transitions.

Given a number of bits n, generate a possible gray code for it.

For example, for n = 2, one gray code would be [00, 01, 11, 10].

Example:

Input:  n = 2
Output: codes = [00,01,11,10]

Approach

C++

#include <bits/stdc++.h>
using namespace std;

vector<stringGreyCode(int n)
{
    vector<stringvec;

    //base case
    if (n <= 0)
        return vec;

    vec.push_back("0");
    vec.push_back("1");

    for (int i = 2i < (1 << n); i = i << 1)

    {
        for (int j = i - 1j >= 0j--)
            vec.push_back(vec[j]);

        //left side add 0
        for (int j = 0j < ij++)
            vec[j] = "0" + vec[j];

        //right side add 1
        for (int j = ij < 2 * ij++)
            vec[j] = "1" + vec[j];
    }

    return vec;
}

int main()
{
    int n = 2;
    vector<stringcodes = GreyCode(n);

    cout << "[";
    for (int i = 0i < codes.size(); i++)

    {
        cout << codes[i];
        if (i != codes.size() - 1)
            cout << ", ";
    }

    cout << "]";

    return 0;
}


No comments:

Post a Comment