ALGORITHM/BOJ
[백준_javascript] 심화 1 (1157, 2941, 1316, 25206)
오늘도 코딩하나
2024. 8. 11. 17:16
#1157 (단어 공부)
solution1_Object.
const fs = require('fs');
const file = process.platform === 'linux' ? '/dev/stdin' : __dirname+'/input.txt';
const input = fs.readFileSync(file).toString().trim().toLowerCase().split('');
const result = [];
input.forEach(x => {
result[x] = (result[x] || 0) + 1;
})
const max = Math.max(...Object.values(result));
const maxKey = Object.keys(result).find(x => result[x] === max);
const maxLen = Object.values(result).filter(x => x === max);
console.log(maxLen.length > 1 ? '?' : maxKey.toUpperCase());
solution2_charCodeAt().
const fs = require('fs');
const file = process.platform === 'linux' ? '/dev/stdin' : __dirname+'/input.txt';
const input = fs.readFileSync(file).toString().trim().toUpperCase().split('');
const arr = new Array(26).fill(0);
for(let i of input) {
const char = i.charCodeAt();
arr[char-65] += 1;
}
const max = Math.max(...arr);
const maxCnt = arr.filter(x => x === max).length;
const index = arr.indexOf(max);
const result = String.fromCharCode(index + 65);
console.log(maxCnt === 1 ? result : '?');
#2941 (크로아티아 알파벳)
solution1_includes().
const fs = require('fs');
const file = process.platform === 'linux' ? '/dev/stdin' : __dirname+'/input.txt';
let input = fs.readFileSync(file).toString().trim();
const alpha = ['c=', 'c-', 'dz=', 'd-', 'lj', 'nj', 's=', 'z='];
alpha.forEach(x => {
if(input.includes(x)) {
input = input.replaceAll(x,'.');
}
});
console.log(input.length);
solution2_replaceAll().
const fs = require('fs');
const file = process.platform === 'linux' ? '/dev/stdin' : __dirname+'/input.txt';
let input = fs.readFileSync(file).toString().trim();
const alpha = ['c=', 'c-', 'dz=', 'd-', 'lj', 'nj', 's=', 'z='];
for(let x of alpha) {
input = input.replaceAll(x,'.');
}
console.log(input.length);
### 틀렸습니다.
const fs = require('fs');
const file = process.platform === 'linux' ? '/dev/stdin' : __dirname+'/input.txt';
let input = fs.readFileSync(file).toString().trim();
const alpha = ['c=', 'c-', 'dz=', 'd-', 'lj', 'nj', 's=', 'z='];
let cnt = alpha.filter(x => input.includes(x));
let count = 0;
alpha.forEach(x => {
if(input.includes(x)) {
count += input.split(x).length-1;
input = input.replaceAll(x,'');
}
});
console.log(count + input.length);
▶ 초기 내가 작성한 소스코드다.
예제대로 테스트했을 때는 정상출력되는 줄 알았으나,
' nljj'로 테스트 했을 때, alpha에서 lj만 걸려야하는데, lj가 걸리고 for문 안에서 replace되면서 nj까지 count가 되는 문제 가 발생했다.
⇒ 그래서 수정한 후.. solution1의 소스코드를 최종 작성했다.
### 참고한 블로그
https://hianna.tistory.com/459
https://parkparkpark.tistory.com/65