Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smarter looping over permutations

Tags:

c++

algorithm

I've got a 3 by 3 grid of boolean values, and I'm interested in the number of ways I can have exactly three "living" cells (there's 56 permutations, by my count). Rotational symmetries don't matter, but the living cells are indistinguishable from each other.

Assuming that I'm indexing the values in the grid relative to the centroid:

-------------------
|-1,-1| 0,-1| 1,-1|
-------------------
|-1,0 |     | 1,0 |
-------------------
|-1,1 | 0,1 | 1,1 |
-------------------

is there a nice loop that I could use to calculate the 56 permutations? (I've just finished typing it all out, and I'd love to know if I could have been slightly smarter).

I'm using C++, but a basic algorithm would be wonderful in any language or pseudo-language, if it's clear.

like image 997
simont Avatar asked Dec 20 '25 05:12

simont


1 Answers

You can use next_permutation.

For example, assume string each character in x below represents the a cell in the grid (except centroid cell) starting at top left and going to bottom right. You could run this code to find all the possible arrangements, and inside the loop, string x will represent a possible arrangement, where 1 is a live cell, and 0 is a dead one.

int main() {
  string x = "00000111";
  int cnt = 0;
  do {
    ++cnt;

    // do something useful with this configuration...

  } while(next_permutation(x.begin(),x.end()));
  cout<<cnt<<endl;
  return 0;
}
like image 165
dcp Avatar answered Dec 21 '25 19:12

dcp