Using bitwise or operator in switch case - c++

I have enum,
enum ENUM_MSG_TEXT_CHANGE {COLOR=0,SIZE,UNDERLINE};
void Func(int nChange)
{
bool bColor=false, bSize=false;
switch(nChange)
{
case COLOR:bColor=true;break;
case SIZE:bSize=true;break;
case COLOR|SIZE:bSize=true; bColor=true;break;
}
}
case SIZE: and case COLOR|SIZE: both gives value 1, so I am getting the error C2196: case value '1' already used. How to differentiate these two cases in switch case?
Thanks

If you want to make a bitmask, every element of your enum has to correspond to a number that is a power of 2, so it has exactly 1 bit set. If you number them otherwise, it won't work. So, the first element should be 1, then 2, then 4, then 8, then 16, and so on, so you won't get overlaps when orring them. Also, you should just test every bit individually instead of using a switch:
if (nChange & COLOR) {
bColor = true;
}
if (nChange & SIZE) {
bSize = true;
}

These two labels
case SIZE:bSize=true;break;
case COLOR|SIZE:bSize=true; bColor=true;break;
evaluates to 1 because SIZE is defined as having the value 1 and the bit-wise operator | used in the label COLOR|SIZE also yields 1.
Usually such enumerations are declared as bitmask types like
enum ENUM_MSG_TEXT_CHANGE { COLOR = 1 << 0, SIZE = 1 << 1, UNDERLINE = 1 << 2 };
In this case this label
case COLOR|SIZE:bSize=true; bColor=true;break;
will be equal to 3.

When using the binary OR (operator|) you need to assign values to the individual bits (or combinations of bits). Since COLOR has the value 0 it can't be extracted from a bitfield like you try to do.
Also, for the three enums you have, there are 8 possible combinations. To use a switch, you'd need 8 case labels.
Consider this as an alternative:
#include <iostream>
enum ENUM_MSG_TEXT_CHANGE : unsigned {
COLOR = 1U << 0U, // 0b001
SIZE = 1U << 1U, // 0b010
UNDERLINE = 1U << 2U // 0b100
};
void Func(unsigned nChange) {
// extract the set bits
bool bColor = nChange & COLOR;
bool bSize = nChange & SIZE;
bool bUnderline = nChange & UNDERLINE;
// print out what was extracted
std::cout << bUnderline << bSize << bColor << '\n';
}
int main() {
// test all combinations
for(unsigned change = 0; change <= (COLOR | SIZE | UNDERLINE); ++change) {
Func(change);
}
}
Output:
000
001
010
011
100
101
110
111

Related

Parsing Message with Varying Fields

I have a byte stream that represents a message in my application. There are 5 fields in the message for demonstration. The first byte in the stream indicates which message fields are present for the current stream. For instance 0x2 in the byte-0 means only the Field-1 is present for the current stream.
The mask field might have 2^5=32 different values. To parse this varying width of message, I wrote the example structure and parser below. My question is, is there any other way to parse such dynamically changing fields? If the message had 64 fields with I would have to write 64 cases, which is cumbersome.
#include <iostream>
typedef struct
{
uint8_t iDummy0;
int iDummy1;
}__attribute__((packed, aligned(1)))Field4;
typedef struct
{
int iField0;
uint8_t ui8Field1;
short i16Field2;
long long i64Field3;
Field4 stField4;
}__attribute__((packed, aligned(1)))MessageStream;
char* constructIncomingMessage()
{
char* cpStream = new char(1+sizeof(MessageStream)); // Demonstrative message byte array
// 1 byte for Mask, 20 bytes for messageStream
cpStream[0] = 0x1F; // the 0-th byte is a mask marking
// which fields are present for the messageStream
// all 5 fields are present for the example
return cpStream;
}
void deleteMessage( char* cpMessage)
{
delete cpMessage;
}
int main() {
MessageStream messageStream; // Local storage for messageStream
uint8_t ui8FieldMask; // Mask to indicate which fields of messageStream
// are present for the current incoming message
const uint8_t ui8BitIsolator = 0x01;
uint8_t ui8FieldPresent; // ANDed result of Mask and Isolator
std::size_t szParsedByteCount = 0; // Total number of parsed bytes
const std::size_t szMaxMessageFieldCount = 5; // There can be maximum 5 fields in
// the messageStream
char* cpMessageStream = constructIncomingMessage();
ui8FieldMask = (uint8_t)cpMessageStream[0];
szParsedByteCount += 1;
for(std::size_t i = 0; i<szMaxMessageFieldCount; ++i)
{
ui8FieldPresent = ui8FieldMask & ui8BitIsolator;
if(ui8FieldPresent)
{
switch(i)
{
case 0:
{
memcpy(&messageStream.iField0, cpMessageStream+szParsedByteCount, sizeof(messageStream.iField0));
szParsedByteCount += sizeof(messageStream.iField0);
break;
}
case 1:
{
memcpy(&messageStream.ui8Field1, cpMessageStream+szParsedByteCount, sizeof(messageStream.ui8Field1));
szParsedByteCount += sizeof(messageStream.ui8Field1);
break;
}
case 2:
{
memcpy(&messageStream.i16Field2, cpMessageStream+szParsedByteCount, sizeof(messageStream.i16Field2));
szParsedByteCount += sizeof(messageStream.i16Field2);
break;
}
case 3:
{
memcpy(&messageStream.i64Field3, cpMessageStream+szParsedByteCount, sizeof(messageStream.i64Field3));
szParsedByteCount += sizeof(messageStream.i64Field3);
break;
}
case 4:
{
memcpy(&messageStream.stField4, cpMessageStream+szParsedByteCount, sizeof(messageStream.stField4));
szParsedByteCount += sizeof(messageStream.stField4);
break;
}
default:
{
std::cerr << "Undefined Message field number: " << i << '\n';
break;
}
}
}
ui8FieldMask >>= 1; // shift the mask
}
delete deleteMessage(cpMessageStream);
return 0;
}
The first thing I'd change is to drop the __attribute__((packed, aligned(1))) on Field4. This is a hack to create structures which mirror a packed wire-format, but that's not the format you're dealing with anyway.
Next, I'd make MessageStream a std::tuple of std::optional<T> fields.
You now know that there are std::tuple_size<MessageStream> possible bits in the mask. Obviously you can't fit 64 bits in a ui8FieldMask but I'll assume that's a trivial problem to solve.
You can write a for-loop from 0 to std::tuple_size<MessageStream> to extract the bits from ui8FieldMask to see which bits are set. The slight problem with that logic is that you'll need compile-time constants I for std::get<size_t I>(MessageStream), and a for-loop only gives you run-time variables.
Hence, you'll need a recursive template <size_t I> extract(char const*& cpMessageStream, MessageStream&), and of course a specialization extract<0>. In extract<I>, you can use typename std::tuple_element<I, MessageStream>::type to get the std::optional<T> at the I'th position in your MessageStream.

Why bitwise OR and AND logic is not working as expected?

