Jump to content

  • Log In with Google      Sign In   
  • Create Account


More efficient alternative to compare booleans?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
12 replies to this topic

#1 Rybo5001   Members   -  Reputation: 488

Like
0Likes
Like

Posted 08 October 2012 - 11:21 PM

Say I have many booleans, for simplicity sake I will called them A, B, C and D.

so my code if:
[source lang="cpp"]if(A && B && C && D){doSomething();}else if(A && B && C)//but NOT D{doSomethingElse();}else if(A && B && D)//but NOT C{doSomethingElseElse();}else if(B && C)//but NOT D or A[/source]
and this will continue onward for all possiblites (what if only A is true, none are true etc etc etc).


I know a switch statement could be used but that'd be just as long.

Is there a better way of doing this?

Sponsor:

#2 Ashaman73   Crossbones+   -  Reputation: 6735

Like
0Likes
Like

Posted 08 October 2012 - 11:46 PM

Is there a better way of doing this?


Yes =>

I know a switch statement could be used


or, depending on the language you are using, you can use a hashmap (int->function), where int is the binary representation of your conditions.

#3 Felix Ungman   Members   -  Reputation: 916

Like
0Likes
Like

Posted 08 October 2012 - 11:53 PM

If you have 16 possibilities you can't get away with less than 16 "ifs" or switch cases, if that's what you mean. Sometimes it's appropriate to define an enum that lists all possibilities, and use the switch statement:
switch (convert_to_enum(A, B, C, D))
{
    case <case1>: ...;
    case <case2>: ...;
    ...
}

Or, as Ashaman73 says, adopt the functional approach and define a function (or hash map) that gives you the function to be called.

openwar  - the real-time tactical war-game platform


#4 wqking   Members   -  Reputation: 756

Like
0Likes
Like

Posted 08 October 2012 - 11:59 PM

Or you can use bit flags.
const unsigned int BitA = 1 << 0;
const unsigned int BitB = 1 << 1;
...
if(value == (BitA | BitB)) ...
if(value == (BitA | BitB | BitC)) ...
Also you can make some hash map to dispatch the function invoke based on the bit value.

http://www.cpgf.org/
cpgf library -- free C++ open source library for reflection, serialization, script binding, callbacks, and meta data for OpenGL Box2D, SFML and Irrlicht.
v1.5.5 was released. Now supports tween and timeline for ease animation.


#5 iMalc   Crossbones+   -  Reputation: 2260

Like
0Likes
Like

Posted 09 October 2012 - 12:05 AM

If you have 16 distinct pieces of code similar to doSomething, which for the sake of this thread I assume is several lines of code and have hardly anything in common, then you cant exactly shorten it much. Most times though, I would expect that there is a lot of commonality between cases that can be taken advantage of.

Other than that, you can convert the booleans to bit-flags:
i.e.
static const int AIsSet = 1;
static const int BIsSet = 2;
static const int CIsSet = 4;
static const int DIsSet = 8;

int choice = 0;
if (A) choice += AIsSet;
if (B) choice += BIsSet;
if (C) choice += CIsSet;
if (D) choice += DIsSet;

switch (choice) {
  case AIsSet + BIsSet + CIsSet + DIsSet:
	doSomething();
	break;
case AIsSet + BIsSet + CIsSet:
	doSomethingElse();
	break;
case AIsSet + BIsSet + DIsSet:
	doSomethingElseElse();
	break;
case BIsSet + CIsSet:
	doAnotherThing();
	break;
};

Edited by iMalc, 09 October 2012 - 12:07 AM.

"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

#6 Rybo5001   Members   -  Reputation: 488

Like
0Likes
Like

Posted 09 October 2012 - 03:16 AM

Thank you for all these excellent suggestions, looks like I'm not getting away with shorter coding! Posted Image

I think I like the sound of

you can convert the booleans to bit-flags:

as this seems like the best way for what I'm doing.

EDIT: another thought, is there an easy way to work out all the possibilities such as A+B+C+D, A+B+C? Because at the moment my program may end up having to compare many many variables like this.

Edited by Rybo5001, 09 October 2012 - 03:19 AM.


