가능한 모든 서브 네트워크와 호스트 범위를 작성할 프로그램을 만들고 있습니다. 예를 들어 서브 네트워크에 대해 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;
. 먼저 프로그램 벤치마킹을하십시오. 프로그램의 작동 속도와 작동 속도를 결정하십시오. 그런 다음이를 최적화 할 방법을 찾으십시오. 실패 할 경우 코드를 게시하고 원하는 속도와 원하는 결과를 알려주십시오. – sasha199568
좋아, 내 새로운 아이디어는 문자열에 "바이너리"라는 문자열을 만들어서 시도해 보겠다; D – superninja9000
이 문서는 http://www.math.mcgill.ca/haron/Papers/Journal/coolTOCS에서 볼 수있다. .pdf – sasha199568