2012-10-31 3 views
8

사이트에 비슷한 도움이되는 몇 가지 질문이 있지만이 문제를 해결할 수는 없으므로 반복되지 않기를 바랍니다.반복에서 Java의 배열 순열

이것은 숙제 지정으로 [A, B, C]의 문자 배열로되어 있으며 반복을 사용하여 모든 순열을 가져와야합니다 (반복 사용). 나는 일종의이 코드는 다음을 수행합니다

char[] c = {'A', 'B' , 'C'}; 

public void printAll(char[] c, int n, int k) { 
    if (k == n) { 
     System.out.print(c); 
     return; 
    } 
    else { 
     for (int j = 0; j<n; j++) { 
     for (int m = 0; m<n; m++) { 
      System.out.print(c[k]); 
      System.out.print(c[j]); 
      System.out.print(c[m] + "\r\n"); 
     } 
     } 
    }   
    printAll(c, n, k+1);  
} 

그러나,이 기능은 길이 3의 모든 순열을 인쇄하는 동안, 그것은 길이 2. 그들을 할 수 있도록 출력의 길이를 정의해야 매개 변수 N 내가 생각할 수있는 모든 것을 시도해 보았고 Google 검색 결과를 검토해 보았습니다. 오히려 간단한 문제인 것처럼 보이는 것을 해결할 수 없다는 이유로 나 자신이 더 심했습니다.

+0

는 "반복과"여기 무슨 뜻입니까? – seh

+0

일단 문자를 사용하면 다시 사용할 수 있습니다. 그래서 가능한 출력의 수는 3^3이 아니라 3^3입니다. – user1788424

답변

6

과 동일하지만 당신은 당신이 만든 것들을 추적해야한다는 것입니다 , 문자 세트 c 및 원하는 길이 n이 주어집니다.

기술적으로 반복되는 순열과 같은 것은 없습니다. 나는 길이가 n이고 길이가 c 인 모든 문자열을 원한다고 가정합니다.

(핵심 아이디어는 다음과 같습니다 반복으로 지정된 캐릭터 라인의 순열을 생성하기 위해 C# 버전을 여기

printAll(char[] c, int n, String start){ 
    if(start.length >= n){ 
    System.out.println(start) 
    }else{ 
    for(char x in c){ // not a valid syntax in Java 
     printAll(c, n, start+x); 
    } 
    } 
} 
+0

입니다. 선생님은 단지 신사가 아니며 학자 일뿐입니다. 당신은 왕자, 신사 그리고 학자입니다. 어떤 다른 사람들은 문자열을 사용하지 않고 배열을 사용하는 것을 제외하고는 비슷한 것을 제안했습니다. 그러나 당신의 설명은 훨씬 더 분명했습니다. – user1788424

+0

참고로 누구나 관심이있는 경우 n 매개 변수가 인쇄되는 각 줄의 길이를 제어하는 ​​마지막 함수가 있습니다. public void printAll3 (char [] c, int n, int k, String s) { if (s.length()> = n) {System.out.print (s + "\ r \ n");return;} else if (k user1788424

+0

@JanDvorak 나는 이것이 오래되었다는 것을 알고 있지만 해결하려고 노력하고있는 유사한 문제가 있으며 수정하여 완전히 완료되었습니다. 최종 호출 printAll (c, n, 시작 + x)가 작동합니다. 나는 그것을 인쇄하고 처음 몇 통화 (a, aa, aaa, aab, aac, ab, aba)에 대해 이렇게 시작합니다. 나는 그것이 왜 끝나지 않는지 이해하지 못한다. (abc, abcabc, abcabcabc). 당신이 설명 할 수 있기를 바랬습니다. 나는 그것을 추적하려고 노력하고 있으며 매번 인쇄 할 때마다 자신을 n 번 더 호출하는 루프 내부에서 호출한다는 것을 알고 있습니다. 어쨌든 할 수만 있다면 좀 더 설명 해주고 싶습니다. – MichelleJS

1

방금 ​​아이디어가있었습니다. 숨겨진 캐릭터 (H 숨김) [A, B, C, H]를 추가 한 다음 고정 길이의 순열을 모두 수행하면 어떻게 할 것인지를 알 수 있습니다. 그런 다음 그것을 읽으면 숨겨진 캐릭터에 머물게됩니다. [B, A, H, C]는 (B, A)가됩니다.

흠는 단점은 만약 내가 제대로 이해 [B가, H, A, C가] [B, H, C, A]

+0

문제를 올바르게 이해하면 필요한 순열 길이는 –

1

됩니다 : 코드에서

to generate all strings of length N with letters from C 
-generate all strings of length N with letters from C 
    that start with the empty string. 

to generate all strings of length N with letters from C 
    that start with a string S 
-if the length of S is N 
    -print S 
-else for each c in C 
    -generate all strings of length N with letters from C that start with S+c 

:

당신은이 방법을 수행 할 수 있습니다 - 길이가 n이고 반복이있는 순열의 수는 n^n입니다.

string[] GetPermutationsWithRepetition(string s) 
     { 
      s.ThrowIfNullOrWhiteSpace("s"); 
      List<string> permutations = new List<string>(); 
      this.GetPermutationsWithRepetitionRecursive(s, "", 
       permutations); 
      return permutations.ToArray(); 
     } 
     void GetPermutationsWithRepetitionRecursive(string s, string permutation, List<string> permutations) 
     { 
      if(permutation.Length == s.Length) 
      { 
       permutations.Add(permutation); 
       return; 
      } 
      for(int i =0;i<s.Length;i++) 
      { 
       this.GetPermutationsWithRepetitionRecursive(s, permutation + s[i], permutations); 
      } 
     } 

아래는 대응 유닛 테스트입니다

[TestMethod] 
     public void PermutationsWithRepetitionTests() 
     { 
      string s = ""; 
      int[] output = { 1, 4, 27, 256, 3125 }; 
      for(int i = 1; i<=5;i++) 
      { 
       s += i; 
       var p = this.GetPermutationsWithRepetition(s); 
       Assert.AreEqual(output[i - 1], p.Length); 
      } 
     } 
2

난 반복과 순열이 자바 구현을 사용한다. A ~ (n, m) : n = 배열의 길이, m = k. m은 n보다 크거나 작을 수 있습니다.

public class Permutations { 


    static void permute(Object[] a, int k, PermuteCallback callback) { 
     int n = a.length; 

     int[] indexes = new int[k]; 
     int total = (int) Math.pow(n, k); 

     Object[] snapshot = new Object[k]; 
     while (total-- > 0) { 
      for (int i = 0; i < k; i++){ 
       snapshot[i] = a[indexes[i]]; 
      } 
      callback.handle(snapshot); 

      for (int i = 0; i < k; i++) { 
       if (indexes[i] >= n - 1) { 
        indexes[i] = 0; 
       } else { 
        indexes[i]++; 
        break; 
       } 
      } 
     } 
    } 

    public static interface PermuteCallback{ 
     public void handle(Object[] snapshot); 
    }; 

    public static void main(String[] args) { 
     Object[] chars = { 'a', 'b', 'c', 'd' }; 
     PermuteCallback callback = new PermuteCallback() { 

      @Override 
      public void handle(Object[] snapshot) { 
       for(int i = 0; i < snapshot.length; i ++){ 
        System.out.print(snapshot[i]); 
       } 
       System.out.println(); 
      } 
     }; 
     permute(chars, 8, callback); 
    } 

} 

예 출력

aaaaaaaa 
baaaaaaa 
caaaaaaa 
daaaaaaa 
abaaaaaa 
bbaaaaaa 
... 
bcdddddd 
ccdddddd 
dcdddddd 
addddddd 
bddddddd 
cddddddd 
dddddddd