Java Перестановка рекурсии с помощью вспомогательного метода - PullRequest
0 голосов
/ 01 мая 2020

Я получаю сообщение об ошибке при выполнении домашнего задания с помощью метода permutationHelper.

Автоматическая система оценок под названием zybooks не сообщает мне, в чем я ошибаюсь ...

Однако, это дает мне ошибку, которая говорит:

Test feedback : permutation("123") incorrectly returned с моим выводом, показывающим: Your output : 123 132 213 231 312 321, который, imo, выглядит точно так, как и предполагалось.

(инструкторы оставили пример в закомментированном коде) .

Мне бы очень хотелось понять, почему я получаю эту ошибку, даже если кажется, что код работает нормально. Или Если есть лучший способ выполнить задачу.

Примечание

Мне не разрешено изменять параметры или заголовки метода.

Вот мой код ниже.

    /*
    * The following method is given to you, and you will be responsible for completing the permutationHelper method it calls.
    * Sometimes, helper methods are used for recursive methods when another parameter is needed to recursively call a method repeatedly, but passing that parameter initially doesn't make sense.
    */
    public static String permutation(String word){
        return permutationHelper(" ", word);
    }

    /* permutationHelper()
    * This method is called by the permutation method.
    * Given a string, return a string that lists all possible permutations of the letters in the string, with spaces preceding each permutation.
    * For example, "123" would give "123 132 213 231 312 321". 
    * The perm parameter keeps track of the current permutation you are creating.
    * Consider using the a for loop to call the method recursively a certain number of times with different parameters, so you cover all permutations.
    */
    public static String permutationHelper(String perm, String word) {
        if (word.isEmpty()) return perm;
        String a = "";

        for (int i = 0; i < word.length(); i++)
        {
            a += permutationHelper(perm.trim() + word.charAt(i) + " ", word.substring(0, i) + word.substring(i+1, word.length()));
        }
        return a;
    }  

Любое руководство будет с благодарностью.

1 Ответ

0 голосов
/ 01 мая 2020
    /*
* The following method is given to you, and you will be responsible for completing the permutationHelper method it calls.
* Sometimes, helper methods are used for recursive methods when another parameter is needed to recursively call a method repeatedly, but passing that parameter initially doesn't make sense.
*/
public static String permutation(String word){
    return permutationHelper(" ", word);
}

/* permutationHelper()
* This method is called by the permutation method.
* Given a string, return a string that lists all possible permutations of the letters in the string, with spaces preceding each permutation.
* For example, "123" would give "123 132 213 231 312 321". 
* The perm parameter keeps track of the current permutation you are creating.
* Consider using the a for loop to call the method recursively a certain number of times with different parameters, so you cover all permutations.
*/
public static String permutationHelper(String perm, String word) {
    if (word.isEmpty()) return perm;
    String a = "";

    for (int i = 0; i < word.length(); i++) a += permutationHelper(perm + word.charAt(i), word.substring(0, i) + word.substring(i+1, word.length()));
    return a;
}   

Ошибка была в Инструкции. Профессора сказали игнорировать прокомментированные примеры и удостовериться, что перманент предшествует слову.

...