# 줄 서는 방법

## **문제 설명**

n명의 사람이 일렬로 줄을 서고 있습니다. n명의 사람들에게는 각각 1번부터 n번까지 번호가 매겨져 있습니다. n명이 사람을 줄을 서는 방법은 여러가지 방법이 있습니다. 예를 들어서 3명의 사람이 있다면 다음과 같이 6개의 방법이 있습니다.

* \[1, 2, 3]
* \[1, 3, 2]
* \[2, 1, 3]
* \[2, 3, 1]
* \[3, 1, 2]
* \[3, 2, 1]

사람의 수 n과, 자연수 k가 주어질 때, 사람을 나열 하는 방법을 사전 순으로 나열 했을 때, k번째 방법을 return하는 solution 함수를 완성해주세요.

**제한사항**

* n은 20이하의 자연수 입니다.
* k는 n! 이하의 자연수 입니다.

***

**입출력 예**

| n | k | result   |
| - | - | -------- |
| 3 | 5 | \[3,1,2] |

**입출력 예시 설명**

입출력 예 #1\
문제의 예시와 같습니다.

## 코드

순열을 이용해서 풀이하는 것은 알겠는데 모든 경우의 수를 구하면 런타임 에러가 난다고 한다.

```javascript
function solution(n, k) {
    // 순열
    let answer = [];
    let arr = Array.from(Array(n), (_,i) => i + 1); // [1,2,3]
    
    let fac = arr.reduce((ac,v) => ac * v, 1);
    k--;

    while(answer.length !== n) {
        fac = fac / arr.length; 
        let temp = arr[Math.floor(k / fac)];
        answer.push(temp);
        k = k % fac;
        arr = arr.filter(v => v !== temp);
    }
    return answer;
}
```

순열 경우의 수를 모두 구한 다음에 k 번째를 찾는 방식이 아니라, 첫번째 자릿수부터 차근차근 찾아가는 방식이다. (사전순)

기본적으로 순열은 n x (n-1) x (n-2) x ... 1 = n! 가지의 경우의 수를 가진다.

맨 앞자리 수 후보 n개, 두번째 자리수 후보 n-1개 ... 중에서 각 자릿수가 결정되기 때문이다.

그러므로 맨 앞자리 수를 구하려면 (n-1)!이 k앞에 몇 개 있는지 확인해야 한다.

.

.

.

<https://jiwoo84.tistory.com/116>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://songeun.gitbook.io/coding-test/lv.2/12.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
