Guys, help with the code gray. I can not bring to mind. In response, displays 1110, 1110, 1111, 1111.

import java.io.*; public class cod { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int m; String settext = ""; int i = 4; //указываем длинну double k = Math.pow(2, i); int[][] code = new int[int k][i + 1]; code[1][i] = 0; code[2][i] = 1; for (int a = 2; a <= i; a++) { m = (int) (Math.pow(2, a)); for (int b = (int) (Math.pow(2, a - 1)) + 1; b <= m; b++) { code[b] = code[m - b + 1]; code[m - b + 1][i - a + 1] = 0; code[b][i + 1 - a] = 1; } } for (int n = 1; n <= k; n++) { for (int q = 1; q <= i; q++) { settext = Integer.toString(code [n][q]) ; System.out.print(settext); System.out.print (" "); } System.out.println(); } } } 
  • more information what you want to get? - Viacheslav
  • one
    @Viacheslav, don't you know the gray code?))))) - Gorets
  • It is necessary to display 0000 0001 0010, etc. and it turns out 1110 1110 1111 1111, etc. - Alex20
  • I know him, but I don’t know how to write to work in the right language - Alex20
  • 2
    in your code, the devil will break your leg, and comments like //указываем длинну does not help anything, if you naming the variables somehow corresponded to their purpose and the comments were not for a tick, maybe everything was much simpler, you are not taught this? - Specter

2 answers 2

Read the article on the wiki for specific examples in C. You just have to make a port in Java. And there the code is much more optimal than yours.
UPD
The code in the article does exactly what you want in Java.

  • Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at cod.main (cod.java:23) this one - Alex20
  • Well, now this kind of training, that you do everything yourself, how do you do it? ” Alex20
  • System.out.println ("0000"); System.out.println ("0001"); System.out.println ("0010"); Yes, this is exactly what I brought out, but without using the array task in this way and, accordingly, it is impossible through printn - Alex20
  • 3
    I tested it before posting :) Everything works. public static void main (String [] args) {int N = Integer.parseInt (args [0]); gray ("", N); } You just need to either pass the arguments, or int N = 4; - ReinRaus 1:01 pm

Here is a rather laconic implementation :

 int g (int n) { return n ^ (n >> 1); } 

This method finds the next, knowing the previous one.

  • on the wiki, too, this example is - Specter
  • Only this is C. In Java, this construction does not give what is needed. - ReinRaus