Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You don't need recursion, or heavily nested loops, or even to generate/store the whole array of permutations in memory.</p> <p>Since the number of permutations is the product of the lengths of each of the arrays (call this <code>numPerms</code>), you can create a function <code>getPermutation(n)</code> that returns a unique permutation between index <code>0</code> and <code>numPerms - 1</code> by calculating the indices it needs to retrieve its characters from, based on <code>n</code>.</p> <p>How is this done? If you think of creating permutations on arrays each containing: [0, 1, 2, ... 9] it's very simple... the 245th permutation (n=245) is "245", rather intuitively, or:</p> <pre><code>arrayHundreds[Math.floor(n / 100) % 10] + arrayTens[Math.floor(n / 10) % 10] + arrayOnes[Math.floor(n / 1) % 10] </code></pre> <p>The complication in your problem is that array sizes differ. We can work around this by replacing the <code>n/100</code>, <code>n/10</code>, etc... with other divisors. We can easily pre-calculate an array of divisors for this purpose. In the above example, the divisor of 100 was equal to <code>arrayTens.length * arrayOnes.length</code>. Therefore we can calculate the divisor for a given array to be the product of the lengths of the remaining arrays. The very last array always has a divisor of 1. Also, instead of modding by 10, we mod by the length of the current array.</p> <p>Example code is below:</p> <pre><code>var allArrays = [first, second, third, ...]; // Pre-calculate divisors var divisors = []; for (var i = allArrays.length - 1; i &gt;= 0; i--) { divisors[i] = divisors[i + 1] ? divisors[i + 1] * allArrays[i + 1].length : 1; } function getPermutation(n) { var result = "", curArray; for (var i = 0; i &lt; allArrays.length; i++) { curArray = allArrays[i]; result += curArray[Math.floor(n / divisors[i]) % curArray.length]; } return result; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload