# Permuations



{% tabs %}
{% tab title="demo" %}
{% embed url="https://codesandbox.io/embed/permutations-97740?fontsize=14&hidenavigation=1&theme=dark" %}
Permutations
{% endembed %}
{% endtab %}

{% tab title="JS" %}
💾 程式：codesandbox - [Permutations](https://codesandbox.io/s/permutations-97740?file=/math/combinatorics.js)

```javascript
/**
 * find all the permutations of an array.
 * @param {any[]} arr - array (of distinct elements)
 */
export function permutations(arr) {

  // base case:
  if (arr.length === 1) return [arr];
  
  // recursive case:
  //     |ABC = A|BC + B|AC + C|AB
  // hint: A|BC means fix A, permute BC.
  return arr
    .map((x, i) => {
      let subarr = arr.slice(); // copy array
      subarr.splice(i, 1); // remove `x` in place
      return permutations(subarr).map((p) => [x, ...p]);
    })
    .reduce((union, ps) => [...union, ...ps], []);
}
```
{% endtab %}

{% tab title="👥 相關" %}
* [matrix-methods](../../val/builtin/arr/matrix-methods "mention")functions
{% endtab %}
{% endtabs %}
