1

こんにちは私は(C ++)の8 421コードの16の状態を実行するためのループを構築しようとしています

   while( condition)
   {
   double Bubble[16], Bubble1[16];
        Bubble[0] = ( a-2 - (b-2) ) + ( c-2 - (d-2)); // represents 0000
        Bubble[1] = ( a-2 - (b-2) ) + ( c-2 - (d+2)); // represents 0001
        Bubble[2] = ( a-2 - (b-2) ) + ( c+2 - (d-2)); // represents 0010
        Bubble[3] = ( a-2 - (b-2) ) + ( c+2 - (d+2)); //represents 0011
    .......
        Bubble[15] =(a+2 - (b+2) ) + ( c+2 - (d+2)); //represents 1111
  }

forループを使用してコーディングする簡単な方法はありますか?毎回bubble[]を書く代わりに?
0は-2を表し、1は+2を表します。したがって、4つの変数があり、それぞれをインクリメントまたはデクリメントする必要があります。これはforループを使用して実行できますか?

あなたの助けに感謝

4

5 に答える 5

5

コードが何をしているのか完全にはわかりませんが、次のように書き直すことができます。

for (int i = 0; i < 16; i++) {
  double a_value = (i & 0x8) ? a+2 : a-2;
  double b_value = (i & 0x4) ? b+2 : b-2;
  double c_value = (i & 0x2) ? c+2 : c-2;
  double d_value = (i & 0x1) ? d+2 : d-2;
  Bubble[i] = (a_value - b_value) + (c_value - d_value);
}
于 2012-12-07T17:02:12.780 に答える
2

分岐を回避するバージョンは次のとおりです。

double Bubble[16];
for(int i = 0 ; i < 16 ; i ++)
{
    int da,db,dc,dd;
    da = ((i&8) - 4) >> 1;
    db = ((i&4) - 2);
    dc = ((i&2) - 1) << 1;
    dd = ((i&1) << 2) - 2;

    Bubble[i] = 
        ((a + da) - (b + db)) + ((c + dc) - (d + dd));
}
于 2012-12-07T17:11:16.360 に答える
0

これがより多くの状態(ビット)に対して実行される必要がある場合は、もう少し一般的な方法も1つあります。

var varList = [a, b, c, d];  //these would be the values of a, b, c, d up to the number of states desired
for (var i=0; i<Bubble.length; i++) {
     var numBits = varList.length;
     //If the var list is not large enough, this will be an error (I will just handle it by returning)
     if (Math.pow(2, numBits) < Bubble.length) return;
     for (var j=1; j<=numBits; j++) {
         //first bit corresponds to last state
         var stateVal = varList[numBits - j];
         //if 2^bit is set, add 2, else subtract 2
         stateVal += (i % pow(2, j) === 0) ? 2 : -2;
         //add if even state, subtract if odd state
         Bubble[i] += ((numBits - j) % 2 === 0) ? stateVal : -stateVal;
     }
}
于 2012-12-07T17:46:35.850 に答える
0

常に分岐して、ループ内のすべてのdoubleを合計する必要はありません。

double offset = a0 - b0 + c0 - d0;
for( int idx = 0; idx < sizeof(bbl)/sizeof(bbl[0]); ++idx )
{
    bbl[idx] = offset + ( (   ( 1 & ( idx >> 3 ) )
                            - ( 1 & ( idx >> 2 ) )
                            + ( 1 & ( idx >> 1 ) )
                            - ( 1 &   idx        ) ) << 2 );
}
于 2015-09-22T18:28:03.067 に答える
-1

問題が何であるかわからない。forループを使用して配列をループすること自体が単純です。

for( int i=0; i < 16; ++i )
{
    Bubble[i] = /* whatever */
}
于 2012-12-07T17:02:58.667 に答える