title: Printing all Possible nCr Combinations in Java
body: <p>I'm trying to print out all possibilities of nCr, which are the combinations when order doesn't matter.  So 5C1 there are 5 possibilities: 1 , 2, 3, 4, 5. 5C2 there are 10 possibilities: 1 2, 1 3, 1 4, 1 5, 2 3, 2 4, 2 5, 3 4, 3 5, 4 5.</p>
  
  <p>I made functions that print what I want for r = 2, r = 3, and r = 4, and I sort of see the pattern, but I cant seem to make a working method for variable r:</p>
  
  <pre><code>public void printCombinationsChoose2(int n, int k) //for when k = 2
  {
      for (int a = 1; a &lt; n; a++)
      {
          for (int b = a + 1; b &lt;= n; b++)
          {
              System.out.println("" + a + " " + b);
          }
      }
  }
  
  public void printCombinationsChoose3(int n, int k) //for when k = 3
  {
      for (int a = 1; a &lt; n - 1; a++)
      {
          for (int b = a + 1; b &lt; n; b++)
          {
              for (int c = b + 1; c &lt;= n; c++)
              {
                  System.out.println("" + a + " " + b + " " + c);
              }
          }
      }
  }
  
  public void printCombinationsChoose4(int n, int k) //for when k = 4
  {
      for (int a = 1; a &lt; n - 2; a++)
      {
          for (int b = a + 1; b &lt; n - 1; b++)
          {
              for (int c = b + 1; c &lt; n; c++)
              {
                  for (int d = c + 1; d &lt;= n; d++)
                  {
                      System.out.println("" + a + " " + b + " " + c + " " + d);
                  }
              }
          }
      }
  }
  
  public void printCombinations(int n, int k) //Doesn't work
  {
      int[] nums = new int[k];
      for (int i = 1; i &lt;= nums.length; i++)
          nums[i - 1] = i;
  
      int count = 1;
  
      while (count &lt;= k)
      {
          for (int a = nums[k - count]; a &lt;= n; a++)
          {
              nums[k - count] = a;
  
              for (int i = 0; i &lt; nums.length; i++)
                  System.out.print("" + nums[i] + " ");
              System.out.println();
          }
          count++;
      }
  }
  </code></pre>
  
  <p>So I think the layout of my last method is right, but I'm just not doing the right things, because when I call <code>printCominbations(5, 2)</code>, it prints</p>
  
  <pre><code>1 2 
  1 3 
  1 4 
  1 5 
  1 5 
  2 5 
  3 5 
  4 5 
  5 5 
  </code></pre>
  
  <p>when it should be what I said earlier for 5C2.</p>
  
  <p><strong>Edit</strong>
  The last example was bad. This is a better one to illustrate what it's doing wrong: <code>printCombinations(5, 3)</code> gives this:</p>
  
  <pre><code>1 2 3 
  1 2 4 
  1 2 5 
  1 2 5 
  1 3 5 
  1 4 5 
  1 5 5 
  1 5 5 
  2 5 5 
  3 5 5 
  4 5 5 
  5 5 5 
  </code></pre>
  
  <p>How do I get it to be:</p>
  
  <pre><code>1 2 3
  1 2 4
  1 2 5
  1 3 4
  1 3 5
  1 4 5
  2 3 4
  2 3 5
  2 4 5
  3 4 5
  </code></pre>