title: Brute Force Permutation Swapping
body: <p>I've been working on a brute force algorithm to generate all permutations of a given set. Eventually, I want to feed each of these permutations into a nxn matrix to test if it is a valid magic square or not. 
  --I KNOW THAT THERE IS A WAY TO GENERATE A MAGIC SQUARE EASILY--
  That is not what I want to do, though. I'm focusing on the brute force aspect of it.</p>
  
  <p>For a set of 3 elements, it works wonderfully. However, once I use 4 or more elements, I lose out on a few permutations. Just from looking at the output of 4, I am missing 7 permutations.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;iostream&gt;
  
  using namespace std;
  
  
  //ms = magic square
  //n = size
  void perm(int ms[], int n) {
      int pivot = 0;
      int index = 0;
      int pivBit = 1;
      int fin = 0;
      int hold = 0;
  
      //While we are not finished
      while (fin == 0)  {
          //Incriment the index
          ++index;
          if (index &gt;= n) {
              index = 0;
          }
          //if index is equal to the pivot
          if (index == pivot) {
              //Is this the first time visiting the pivot?
              if (pivBit == 0) {
                  //Are we at the beginning again?
                  if (index == 0 &amp;&amp; pivot == 0)
                  {
                      fin = 1;
                  }
                  pivBit = 1;
                  ++index;
              }
              //Second time visiting? 
              else {
                  pivBit = 0;
                  ++pivot;
                  if (pivot &gt;= n) {
                      pivot = 0;
                  }
              }
          }
  
          //If we are out of bounds
          if (index &gt;= n) {
              index = 0;
          }
  
          //swap
          hold = ms[index];
          ms[index] = ms[pivot];
          ms[pivot] = hold;
  
          for (int i = 0; i &lt; n; ++i) {
              cout &lt;&lt; ms[i];
              if (i &lt; n - 1) {
                  cout &lt;&lt; ", ";
              }
              else {
                  cout &lt;&lt; endl;
              }
  
  
          }
  
      }
  
  }
  
  
  
  int main() {
  
      cout &lt;&lt; "Are you ready to brute force, my brother?" &lt;&lt; endl;
  
      //Set
      int magicsquare[] = { 1, 2, 3, 4};
      int size = 4;
  
      perm(magicsquare, size);
  
      getchar();
      return 0;
  }
  </code></pre>
  
  <p>My output is:</p>
  
  <pre><code>2 1 3 4
  3 1 2 4
  4 1 2 3
  1 4 2 3
  1 2 4 3
  1 3 4 2
  3 1 4 2 
  3 4 1 2
  3 4 2 1
  2 4 3 1
  2 3 4 1 
  2 3 1 4
  4 3 1 2
  4 2 1 3
  4 2 3 1
  1 2 3 4
  2 1 3 4
  </code></pre>
  
  <p>Looking at it, I can already see that I am missing both 1 4 3 2 and 1 3 2 4. 
  Where've I gone wrong in my algorithm?</p>