Question

Implement the binary reflected Gray code algorithm for generating subsets in Java

Implement the binary reflected Gray code algorithm for generating subsets in Java

0 0
Add a comment Improve this question Transcribed image text
Answer #1

// Generating n-bit Gray codes
import java.util.*;
class GfG {

// It generates all n bit Gray codes and outputs the generated codes
static void generateGraycodes(int n)
{
   if (n <= 0)
       return;

   // 'sets' will store all generated codes
   ArrayList<String> sets= new ArrayList<String> ();

   // start with 1-bit pattern
    sets.add("0");
    sets.add("1");

   // Every iteration of this loop generates 2*i codes from previously
   // generated i codes.
   int i, j;
   for (i = 2; i < (1<<n); i = i<<1)
   {
       // Enter the prviously generated codes again in sets[] in reverse
       // order. Nor sets[] has double number of codes.
       for (j = i-1 ; j >= 0 ; j--)
            sets.add(sets.get(j));

       // append 0 to the first half
       for (j = 0 ; j < i ; j++)
            sets.set(j, "0" + sets.get(j));

       // append 1 to the second half
       for (j = i ; j < 2*i ; j++)
            sets.set(j, "1" + sets.get(j));
   }

   // print contents of sets[]
   for (i = 0 ; i < sets.size() ; i++ )
       System.out.println(sets.get(i));
}

//Main Function
public static void main(String[] args)
{
   generateGraycodes(3);
}
}

Add a comment
Know the answer?
Add Answer to:
Implement the binary reflected Gray code algorithm for generating subsets in Java
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT