Get every combination of on/off

Monkey Forums/Monkey Programming/Get every combination of on/off

slenkar(Posted April) [#1]
I have a command that has 4 actions

each action has on/off states

so a command could consist of turn left and walk forward
or if walk forward is turned off then it would just be turn left

turn left and turn right could be turned on at the same time, although it would be pointless

So, the question is, how would I get every combination of on/off for 4 actions?

for example if there were 2 actions the 4 possible commands would be:

TurnLeft 1
TurnRight 1

Turn Left1
TurnRight0

Turn Left0
TurnRight1

Turn Left0
TurnRight0


The only way i can think of doing it would be to make a byte class because bytes are the best way to represent on/off states that I can think of.


dawlane(Posted April) [#2]
Using the bits of an integer for such thing is I think the best method. I use the method for all sorts of things from controlling a sprite character, triggering custom events to constructing SQL commands.
It makes sense to use an integer as a flag variable where you can use multiple controllers to move a player character. There is no need to write a 'byte' class as you can just implement the logic to read whats in the flag using the bit-wise and (&) operator and perform the action. If you need to handle more that 32 bits, a wrapper class for the flags would be a good method to pass them to a function method for processing.
A working example for handling two players.



slenkar(Posted April) [#3]
thanks i wasnt sure how to use the bitwise commands


dawlane(Posted April) [#4]
Using an integers with bit-wise operators is also a reasonable way to optimize tile maps if you are a bit pushed for memory. You can encode maps of 65536 x 65536 tiles using a minimum of 8 bytes by using one 32 bit integer to hold the tile location on a virtual grid and only display those that are in the region of the view port, while the second can hold information about that tile or other little optimization tricks like how main tiles to draw in any direction from that start grid location. The down side would be the more tile you have the bigger the list to parse, but there are ways round this.

If you need to clear a bit while preserving the others you can hard code the bits to preserve or do
val &= ~BIT_TO_CLEAR ' BIT_TO_CLEAR being the value of the bit to set
an all in one to clear and set another
val = (val & (~BIT_TO_CLEAR)) | NEW_BIT_TO_SET

Hard coding would probably save you a few clock cycles as the processor would have to assign the value rhs value of whatever you wanted to clear to a register, then eXclusive OR the register contents before bit-wise AND to the lhs value.

The docs on the shift bits operators are incorrect. If I remember there was a few posts about it a while back.