I have the below sample code. I was always under the impression that doing Bitwise OR on enum values, will allow me to check the result (using Bitwise AND) to see which enum values are included in the result and which are not.
For example, if I do result = mouse | headphone, then I can check agaist result & mouse == mouse as condition to know if mouse is included in result or not. But it seem that whatever I & result with, say X, I always end up with X. Why?
In the below code, I thought that the if should fail since straw was not included in options, but it does not..
#include <iostream>
#include <iomanip>
using namespace std;
enum Stock
{
milk,
choclate,
tv,
cable,
mouse,
fan,
headphone,
cup,
straw,
pen,
candy,
glasses,
book,
plug
};
int main()
{
Stock options = static_cast<Stock>( static_cast<int>(mouse) | static_cast<int>(headphone)
| static_cast<int>(cup) | static_cast<int>(pen) );
if ((static_cast<int>(loptions)) & (static_cast<int>(straw)) == static_cast<int>(straw))
{
cout << "bring straw!" << endl;
}
system("PAUSE");
return 0;
}
Edit:
Even when I add unique-bit set for the enum values, it does not work. For the below code, it ignores both if() statements when I am expecting it to display "bring cup" instead:
enum Stock
{
milk = 1,
choclate = 2,
tv = 4,
cable = 8,
mouse = 16,
fan = 32,
headphone = 64,
cup = 128,
straw = 256,
pen = 512,
candy = 1024,
glasses = 2048,
book = 4096,
plug = 8192
};
int main()
{
Stock options = static_cast<Stock>(static_cast<int>(mouse) | static_cast<int>(headphone)
| static_cast<int>(cup) | static_cast<int>(pen));
if ((static_cast<int>(options)) & (static_cast<int>(straw)) == static_cast<int>(straw))
{
cout << "bring straw!" << endl;
}
if ((static_cast<int>(options)) & (static_cast<int>(cup)) == static_cast<int>(cup))
{
cout << "bring cup!" << endl;
}
system("PAUSE");
return 0;
}
To use enums as bitsets (or flags) you need to make sure the binary representation for each enum value contains exactly one bit set to 1. In other words, each enum value needs to be a power of two. Example :
enum Stock
{
milk = 1, // 0b0001
choclate = 2, // 0b0010
tv = 4, // 0b0100
cable = 8 // 0b1000
// etc.
};
Otherwise, bit-wise logical operators won't be able to differentiate between certain values and certain combinations of other values. In the original code chocolate, tv and cable have the values 1, 2 and 3 respectively. In binary, that is 01, 10 and 11. ORing chocolate and tv produces 11 (0b01 | 0b10 == 0b11) which is the same value as cable. The combination of the chocolate and tv is not distinguishable from the cable flag.
But c++ provides std::bitset. This class allows you to easily manipulate a bit set in a way similar to an array of bits. You can then just use your original enum and use each enum value as the index of a bit.

Translate c++ functions in TypeScript

Given the following functions written in C++:
#define getbit(s,i) ((s)[(i)/8] & 0x01<<(i)%8)
#define setbit(s,i) ((s)[(i)/8] |= 0x01<<(i)%8)
How can I turn them into compatible TypeScript functions?
I came up with:
function setbit(s: string, i: number): number {
return +s[i / 8] | 0x01 << i % 8;
}
function getbit(s: string, i: number): number {
return +s[i / 8] & 0x01 << i % 8;
}
I found out that the a |= b equivalent is a = a | b, but I'm not sure about the getbit function implementation. Also, I don't really understand what those functions are supposed to do. Could someone explain them, please?
Thank you.
EDIT:
Using the ideas from #Thomas, I ended up doing this:
function setBit(x: number, mask: number) {
return x | 1 << mask;
}
// not really get, more like a test
function getBit(x: number, mask: number) {
return ((x >> mask) % 2 !== 0);
}
since I don't really need a string for the binary representation.
Strings ain't a good storage here. And btw, JS Strings use 16bit characters, so you're using only 1/256th of the storage possible.
function setbit(string, index) {
//you could do `index >> 3` but this will/may fail if index > 0xFFFFFFFF
//well, fail as in produce wrong results, not as in throwing an error.
var position = Math.floor(index/8),
bit = 1 << (index&7),
char = string.charCodeAt(position);
return string.substr(0, position) + String.fromCharCode(char|bit) + string.substr(position+1);
}
function getbit(string, index) {
var position = Math.floor(i/8),
bit = 1 << (i&7),
char = string.charCodeAt(position);
return Boolean(char & bit);
}
better would be a (typed) Array.
function setBit(array, index){
var position = Math.floor(index/8),
bit = 1 << (index&7);
array[position] |= bit; //JS knows `|=` too
return array;
}
function getBit(array, index) {
var position = Math.floor(index/8),
bit = 1 << (index&7);
return Boolean(array[position] & bit)
}
var storage = new Uint8Array(100);
setBit(storage, 42);
console.log(storage[5]);
var data = [];
setBit(data, 42);
console.log(data);
works with both, but:
all typed Arrays have a fixed length that can not be changed after memory allocation (creation).
regular arrays don't have a regular type, like 8bit/index or so, limit is 53Bit with floats, but for performance reasons you should stick with up to INT31 (31, not 32), that means 30bits + sign. In this case the JS engine can optimize this thing a bit behind the scenes; reduce memory impact and is a little faster.
But if performance is the topic, use Typed Arrays! Although you have to know in advance how big this thing can get.

