2012-08-26 23 views
0

這個問題似乎基本到一些人,但我一直在分析和解剖沒有成功將該代碼作爲這個permutation程序由羅伯特·塞奇威克如何打印的文字或字符,而無需使用System.out的組合。在方法perm1和perm2中打印。任何幫助或解釋傻瓜非常感謝。先謝謝你。解釋Java的程序排列

這是鏈接下的代碼:

public class Permutations { 
    // print N! permutation of the characters of the string s (in order) 
    public static void perm1(String s) { perm1("", s); } 
    private static void perm1(String prefix, String s) { 
     int N = s.length(); 
     if (N == 0) System.out.println(prefix); 
     else { 
      for (int i = 0; i < N; i++) 
      perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, N)); 
     } 
    } 
    // print N! permutation of the elements of array a (not in order) 
    public static void perm2(String s) { 
    int N = s.length(); 
    char[] a = new char[N]; 
    for (int i = 0; i < N; i++) 
     a[i] = s.charAt(i); 
    perm2(a, N); 
    } 

    private static void perm2(char[] a, int n) { 
     if (n == 1) { 
      System.out.println(a); 
      return; 
     } 
     for (int i = 0; i < n; i++) { 
      swap(a, i, n-1); 
      perm2(a, n-1); 
      swap(a, i, n-1); 
     } 
    } 

    // swap the characters at indices i and j 
    private static void swap(char[] a, int i, int j) { 
     char c; 
     c = a[i]; a[i] = a[j]; a[j] = c; 
    } 

    public static void main(String[] args) { 
    int N = Integer.parseInt(args[0]); 
    String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
    String elements = alphabet.substring(0, N); 
    perm1(elements); 
    System.out.println(); 
    perm2(elements); 
    } 
} 
+0

這是可怕的代碼。命名函數和變量,使用'String'連接 - 邪惡。 – Sulthan

+0

但它確實使用它們,只是在它們的第二次重載中。你瞭解它的其餘部分是如何工作的,對嗎? – dasblinkenlight

+0

@Sulthan It't可能是一個天真的Java實現一個衆所周知的遞歸置換算法的。典型的課堂代碼。 –

回答

2

這是正確的有:

if (N == 0) System.out.println(prefix); 

System.out.printSystem.out.println基本相同,只是後來的打印文本後換行。

+0

感謝您的回覆,如果N等於零,我認爲該行只打印出前綴?意思是沒有檢測到輸入? – dimas

+1

它是一個遞歸函數調用中,N總是減小,並最終達到零,並且該函數打印並終止。 – Matzi