• Source
    1. import java.util.*;
    2.  
    3. /**
    4.  * Generate gray code sequence of given length
    5.  *
    6.  * The reflected binary code, also known as Gray code after Frank Gray,
    7.  * is a binary numeral system where two successive values differ in only one bit (binary digit).
    8.  *
    9.  * Refer : http://en.wikipedia.org/wiki/Gray_code
    10.  *
    11.  */
    12. class Ideone{
    13.  
    14. public static void main(String[] args){
    15. int length = 4;
    16. List<String> grayCodeSeq = new ArrayList<String>(2);
    17. grayCodeSeq.add("0");
    18. grayCodeSeq.add("1");
    19.  
    20. for(int i=1; i<length; i++){
    21. grayCodeSeq = generateNextSequence(grayCodeSeq);
    22. }
    23.  
    24. printList(grayCodeSeq);
    25. }
    26.  
    27. private static void printList(List<String> list){
    28. for(int i=0; i<list.size(); i++){
    29. System.out.println(list.get(i));
    30. }
    31. }
    32.  
    33. /**
    34. * Generates gray code of next length sequeue
    35. */
    36. private static List<String> generateNextSequence(List<String> grayCodes){
    37. if(grayCodes == null || grayCodes.isEmpty()){
    38. return grayCodes;
    39. }
    40.  
    41. List<String> newSeq = new ArrayList<String>(grayCodes.size());
    42. for(int i=0; i<grayCodes.size();i++){
    43. newSeq.add("0"+grayCodes.get(i));
    44. }
    45.  
    46. //Reverse the list
    47. Collections.reverse(grayCodes);
    48. for(int i=0; i<grayCodes.size();i++){
    49. newSeq.add("1"+grayCodes.get(i));
    50. }
    51. return newSeq;
    52. }
    53. }
    54.