Are enums the canonical way to implement bit flags?

Currently I'm using enums to represent a state in a little game experiment. I declare them like so:
namespace State {
enum Value {
MoveUp = 1 << 0, // 00001 == 1
MoveDown = 1 << 1, // 00010 == 2
MoveLeft = 1 << 2, // 00100 == 4
MoveRight = 1 << 3, // 01000 == 8
Still = 1 << 4, // 10000 == 16
Jump = 1 << 5
};
}
So that I can use them this way:
State::Value state = State::Value(0);
state = State::Value(state | State::MoveUp);
if (mState & State::MoveUp)
movement.y -= mPlayerSpeed;
But I'm wondering if this is the right way to implement bit flags. Isn't there a special container for bit flags? I heard about std::bitset, is it what I should use? Do you know something more efficient?
Am I doing it right?
I forgot to point out I was overloading the basic operators of my enum:
inline State::Value operator|(State::Value a, State::Value b)
{ return static_cast<State::Value>(static_cast<int>(a) | static_cast<int>(b)); }
inline State::Value operator&(State::Value a, State::Value b)
{ return static_cast<State::Value>(static_cast<int>(a) & static_cast<int>(b)); }
inline State::Value& operator|=(State::Value& a, State::Value b)
{ return (State::Value&)((int&)a |= (int)b); }
I had to use a C-style cast for the |=, it didn't work with a static_cast - any idea why?
The STL contains std::bitset, which you can use for precisely such a case.
Here is just enough code to illustrate the concept:
#include <iostream>
#include <bitset>
class State{
public:
//Observer
std::string ToString() const { return state_.to_string();};
//Getters
bool MoveUp() const{ return state_[0];};
bool MoveDown() const{ return state_[1];};
bool MoveLeft() const{ return state_[2];};
bool MoveRight() const{ return state_[3];};
bool Still() const{ return state_[4];};
bool Jump() const{ return state_[5];};
//Setters
void MoveUp(bool on) {state_[0] = on;}
void MoveDown(bool on) {state_[1] = on;}
void MoveLeft(bool on) {state_[2] = on;}
void MoveRight(bool on) {state_[3] = on;}
void Still(bool on) {state_[4] = on;}
void Jump(bool on) {state_[5] = on;}
private:
std::bitset<6> state_;
};
int main() {
State s;
auto report = [&s](std::string const& msg){
std::cout<<msg<<" "<<s.ToString()<<std::endl;
};
report("initial value");
s.MoveUp(true);
report("move up set");
s.MoveDown(true);
report("move down set");
s.MoveLeft(true);
report("move left set");
s.MoveRight(true);
report("move right set");
s.Still(true);
report("still set");
s.Jump(true);
report("jump set");
return 0;
}
Here's it working: http://ideone.com/XLsj4f
The interesting thing about this is that you get std::hash support for free, which is typically one of the things you would need when using state inside various data structures.
EDIT:
There is one limitation to std::bitset and that is the fact that you need to know the maximum number of bits in your bitset at compile time. However, that is the same case with enums anyway.
However, if you don't know the size of your bitset at compile time, you can use boost::dynamic_bitset, which according to this paper (see page 5) is actually really fast. Finally, according to Herb Sutter, std::bitset was designed to be used in cases you would normally want to use std::vector.
That said, there really is no substitute for real world tests. So if you really want to know, profile. That will give you performance numbers for a context that you care about.
I should also mention that std::bitset has an advantage that enum does not - there is no upper limit on the number of bits you can use. So std::bitset<1000> is perfectly valid.
I believe that your approach is right (except several things):
1. You can explicitly specify underlying type to save memory;
2. You can not use unspecified enum values.
namespace State {
enum Value : char {
None = 0,
MoveUp = 1 << 0, // 00001 == 1
MoveDown = 1 << 1, // 00010 == 2
MoveLeft = 1 << 2, // 00100 == 4
MoveRight = 1 << 3, // 01000 == 8
Still = 1 << 4, // 10000 == 16
Jump = 1 << 5
};
}
and:
State::Value state = State::Value::None;
state = State::Value(state | State::MoveUp);
if (mState & State::MoveUp) {
movement.y -= mPlayerSpeed;
}
about overloading:
inline State::Value& operator|=(State::Value& a, State::Value b) {
return a = static_cast<State::Value> (a | b);
}
and since you use C++11, you should use constexpr every were is possible:
inline constexpr State::Value operator|(State::Value a, State::Value b) {
return a = static_cast<State::Value> (a | b);
}
inline constexpr State::Value operator&(State::Value a, State::Value b) {
return a = static_cast<State::Value> (a & b);
}
To be honest I don't think there is a consistent pattern for them.
Just look at std::ios_base::openmode and std::regex_constants::syntax_option_type as two completely different ways of structuring it in the standard library -- one using a struct, the other using an entire namespace. Both are enums all right, but structured differently.
Check your standard library implementation to see the details of how the above two are implemented.