#7 Brother Bob   Moderators   -  Reputation: 7785

Like
0Likes
Like

Posted 09 October 2012 - 03:29 AM

another thought, is there an easy way to work out all the possibilities such as A+B+C+D, A+B+C? Because at the moment my program may end up having to compare many many variables like this.

If you have four boolean states, and each state corresponds to a bit in an integer, then all possible combinations are just the bit patterns of the numbers from 0 to 24-1=15.
for(int i=0; i<16; ++i) {
	    std::cout << "pattern " << i << " = " << ((i&8) ? "D" : "") << ((i&4) ? "C" : "") << ((i&2) ? "B" : "") << ((i&1) ? "A" : "") << std::endl;
    }
Extend to as many bits as you want to use.

#8 Álvaro   Crossbones+   -  Reputation: 11942

Like
3Likes
Like

Posted 09 October 2012 - 03:54 AM

People have suggested using a hash map from int to functions, but since we have indices that are small consecutive integers starting at 0, an array is much more reasonable.

In C++:
typedef void Function(void);

void call_appropriate_function(bool a, bool b, bool c, bool d) {
  static Function *function_array[16] = {
	some_function, some_other_function, ...
  };

  (function_array[a + 2*b + 4*c + 8*d])();
}

Edited by alvaro, 09 October 2012 - 03:54 AM.


#9 turch   Members   -  Reputation: 590

Like
0Likes
Like

Posted 09 October 2012 - 07:30 AM

People have suggested using a hash map from int to functions, but since we have indices that are small consecutive integers starting at 0, an array is much more reasonable.


Don't most [all?] compilers convert switches into jump tables anyway?

#10 Álvaro   Crossbones+   -  Reputation: 11942

Like
0Likes
Like

Posted 09 October 2012 - 07:46 AM

People have suggested using a hash map from int to functions, but since we have indices that are small consecutive integers starting at 0, an array is much more reasonable.


Don't most [all?] compilers convert switches into jump tables anyway?


Yes, that's probably what a switch would become. But the OP was complaining about the code being long, and using a container of function pointers is shorter, because you save yourself the `case' labels and the `break's.

Anyway, my comment was objecting to using a hash map: Using a switch statement is perfectly acceptable in my opinion.

#11 greenvertex   Members   -  Reputation: 510

Like
0Likes
Like

Posted 09 October 2012 - 10:03 AM

Don't most [all?] compilers convert switches into jump tables anyway?


Not all switches are converted to jump tables in C++. Only switch statements with contiguous integer cases starting from 0 AFAIK.

#12 Brother Bob   Moderators   -  Reputation: 7785

Like
1Likes
Like

Posted 09 October 2012 - 10:30 AM

Don't most [all?] compilers convert switches into jump tables anyway?


Not all switches are converted to jump tables in C++. Only switch statements with contiguous integer cases starting from 0 AFAIK.

There's no reason why any range compact enough could be implemented as a jump table. Any offset from zero can be accounted for by subtraction before lookup, and missing cases can be accounted for with an entry jumping to the end of the case statement, or to wherever the no-case route goes.

Edited by Brother Bob, 09 October 2012 - 10:31 AM.


#13 slicksk8te   Members   -  Reputation: 190

Like
0Likes
Like

Posted 09 October 2012 - 10:37 AM

This type of structure with a massive "if else if" is typically not the best style. The only way I see reducing this large block is to take a step back and see if you can group functionality in a different way. The way to tell if this will work is to look through all the body's of the if statements and see if they are unique. If they are not you can try and regroup the logic based on the statement bodies.

If you can't do this and you still want to have clean code, use a hash map as stated above because this will be the most efficient and expandable in the long term. Also rather than using individual booleans for A, B, C, and D, consider having a bit mask because it will make it easier to use as an index. For instance,
[source lang="cpp"]int ABCD = 0; // Flags variableABCD |= 1; // Set AABCD |= 2; // Set Bstatic Function functions[FUNC_NUM] = { doSomething, doSomethingElse, ...}int index = hash(ABCD);function[index]();[/source]




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS