[JS] 백준 1157번 단어공부

jsg_ko·2021년 11월 23일
0

코테연습

목록 보기
15/21
const fs = require("fs"); //파일받기위해 필요
const localFile = fs.existsSync("./input.txt"); // 내가 알고리즘 풀려는 폴더에 './input.txt'의 유무를 참,거짓으로 변수에 넣어라
const filePath = () => {
  // 참이면 내 input파일을 열고 그외는 백준의 알고리즘에서 주는 입력값을 받겠다.
  if (localFile) {
    return "./input.txt";
  }
  return "/dev/stdin";
};

let input = fs.readFileSync(filePath()).toString().toUpperCase(); // 대문자로
input = input.slice(0,input.length-1); // 입력값에 개행문자가 왜 들어있는지 모르겠는데 개행문자 빼줫다

const countWordData = {}; // 각 단어의 반복횟수를 가진 객체
const inspetedWord = []; 

for(let i=0; i < input.length; i++){
  if(inspetedWord.indexOf(input[i]) === -1){ // 아직 검사하지 않은 단어는 default 1 
    inspetedWord.push(input[i]);
    countWordData[input[i]] = 1;
  } else { // 한번 검사한 단어는 카운트 시작 
    countWordData[input[i]] = countWordData[input[i]] + 1;
  }
}

let resultValue; 
let repetitionCheck;
for(let key in countWordData){ 

  if(repetitionCheck === undefined){ // 맨처음
    repetitionCheck = countWordData[key] // 가장많이 반복된 단어의 횟수가 저장된 변수 업데이트
    resultValue = key // 결과값 업데이트 
  } else {
    
    if(countWordData[key] > repetitionCheck){ // 현재의 key값(반복횟수)가 더크면
      repetitionCheck = countWordData[key] 
      resultValue = key; 
    } else if(countWordData[key] === repetitionCheck){  // 현재의 key값(반복횟수)과 같으면 (가장많이반복된 단어가 다수이면)
      resultValue = '?';
    }
  }
} 
console.log(resultValue)
profile
디버깅에서 재미를 추구하면 안되는 걸까

0개의 댓글