https://www.acmicpc.net/problem/1439

//test.txt
11001100110011000001
sol1
const input = require('fs').readFileSync('test.txt').toString().trim();
function solution(input) {
if(input.includes(0) && input.includes(1)) {
let toOne = input.split(0).filter(el => el!== '').length;
let toZero = input.split(1).filter(el => el!== '').length;
return toOne < toZero ? toOne : toZero;
} else return 0
};
console.log(solution(input));
입력받은 문자열이 '0000' 이거나 '111'처럼 바꿀 필요가 없는 경우엔 바로 0을 출력하게 하고, 0과 1이 모두 있는 경우만 조건에 맞는 값을 출력한다.
let toOne = input.split(0).filter(el => el!== '');
let toZero = input.split(1).filter(el => el!== '');
console.log(toOne);
console.log(toZero);
// [ '11', '11', '11', '11', '1' ]
// [ '00', '00', '00', '00000' ]
split()으로 나누면 구분자는 [''] 빈 요소로 남게 되기 때문에 filter() 메서드를 사용해 빈 요소를 제거한 길이를 비교해야 한다. 0으로 나눈 경우, 1로 나눈 경우 중에서 배열의 길이가 작은 쪽을 출력하면 된다.
'Study > Algorithm' 카테고리의 다른 글
[BEAKJOON / node.js] 10816 숫자 카드 2 (0) | 2022.06.11 |
---|---|
[BEAKJOON / node.js] 11659 구간 합 구하기 4 (0) | 2022.06.10 |
[BEAKJOON / node.js] 2775 부녀회장이 될테야 (0) | 2022.06.07 |
<programmers / JavaScript> 신고 결과 받기 (0) | 2022.06.03 |
<BEAKJOON / node.js> 1181 단어정렬 (0) | 2022.05.29 |