2016-12-19 7 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

[OK]私の新しいアイデアは文字列に独自の "バイナリ"を作成していますので、試してみましょうD – superninja9000

+0

この記事を読むことができますhttp://www.math.mcgill.ca/haron/Papers/Journal/coolTOCS .pdf – sasha199568

答えて

0

ご質問は、0と1のすべての可能な組み合わせでのn文字深い/長いシーケンスを生成する方法を基本的に動作します。この質問にはすでに回答がありますhere

要件にそれを適応させることは簡単です:あなたはあなたの仕事をするために誰かを求めているGetNthEnumeration(new[] { "0", "1" }, 3).ToList();

+0

Thx、それは私の方が速いと思われます... 20バイトの場合、私は結果を得ます:ElapsedMine = 00:00:00.6530281 ElapsedRecursive = 00:00:01.8145570 – superninja9000

関連する問題