function solution(n, k) {
var answer = [];
const arr = Array.from({length:n+1},(_,i)=>i)
return getKth(arr,k)
}
function getKth (arr,k){
if(k===1) return arr.slice(1)
if(k===0) return arr.slice(1).sort((a,b)=>b-a)
if(arr.length===1) return arr
const n = arr.length-1
let unit = factorial(n-1)
let first = Math.ceil(k/unit)
let rest = k%unit
let newArr = [...arr.slice(0,first),...arr.slice(first+1)]
return [arr[first],...getKth(newArr,rest)]
}
function factorial(n){
if(n<2) return 1
return n*factorial(n-1)
}
const getPermutations = function (arr, selectNumber,k){
const results = [];
if(selectNumber===1) return arr.map((el)=>[el]);
for(let i=0;i<arr.length;i++){
const rest = [...arr.slice(0,i),...arr.slice(i+1)]
const permutations = getPermutations(rest,selectNumber-1)
const attached = permutations.map((el)=>[arr[i],...el])
results.push(...attached)
}
return results
}
// const getPermutations = function (arr, selectNumber) {
// const results = [];
// if (selectNumber === 1) return arr.map((el) => [el]);
// // n개중에서 1개 선택할 때(nP1), 바로 모든 배열의 원소 return. 1개선택이므로 순서가 의미없음.
// arr.forEach((fixed, index, origin) => {
// const rest = [...origin.slice(0, index), ...origin.slice(index+1)]
// // 해당하는 fixed를 제외한 나머지 배열
// const permutations = getPermutations(rest, selectNumber - 1);
// // 나머지에 대해서 순열을 구한다.
// const attached = permutations.map((el) => [fixed, ...el]);
// // 돌아온 순열에 떼 놓은(fixed) 값 붙이기
// results.push(...attached);
// // 배열 spread syntax 로 모두다 push
// });
// return results; // 결과 담긴 results return
// }