Как можно распечатать визуализацию на факториал числа с рекурсией - PullRequest
0 голосов
/ 16 мая 2018

Я знаю, как вычислить факториал числа, но я хочу отобразить то, что происходит в памяти, при вызове самого метода. Таким образом, факториал, использующий рекурсию, выглядит как пара

public static long factorial(int n) { 
    if (n == 1) return 1; 
    return n * factorial(n-1); 
} 

и я хочу добиться следующего

factorial(5) 
   factorial(4) 
      factorial(3) 
         factorial(2) 
            factorial(1) 
               return 1 
            return 2*1 = 2 
         return 3*2 = 6 
      return 4*6 = 24 
   return 5*24 = 120

Я пришел к этому моменту ... У меня проблемы с отображением рекурсивного возврата метода (вторая часть)

public static long factorial(int n) {   
    System.out.println("factorial("+n+")");
    if (n == 1) {
        System.out.println("return 1");
        return 1; 
    }       
    return n * factorial(n-1);      
} 

Ответы [ 2 ]

0 голосов
/ 16 мая 2018

Попробуйте распечатать перед возвратом:

public static long factorial(int n) {   
    System.out.println("factorial("+n+")");
    if (n <= 1) { // factorial(0) = factorial(1) = 1
        System.out.println("return 1");
        return 1; 
    }
    long fac = factorial(n-1);
    System.out.printf("return %d * %d = %d%n", n, fac, n * fac);
    return n * fac;      
} 

Чтобы получить n пробелов в строке, вы можете добавить вспомогательную функцию, которая принимает текущую «глубину» рекурсии и, соответственно, печатать n пробелов.

// public function visible to the world
public static long factorial(int n) {   
    return factorial(5, 0);
} 

// helper function that takes in the current depth of 
// the recursion
private static long factorial(int n, int depth) {
    String spaces = repeat(' ', depth);
    System.out.print(spaces);
    System.out.println("factorial("+n+")");
    if (n <= 1) { // factorial(0) = factorial(1) = 1
        System.out.println(spaces + " return 1");
        return 1; 
    }

    long fac = factorial(n-1, depth + 1);
    System.out.print(spaces);
    System.out.printf("return %d * %d = %d%n", n, fac, n * fac);
    return n * fac;      
}

// helper function to create a String by repeating
// char c, n times.
private static String repeat(char c, int times) {
    char[] sequence = new char[times];
    Arrays.fill(sequence, c);
    return new String(sequence);
}
0 голосов
/ 16 мая 2018

Вы можете использовать блоки try {} finally {}, чтобы сделать что-то "после" того, что было возвращено

public static long factorial(int n) {
    try {
        System.out.println("factorial(" + n + ")");
        if (n == 1) {
            System.out.println("return 1");
            return 1;
        }
        return n * factorial(n - 1);
    } finally {
        System.out.println("return " + n);
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...