Algorithm: Design gray code by divide-and-conquer method

Source: Internet
Author: User

Problem Description:

The gray code is a sequence of 2n in length. There are no identical originals in the sequence, each element is a string of n bits in length, and the adjacent element is just one bit different. By using the method of divide and conquer, an algorithm is designed to construct the corresponding gray code for arbitrary N.

Algorithm design:

N=1, Gray code: 0,1

n=2, Gray Code: 00, 10, 11,01

N=3, Gray code: 000,010,011,001,101,111,110,100

N=4, when, Gray code: 0000,0010,0011,0001,0101,0111,0110,0100, 1100,1110,1111,1101,1001,1011,1010,1000

From the above can be seen as follows: Starting from n=2, each n gray code consists of two parts. After a bit of gray code can be obtained from the previous Gray code, that is, the first half of the gray code of n is n-1 all gray code in the front plus 0 to get; n the second half of the gray code is n-1 all gray code reverse order in front plus 1 get.

Realize:

Import java.awt.*; import javax.swing.*; import Java.math.*;  Public classgray{ Public Static voidMain (String args[]) {string []graycode; intN,PN; String Str=joptionpane.showinputdialog ("Please enter N:"); N=integer.parseint (str); PN=(int) Math.pow (2, N); Graycode=NewSTRING[PN];  for(intL=0; l<pn;l++) {Graycode[l]="";    } code (N,PN,GRAYCODE); }    Static voidCodeintNintpn,string graycode[]) {        if(0==N) {System. out. Print ("input Error!"); }        Else if(1==N) {graycode[0]="0"; graycode[1]="1"; }        Else        {            intt=1; intlen=1;  while(t<PN) {T=2*T; Len++;  for(intI=0; i<t/2; i++) {Graycode[i]="0"+Graycode[i]; }                 for(intj=t;j>t/2; j--) {graycode[j-1]="1"+graycode[t-j].substring (1, len-1); }            }        }         for(intm=0; m<pn;m++) {System. out. printf ("%3d", M); System. out. Print ("Gray Code:"); System. out. println (Graycode[m]); }     }}

Algorithm: Design Gray code with divide-and-conquer method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.