Reputation:
Hi I'm trying to construct a loop to execute 16 states of the 8 4 2 1 code in (C++)
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
}
Is there an easy way of coding using for loops? instead of writing bubble[] every time?
0 stands for -2 and 1 stands for +2. So I have 4 variables and each one need to be incremented and/or decremented. Can this be done using for loop?
Appreciate your help
Upvotes: 1
Views: 134
Reputation: 591
No need to branch all the time and sum all doubles within loop:
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 );
}
Upvotes: 0
Reputation: 27
Here's one way as well that is a little more generic if this had to be done for more states(bits):
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;
}
}
Upvotes: 0
Reputation: 16582
Here's a version that avoids branching:
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));
}
Upvotes: 2
Reputation: 1692
Not sure what the problem is. Looping over an array with a for loop is simplicity itself:
for( int i=0; i < 16; ++i )
{
Bubble[i] = /* whatever */
}
Upvotes: -1
Reputation: 110648
I'm not totally sure what your code is doing, but you could rewrite it as follows:
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);
}
Upvotes: 5