HIT해
[JS 백준] 11866.요세푸스 문제 0 본문
728x90
const filePath = process.platform === 'linux' ? '/dev/stdin' : 'input.txt';
const [n,input] = require("fs")
.readFileSync(filePath)
.toString()
.trim().split(' ').map(v => +v)
const solution = (n,input) =>{
let arr = new Array(n).fill(0);
arr.forEach((el,i)=> arr[i] = (arr[i-1] || 0) + 1);
let i = -1;
let count = 0;
let result = [];
while(result.length !== n){
i++; // 인덱스를 위해
count++; // 몇번 갔는지
if(count % input === 0){
result.push(arr[i]);
arr.splice(i,1);
i--;
}
if(i === arr.length-1){
i=-1;
}
}
return '<' + result.join(', ') + '>';
}
console.log(solution(n,input));
배운점
.join(문자열) 을 통해 출력될 때 문자열을 사이에 넣어 출력한다.(console.log를 한다면) 그냥 넣으면 출력안함
그러나 출력에서만 영향을 주고 배열 자체에는 영향을 주지 않는다.
splice 문법이 상당히 유용하다.
map(Number) 과 map(v => +v) 는 같다.
arr.forEach((el,i)=> arr[i] = (arr[i-1] || 0) + 1);
이 구문은 el 은 현재 접근값에 넣을 현재 변수,
arr[i] 에 arr[i-1]이 존재한다면 arr[i-1] + 1을 현재 값에 할당
없다면 ( 배열 index -1) 일때는 0에 1을 더함
'Vue > JavaScript 알고리즘' 카테고리의 다른 글
[JS 백준] 9663. N-Queen (0) | 2024.01.09 |
---|---|
[JS 백준] 15649.N과 M (1) (0) | 2024.01.08 |
[JS 백준] 28279.덱 2 (0) | 2024.01.07 |
[JS 백준] 9012.괄호 (0) | 2024.01.07 |
[JS 백준] 1929.소수 구하기 (0) | 2024.01.06 |