I am currently trying to write a function which will allow me to create the powerset of a vector. I currently have a vector of objects and an empty vector of vectors. I looked around online, and found a recursive algorithm, but was unable to get it to work in my case.
Algorithm:
void Game::PowersetRec(vector <Die> & s, int k, int m, int n) {
// Recursively builds a vector which is the powerset of the input vector
if (m <= n) {
s[k+1].pips = m ;
powerset.push_back(s) ;
PowersetRec(s, k+1, m+1, n) ; /* with m */
PowersetRec(s, k, m+1, n) ; /* without m */
}
}
.
PowersetRec(rolledDice, 0, rolledDice[0].pips, rolledDice[rolledDice.size() - 1].pips);
powerset
is my vector of vectors and rolledDice
is a vector of Die
objects which have a pips
attribute (which is an integer).
When I print out powerset I get this (sample):
1, 1, 4, 6, 4, 6
1, 1, 2, 6, 4, 6
1, 1, 2, 3, 4, 6
1, 1, 2, 3, 4, 5
Which makes sense to me given the algorithm, but isn't the powerset, meaning I don't know how the original algorithm worked.
Edit: This answer Seems useful, but I cannot get the code listed (combinations) to compile in GCC.
I was able to answer the question via: the different combinations of a vector's values
I simply changed char to my die object.
Edit: Full code below.
void Game::PowersetGen(vector <Die> & v) {
for (int counter = 1; counter < (1 << v.size()); ++counter) {
vector <Die> combination;
for (int i = 0; i < v.size(); ++i)
{
if (counter & (1 << i))
combination.push_back(v[i]);
}
powerset.push_back(combination);
}
}
Simple clarifying edit: <Die>
is just the name of the object in my vector, ideally this function would be templated to use any data type.