2016-12-19 2 views
0

가능한 모든 서브 네트워크와 호스트 범위를 작성할 프로그램을 만들고 있습니다. 예를 들어 서브 네트워크에 대해 4 비트가 있으므로 가능한 모든 조합을 작성해야합니다. 입력 : 4 : 출력 (배열) : 0000, 0001, 0010, 0011, 0100,0101 ... 1111 내가 만든 것은 너무 느립니다. 10 진수 증가 -> 이진수로 변환합니다. 변환.비트에서 모든 조합을 얻는 방법?

여기 내 지체 알고리즘이지만,

public List<string> getAllCombination(int bits) 
    { 
     List<string> strarray = new List<string>(); 
     string temp = ""; 
     //make 1st word 
     for(int i = 0;i< bits;i++) 
     { 
      temp += "0"; 
     } 
     strarray.Add(temp); 
     int loops = (int)Math.Pow(2, bits) - 1; 
     for(int i = 0; i< loops;i++) 
     { 
      int smallestBitPosition = -1; 
      //find last 1 
      for(int j = temp.Length -1 ; j >= 0; j--) 
      { 
       if (temp[j] == '1') 
        smallestBitPosition = j; 

      } 
      StringBuilder temp1 = new StringBuilder(temp); 
      //if there are no 1 
      if (smallestBitPosition == -1) 
      { 
       temp1[temp1.Length - 1] = '1'; 
       temp = temp1.ToString(); 
       strarray.Add(temp); 
       continue; 
      } 

      int lastZeroPosition = -1; 
      //find last zero 
      for (int j = smallestBitPosition; j< temp.Length; j++) 
      { 
       if (temp[j] == '0') 
        lastZeroPosition = j; 
      } 
      //if theres no 0 
      if(lastZeroPosition == -1) 
      { 
       temp1[smallestBitPosition - 1] = '1'; 
       for(int g = smallestBitPosition ; g < temp.Length; g++) 
       { 
        temp1[g] = '0'; 
       } 
       temp = temp1.ToString(); 
       strarray.Add(temp); 
       continue; 
      } 
      //i dont even know how to describe this, without this part it makes for example 101 -> 111, when it should be 110 
      else if ((lastZeroPosition + 1 != bits) && temp[lastZeroPosition + 1] == '1') 
      { 
       temp1[lastZeroPosition] = '1'; 
       for (int g = lastZeroPosition + 1; g < temp.Length; g++) 
       { 
        temp1[g] = '0'; 
       } 
       temp = temp1.ToString(); 
       strarray.Add(temp); 
       continue; 
      } 
      else 
      { 
       temp1[lastZeroPosition] = '1'; 

       temp = temp1.ToString(); 
       strarray.Add(temp); 
       continue; 
      } 
     } 
     return strarray; 
+0

. 먼저 프로그램 벤치마킹을하십시오. 프로그램의 작동 속도와 작동 속도를 결정하십시오. 그런 다음이를 최적화 할 방법을 찾으십시오. 실패 할 경우 코드를 게시하고 원하는 속도와 원하는 결과를 알려주십시오. – sasha199568

+0

좋아, 내 새로운 아이디어는 문자열에 "바이너리"라는 문자열을 만들어서 시도해 보겠다; D – superninja9000

+0

이 문서는 http://www.math.mcgill.ca/haron/Papers/Journal/coolTOCS에서 볼 수있다. .pdf – sasha199568

답변

0

귀하의 질문은 0과의 모든 가능한 조합과 n 문자 깊이/긴 시퀀스를 생성하는 방법을 기본적으로 작동합니다. 이 질문에 대한 대답은 이미 here입니다.

요구 사항에 적응하는 것은 간단합니다 : 당신은 당신의 일을하는 사람을 요구하고있다 GetNthEnumeration(new[] { "0", "1" }, 3).ToList();

+0

Thx, 내 것이 더 빠를 것 같습니다 ... 결과가 20bits 인 경우 : ElapsedMine = 00 : 00 : 00.6530281 ElapsedRecursive = 00 : 00 : 01.8145570 – superninja9000

관련 문제