Hanoi Tower, stop moving

I developed a solution to the Hanoi Tower problem:

public static void bewege(int h, char quelle, char ablage, char ziel) {  
  if(h > 0){
     bewege(h - 1, quelle, ziel, ablage);
     System.out.println("Move "+ h +" from " + quelle + " to " + ziel);
     bewege(h - 1, ablage, quelle, ziel);
 }
}

It works great. Now I want to limit the number of slides and throw an exception if a certain limit is reached. I tried it with a counter, but it does not work:

class HanoiNK{

 public static void main(String args[]){
   Integer n = Integer.parseInt(args[0]);
   Integer k = Integer.parseInt(args[1]);

   try{
    bewege(k, n, 'A', 'B', 'C');
   }catch(Exception e){
    System.out.println(e);
   }
 }

 public static void bewege(int c, int h, char quelle, char ablage, char ziel) 
    throws Exception{  
  if(h > 0){
   if(c != 0){
   bewege(c, h - 1, quelle, ziel, ablage);
   c--;
   System.out.println("Move "+ h +" from " + quelle + " to " + ziel);
   bewege(c, h - 1, ablage, quelle, ziel);
   c--;
   }else{ 
    throw new Exception("stop sliding");
   }
  }
 }
}

An exception is never thrown. Any ideas?

UPDATE: the result is 6 slides, but it should be 5 http://ideone.com/lm084

0
source share
3 answers

About the topic:

It seems to me that it is counternot defined anywhere, and therefore it should not be compiled.

Now that you have edited your question to fix this, an exception will be thrown if your first argument is greater than your second argument, for example:

java HanoiNK 5 3

, c == 0 h == 1, .


. :

Integer n = Integer.parseInt(args[0]);
Integer k = Integer.parseInt(args[1]);

int n = Integer.parseInt(args[0]);
int k = Integer.parseInt(args[1]);

... parseInt int (not Integer) , , int (not Integer). -, , , .

+1

counter == c? c--; bewege(c, h - 1, ablage, quelle, ziel);, , :

 public static void bewege(int c, int h, char quelle, char ablage, char ziel) 
throws Exception{       
    if(h > 0){
        if(c != 0){
        c--;
        bewege(c, h - 1, quelle, ziel, ablage);
        System.out.println("Move "+ h +" from " + quelle + " to " + ziel);
        c--;
        bewege(c, h - 1, ablage, quelle, ziel);
        }else{  
            throw new Exception("stop sliding");
        }
    }
}
+1

I’m not sure where the variable is declared counter(it seems there isn’t here), but you will not reduce it anywhere, so its value will never change.

0
source

Source: https://habr.com/ru/post/1782930/


All Articles