title: Swiss tournament - pairing algorithm
body: <p>I am working on a Swiss Tournament system in Python and I'm trying to figure out an optimal pairing algorithm.<br>
  My biggest problem is that every algorithm I came with produced error in few sequences, where the last pair to be picked have already played each other, ruling the pairing is invalid.</p>
  
  <p>The Swiss system I'm working on is simple: even players, everyone plays at each round and pairing is done based on the winning proximity (so strong players play against strong players, and weak against weak).<br>
  No Bye, only win/lose (no draw), opponents cannot play each other twice.</p>
  
  <p>The current algorithm I did works as follow:  </p>
  
  <ol>
  <li>Produce a players list by ranking order (most wins to least wins)  </li>
  <li>Pick player, starting from player with most wins  </li>
  <li>Match him with the closest ranked player. If they already played, match him with the next one, until a match is found</li>
  <li>Pop the pair out of the list and back to 1</li>
  </ol>
  
  <p>For example:<br>
  Ranking after 2 rounds:  </p>
  
  <pre><code>1. P1: [P2 win, P3 win] 2 wins
  2. P5: [P6 win, P2 win] 2 wins
  3. P3: [P4 win, P1 lost] 1 win, 1 loss
  4. P4: [P6 win, P3 lost] 1 win, 1 loss
  5. P2: [P1 lost, P5 lost] 2 losses
  6. P6: [P5 lost, P4 lost] 2 losses
  </code></pre>
  
  <p>First pick would be P1 and the first match is P5. Taking (P1,P5) out of the list.</p>
  
  <pre><code>1. P3: [P4 win, P1 lost] 1 win, 1 loss
  2. P4: [P6 win, P3 lost] 1 win, 1 loss
  3. P2: [P1 lost, P5 lost] 2 losses
  4. P6: [P5 lost, P4 lost] 2 losses
  </code></pre>
  
  <p>First pick would be P3, already played P4, so the match would be P2. Taking (P3,P2) out of the list.<br>
  In this sequence I finish with a pair that played against each other and the pairing is invalid:</p>
  
  <pre><code>1. P4: [P6 win, P3 lost] 1 win, 1 loss
  2. P6: [P5 lost, P4 lost] 2 losses
  </code></pre>
  
  <hr>
  
  <p>Question: Is there any algorithm that guarantees an optimal pairing module while making sure I do not get 'stuck' at the end with two players who played each other? </p>