c ++ language divide and conquer strategy to generate Gray code

Gray code is a string of 2 ^ n sequences. No sequence identical elements, each of length n is (0,1) strings, only just adjacent to a different element.

Here are a few low Golay code

A Gray code (2 ^ 1 = 2) 2-bit Gray code (2 ^ 2 = 4) 3-bit Gray code (2 ^ 3 = 8) 4-bit Gray code (2 ^ 4 = 16) other…
0 00 000 0000
1 01 001 0001
11 011 0011
10 010 0010
110 0110
111 0111
101 0101
100 0100
1100
1101
1111
1110
1010
1011
1001
1000

Not difficult to draw from the above table:

  • A Gray code has two code words 0
  • (N + 1) before 2 ^ n-bit Gray code codewords is equal to n-bit code words of a Gray code, in the order written, prefix 0
  • (N + 1) in the Gray code bit 2 ^ n codewords is equal to n-bit code words of a Gray code, written in reverse order, prefix 1
  • n + 1-bit Gray code set = n-bit Gray code set (order) prefixed 0 + n-bit Gray code set (reverse) prefixed 1

Use two-dimensional array and recursively to solve the problem:

  • n = 1, arr[0][0] = 0, arr[1][0] = 1
  • n> 1, the recursive illustrated as follows:
0 1 2 3 4 n
0 0 0 0
1 1 0 0
2 1 1 0
3 0 1 0
4 0 1 1
5 1 1 1
6 1 0 1
7 0 0 1
n

Gray code output, the output from right to left

#include <iostream> 
#include<math.h> 
using namespace std; 
void Gray(int **arr,int sum, int n) {     //Gray生成函数
    if (n == 1) {
        arr[0][0] = 0;
        arr[1][0] = 1;
        return;
    }
    Gray(arr,sum / 2, n - 1);
    for (int i = 0; i < sum / 2; i++) {		//循环作用为添加 0 和 1 
        arr[i][n - 1] = 0;
        arr[sum - i - 1][n - 1] = 1;
    }	
    for (int i = sum / 2; i < sum; i++) {	//循环作用为 倒序复制
        for (int j = 0; j < n - 1; j++)
            arr[i][j] = arr[sum - i - 1][j];
    }
}
int main()
{
    int n;
    int** arr;
    cout << "输入n: ";
    cin >> n;
    int sum = pow(2, n);  
    arr = new int* [sum];       //动态二维数组
    for (int i = 0; i < sum; i++)
        arr[i] = new int[n];
    Gray(arr, sum, n);		//生成格雷码
    for (int i = 0; i < sum; i++) {	//输出,方向为右向左  ←
        for (int j = n-1; j>=0  ; j--)
        {
            cout << arr[i][j];
        }
        cout << endl;
    }
    for (int i = 0; i < sum; i++)	//释放内存
        delete[] arr[i];
    delete[] arr;
    return 0;
}

Run renderings
Here Insert Picture Description
If you find this article useful to you, please choose a praise it ~ pwp ~ °

Published an original article · won praise 2 · views 50

Guess you like

Origin blog.csdn.net/weixin_43853811/article/details/105080371