Get Permutations

by Génesis García Morilla

JavaScript

function getPermutations(a) {
  let p = []

  if (a.length == 1) {
    p.push(a)
    return p
  }

  for (let i = 0; i < a.length; i++) {
    const rest = getPermutations([...a.slice(0, i), ...a.slice(i + 1)])      
    for (const r of rest) p.push([a[i], ...r])
  }
  
  return p
}


document.body.innerHTML = getPermutations([1, 2, 3]).join('<br>')