2014-12-03 2 views
-3

문자 배열에 정렬 된 조합을 생성하는 방법은 무엇입니까? 배열 ['a','b','c','d'] 주어진 예를 들어배열에서 문자 세트의 반복되지 않는 가능한 조합을 생성하려면 어떻게해야합니까?

, 사전 식 순서에 따라 다음 오름차순, 길이 오름차순 주문한 모든 가능한 조합을위한 프로그램을 작성 - 즉 :

ab ac ad bc bd cd abc abd acd bcd abcd 
+0

에게 보여주고 원하는 결과

var list = dict.Keys.ToList(); list.Sort(); foreach (var key in list) { Console.WriteLine("{0}", key); } 

를 생성 Console.ReadLine하기 전에 아래의 코드를()를 추가합니다. 그럼에도 불구하고 무엇을 시도 했습니까? 그리고 어떤 특정 문제가 있습니까? 또한, 어떤 프로그래밍 언어에서이 문제를 해결하려고합니까? – J0e3gan

+0

숙제 나 해커가 아닌 도전입니다. 배열 요소의 모든 조합을 얻으려고합니다. 원하는 언어를 사용할 수 있습니다. –

+0

"배열 요소의 모든 조합을 얻으려고합니다." 그렇다면 요소는 aa ab ac ad ba bb bc bd ca cb cc cc cd .... 기타 등 abac ad bc bd cd abc abd acd bcd abcd –

답변

0

이 하나를 시도하십시오. 콘솔 응용 프로그램에서 정적 void Main (string [] args)을 메서드로 변경하여 작성했습니다.

static void Main(string[] args) 
{ 
    Dictionary<string, int> s = new Dictionary<string, int>(); 
    Dictionary<string, int> dict = new Dictionary<string, int>(); 
    bool bln = false; 
    string[] str = new string[5] { "a", "b", "c", "d","e"}; 
    int len = str.Length; 
    string lastWord = ""; 
    // a,b,c,d - count=1, aa,ab,ac,ad,ba,bb,bc,bd - count=2 etc 
    int count = 1; 
    foreach(string sa in str) 
    { 
     dict.Add(sa,1); 
    } 

    for(int m=0;m<len;m++) 
    { 
     // Gets last word as eeeee in this example    
     lastWord += str[4]; 
    } 
    for (int i = 0; i < len; i++) 
    { 
     foreach (KeyValuePair<string, int> kvp in dict) 
     { 
       for (int j = 0; j < str.Length; j++) 
       { 
        if (kvp.Value == count) 
        {       
         s.Add(kvp.Key + str[j],count + 1); 
         // If last combination has reached 
         if (s.Keys.Contains(lastWord)) 
          bln = true; 
        } 
       } 
     }     
     foreach (KeyValuePair<string, int> kvp in s) 
     { 
      if (kvp.Value == count + 1) 
      { 
       dict.Add(kvp.Key,kvp.Value); 
      } 
     } 
     if (bln) 
      break; 
     count++; 
     // a,b,c,d - 4 combinations. aa,ab,ac,ad,ba,bb,bc,bd...4*4=16, then 64 etc 
     len = len * str.Length; 
    } 
    dict.Clear(); 
    foreach (KeyValuePair<string, int> kvp in s) 
    { 
      string s1 = SortWord(kvp.Key); 
      if(!dict.Keys.Contains(s1)) 
       dict.Add(s1, kvp.Value);    
    }  
    foreach (KeyValuePair<string, int> kvp in s) 
    { 
     // abdc will get sorted to abcd 
     string s1 = SortWord(kvp.Key); 
     // If aabc then false becz 'a' is repeated two times 
     bool b = IsWordsRepeat(s1); 
     if (dict.Keys.Contains(s1) && !b) 
     {     
       dict.Remove(SortWord(kvp.Key));      
     } 
    } 
    Console.ReadLine(); 
} 

(즉, abdc가 abcd와하는)

static string SortWord(string str) 
{ 
    char[] chars = str.ToArray(); 
    Array.Sort(chars); 
    return new string(chars); 
} 

당신은 얻을 것이다 정렬 후 문자 이상 1 개 시간

public static bool IsWordsRepeat(string text) 
{ 
    int count = 0; 
    foreach(char c in text) 
    { 
     count = 0; 
     foreach (char c1 in text) 
     { 
       if (c == c1) 
       { 
        count++; 
       } 
       if (count == 2) 
       return false; 
     } 
    } 
    return true; 
} 

가져 오기 단어를 반복되어 있는지 여부를 확인하는 부울 상태를 가져옵니다 마지막으로 정렬 된 방식으로 결과를 가져옵니다.

결과

귀하의 질문에 따라 당신은 알파벳/사전 식 순서가 아닌

ab ac ad bc bd cd abc abd acd bcd abcd 

같은 문자열을 주문하도록 요청하고

enter image description here을 다음과 같이 결과를 형성하는 한

그리고 이제는 다른 주문을해야합니다. 주문. 그냥이 숙제 또는 해커의 도전처럼 들리 아래의 결과

enter image description here

+0

코드 덤프! = 대답. 적어도 일부 의견을 추가하십시오 ... – leppie

+0

댓글을 추가했습니다. 이 대답에 충분합니까? @leppie –

+0

위 코드를 사용해 보셨습니까? 해결책있어? @Prasad Nair –

-1
import java.util.*; 
import java.math.*; 

public class combPowerSet { 

    //printing the charachters as per the number sent. 
    void printNumber(int number, char [] items) 
     { 
      String digitString = Integer.toString(number); 
      char [] digitStringArray = digitString.toCharArray(); 
      int length = digitStringArray.length; 
      for (int i=0; i<length; i++) 
      { 
       System.out.print(items[Character.getNumericValue(digitStringArray[i])-1]); 
      } 
      System.out.println(); 
     } 

    //checking if the number follows the required pattern. 
    boolean checkCondition(int number, int itemSize) 
    { 
     boolean validNumber = true; 
     String digitString = Integer.toString(number); 
     char [] digitStringArray = digitString.toCharArray(); 
     int length = digitStringArray.length; 
     for (int i=0; i<length; i++) 
     { 
      for(int j = i+1; j < length; j++) 
      { 
       int x = Character.getNumericValue(digitStringArray[i]); 
       int y = Character.getNumericValue(digitStringArray[j]);    

       if (x > itemSize-1 || y > itemSize || x > y || x==y) 
       { 
        validNumber = false; 
        break; 
       }    
      } 
      if (validNumber == false) break; 
     } 
     return validNumber;  
    } 


    void printCombinations(char [] items) 
    { 
     double maxDigit = 0; 
     int itemSize = items.length; 
     for(int i=1; i<=itemSize; i++) 
     { 
      maxDigit = maxDigit + i*Math.pow(10,itemSize-i); 
     } 


     for(int x=12; x<=maxDigit; x++) 
     { 
      if(checkCondition(x, itemSize)) 
      { 
       printNumber(x, items); 
      } 
     } 
    } 

    public static void main(String [] args) 
    { 
     char [] arr = { 'a','b', 'c','d', 'e'}; 
     combPowerSet obj = new combPowerSet(); 
     obj.printCombinations(arr);  

    } 
} 
+0

@Prasad Nair의 출력보기 –

관련 문제