title: Cartesian power - via recursion
body: <p>The original question is here: <a href="https://stackoverflow.com/questions/52977819">Cartesian power (a special Cartesian product) -- choose elements from array, in repeatable style</a></p>
  
  <p>In the old question, there are already answers gave a solution via iteration.</p>
  
  <p>I am wondering is there a <strong>recursive</strong> solution, similar as the solution from following link, which print permutations with recursion: <a href="https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/</a> </p>
  
  <p>Currently I have wrote following program, which is not correct yet, any help?</p>
  
  <hr>
  
  <h2>Code - implementation</h2>
  
  <p><strong>CartesianPowerRecursive.java:</strong></p>
  
  <pre class="lang-java prettyprint-override"><code>import java.util.Arrays;
  
  /**
   * Print cartesian power of array elements, by recursion.
   * 
   * @author eric
   * @date Oct 13, 2018 12:28:10 PM
   */
  public class CartesianPowerRecursive {
      public static int cartesianPower(int arr[]) {
          int tmpArr[] = Arrays.copyOf(arr, arr.length);
          return cartesianPower(arr, tmpArr, 0, 0);
      }
  
      private static int cartesianPower(int arr[], int tmpArr[], int n, int m) {
          // FIXME ... not correct yet,
  
          int counter = 0;
          for (int i = n; i &lt; arr.length; i++) {
              for (int j = m; j &lt; arr.length; j++) {
                  tmpArr[j] = arr[i];
                  counter += cartesianPower(arr, tmpArr, n, j + 1);
              }
          }
  
          if (m == arr.length - 1) {
              counter++;
              System.out.println(Arrays.toString(tmpArr));
          }
  
          return counter;
      }
  }
  </code></pre>
  
  <hr>
  
  <h2>Code - test case</h2>
  
  <p><em>(via <strong>TestNG</strong>)</em></p>
  
  <p><strong>CartesianPowerRecursiveTest.java:</strong></p>
  
  <pre class="lang-java prettyprint-override"><code>import org.testng.Assert;
  import org.testng.annotations.Test;
  
  /**
   * CartesianPowerRecursive test.
   * 
   * @author eric
   * @date Oct 26, 2018 11:45:27 PM
   */
  public class CartesianPowerRecursiveTest {
      @Test
      public void test() {
          int arr[] = new int[] { 0, 1, 2 };
          Assert.assertEquals(CartesianPowerRecursive.cartesianPower(arr), 27);
      }
  }
  </code></pre>