Using recursion and backtracking to generate all possible combinations

I'm trying to implement a class that will generate all possible unordered n-tuples or combinations given a number of elements and the size of the combination.
In other words, when calling this:
NTupleUnordered unordered_tuple_generator(3, 5, print);
unordered_tuple_generator.Start();
print() being a callback function set in the constructor.
The output should be:
{0,1,2}
{0,1,3}
{0,1,4}
{0,2,3}
{0,2,4}
{0,3,4}
{1,2,3}
{1,2,4}
{1,3,4}
{2,3,4}
This is what I have so far:
class NTupleUnordered {
public:
NTupleUnordered( int k, int n, void (*cb)(std::vector<int> const&) );
void Start();
private:
int tuple_size; //how many
int set_size; //out of how many
void (*callback)(std::vector<int> const&); //who to call when next tuple is ready
std::vector<int> tuple; //tuple is constructed here
void add_element(int pos); //recursively calls self
};
and this is the implementation of the recursive function, Start() is just a kick start function to have a cleaner interface, it only calls add_element(0);
void NTupleUnordered::add_element( int pos )
{
// base case
if(pos == tuple_size)
{
callback(tuple); // prints the current combination
tuple.pop_back(); // not really sure about this line
return;
}
for (int i = pos; i < set_size; ++i)
{
// if the item was not found in the current combination
if( std::find(tuple.begin(), tuple.end(), i) == tuple.end())
{
// add element to the current combination
tuple.push_back(i);
add_element(pos+1); // next call will loop from pos+1 to set_size and so on
}
}
}
If I wanted to generate all possible combinations of a constant N size, lets say combinations of size 3 I could do:
for (int i1 = 0; i1 < 5; ++i1)
{
for (int i2 = i1+1; i2 < 5; ++i2)
{
for (int i3 = i2+1; i3 < 5; ++i3)
{
std::cout << "{" << i1 << "," << i2 << "," << i3 << "}\n";
}
}
}
If N is not a constant, you need a recursive function that imitates the above
function by executing each for-loop in it's own frame. When for-loop terminates,
program returns to the previous frame, in other words, backtracking.
I always had problems with recursion, and now I need to combine it with backtracking to generate all possible combinations. Any pointers of what am I doing wrong? What I should be doing or I am overlooking?
P.S: This is a college assignment that also includes basically doing the same thing for ordered n-tuples.
Thanks in advance!
/////////////////////////////////////////////////////////////////////////////////////////
Just wanted to follow up with the correct code just in case someone else out there is wondering the same thing.
void NTupleUnordered::add_element( int pos)
{
if(static_cast<int>(tuple.size()) == tuple_size)
{
callback(tuple);
return;
}
for (int i = pos; i < set_size; ++i)
{
// add element to the current combination
tuple.push_back(i);
add_element(i+1);
tuple.pop_back();
}
}
And for the case of ordered n-tuples:
void NTupleOrdered::add_element( int pos )
{
if(static_cast<int>(tuple.size()) == tuple_size)
{
callback(tuple);
return;
}
for (int i = pos; i < set_size; ++i)
{
// if the item was not found in the current combination
if( std::find(tuple.begin(), tuple.end(), i) == tuple.end())
{
// add element to the current combination
tuple.push_back(i);
add_element(pos);
tuple.pop_back();
}
}
}
Thank you Jason for your thorough response!
A good way to think about forming N combinations is to look at the structure like a tree of combinations. Traversing that tree then becomes a natural way to think about the recursive nature of the algorithm you wish to implement, and how the recursive process would work.
Let's say for instance that we have the sequence, {1, 2, 3, 4}, and we wish to find all the 3-combinations in that set. The "tree" of combinations would then look like the following:
root
________|___
| |
__1_____ 2
| | |
__2__ 3 3
| | | |
3 4 4 4
Traversing from the root using a pre-order traversal, and identifying a combination when we reach a leaf-node, we get the combinations:
{1, 2, 3}
{1, 2, 4}
{1, 3, 4}
{2, 3, 4}
So basically the idea would be to sequence through an array using an index value, that for each stage of our recursion (which in this case would be the "levels" of the tree), increments into the array to obtain the value that would be included in the combination set. Also note that we only need to recurse N times. Therefore you would have some recursive function whose signature that would look something like the following:
void recursive_comb(int step_val, int array_index, std::vector<int> tuple);
where the step_val indicates how far we have to recurse, the array_index value tells us where we're at in the set to start adding values to the tuple, and the tuple, once we're complete, will be an instance of a combination in the set.
You would then need to call recursive_comb from another non-recursive function that basically "starts off" the recursive process by initializing the tuple vector and inputting the maximum recursive steps (i.e., the number of values we want in the tuple):
void init_combinations()
{
std::vector<int> tuple;
tuple.reserve(tuple_size); //avoids needless allocations
recursive_comb(tuple_size, 0, tuple);
}
Finally your recusive_comb function would something like the following:
void recursive_comb(int step_val, int array_index, std::vector<int> tuple)
{
if (step_val == 0)
{
all_combinations.push_back(tuple); //<==We have the final combination
return;
}
for (int i = array_index; i < set.size(); i++)
{
tuple.push_back(set[i]);
recursive_comb(step_val - 1, i + 1, tuple); //<== Recursive step
tuple.pop_back(); //<== The "backtrack" step
}
return;
}
You can see a working example of this code here: http://ideone.com/78jkV
Note that this is not the fastest version of the algorithm, in that we are taking some extra branches we don't need to take which create some needless copying and function calls, etc. ... but hopefully it gets across the general idea of recursion and backtracking, and how the two work together.
Personally I would go with a simple iterative solution.
Represent you set of nodes as a set of bits. If you need 5 nodes then have 5 bits, each bit representing a specific node. If you want 3 of these in your tupple then you just need to set 3 of the bits and track their location.
Basically this is a simple variation on fonding all different subsets of nodes combinations. Where the classic implementation is represent the set of nodes as an integer. Each bit in the integer represents a node. The empty set is then 0. Then you just increment the integer each new value is a new set of nodes (the bit pattern representing the set of nodes). Just in this variation you make sure that there are always 3 nodes on.
Just to help me think I start with the 3 top nodes active { 4, 3, 2 }. Then I count down. But it would be trivial to modify this to count in the other direction.
#include <boost/dynamic_bitset.hpp>
#include <iostream>
class TuppleSet
{
friend std::ostream& operator<<(std::ostream& stream, TuppleSet const& data);
boost::dynamic_bitset<> data; // represents all the different nodes
std::vector<int> bitpos; // tracks the 'n' active nodes in the tupple
public:
TuppleSet(int nodes, int activeNodes)
: data(nodes)
, bitpos(activeNodes)
{
// Set up the active nodes as the top 'activeNodes' node positions.
for(int loop = 0;loop < activeNodes;++loop)
{
bitpos[loop] = nodes-1-loop;
data[bitpos[loop]] = 1;
}
}
bool next()
{
// Move to the next combination
int bottom = shiftBits(bitpos.size()-1, 0);
// If it worked return true (otherwise false)
return bottom >= 0;
}
private:
// index is the bit we are moving. (index into bitpos)
// clearance is the number of bits below it we need to compensate for.
//
// [ 0, 1, 1, 1, 0 ] => { 3, 2, 1 }
// ^
// The bottom bit is move down 1 (index => 2, clearance => 0)
// [ 0, 1, 1, 0, 1] => { 3, 2, 0 }
// ^
// The bottom bit is moved down 1 (index => 2, clearance => 0)
// This falls of the end
// ^
// So we move the next bit down one (index => 1, clearance => 1)
// [ 0, 1, 0, 1, 1]
// ^
// The bottom bit is moved down 1 (index => 2, clearance => 0)
// This falls of the end
// ^
// So we move the next bit down one (index =>1, clearance => 1)
// This does not have enough clearance to move down (as the bottom bit would fall off)
// ^ So we move the next bit down one (index => 0, clearance => 2)
// [ 0, 0, 1, 1, 1]
int shiftBits(int index, int clerance)
{
if (index == -1)
{ return -1;
}
if (bitpos[index] > clerance)
{
--bitpos[index];
}
else
{
int nextBit = shiftBits(index-1, clerance+1);
bitpos[index] = nextBit-1;
}
return bitpos[index];
}
};
std::ostream& operator<<(std::ostream& stream, TuppleSet const& data)
{
stream << "{ ";
std::vector<int>::const_iterator loop = data.bitpos.begin();
if (loop != data.bitpos.end())
{
stream << *loop;
++loop;
for(; loop != data.bitpos.end(); ++loop)
{
stream << ", " << *loop;
}
}
stream << " }";
return stream;
}
Main is trivial:
int main()
{
TuppleSet s(5,3);
do
{
std::cout << s << "\n";
}
while(s.next());
}
Output is:
{ 4, 3, 2 }
{ 4, 3, 1 }
{ 4, 3, 0 }
{ 4, 2, 1 }
{ 4, 2, 0 }
{ 4, 1, 0 }
{ 3, 2, 1 }
{ 3, 2, 0 }
{ 3, 1, 0 }
{ 2, 1, 0 }
A version of shiftBits() using a loop
int shiftBits()
{
int bottom = -1;
for(int loop = 0;loop < bitpos.size();++loop)
{
int index = bitpos.size() - 1 - loop;
if (bitpos[index] > loop)
{
bottom = --bitpos[index];
for(int shuffle = loop-1; shuffle >= 0; --shuffle)
{
int index = bitpos.size() - 1 - shuffle;
bottom = bitpos[index] = bitpos[index-1] - 1;
}
break;
}
}
return bottom;
}
In MATLAB:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% combinations.m
function combinations(n, k, func)
assert(n >= k);
n_set = [1:n];
k_set = zeros(k, 1);
recursive_comb(k, 1, n_set, k_set, func)
return
function recursive_comb(k_set_index, n_set_index, n_set, k_set, func)
if k_set_index == 0,
func(k_set);
return;
end;
for i = n_set_index:length(n_set)-k_set_index+1,
k_set(k_set_index) = n_set(i);
recursive_comb(k_set_index - 1, i + 1, n_set, k_set, func);
end;
return;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Test:
>> combinations(5, 3, #(x) printf('%s\n', sprintf('%d ', x)));
3 2 1
4 2 1
5 2 1
4 3 1
5 3 1
5 4 1
4 3 2
5 3 2
5 4 2
5 4 3