Poylib
기록형 프론트엔드
Poylib
전체 방문자
오늘
어제
  • 분류 전체보기 (91)
    • Programing (38)
      • Javascript (17)
      • Typescript (1)
      • React (9)
      • React-Native (6)
      • Git (4)
      • Next (1)
    • Study (36)
      • Algorithm (35)
      • Etc. (1)
    • Record (17)
      • Memoirs (12)
      • Group (5)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 백준
  • Git
  • vite
  • ReactNative
  • react-native
  • typescript
  • Error
  • 회고
  • Object
  • 코칭스터디
  • react
  • javascript
  • 기초
  • 프로그래머스
  • 자바스크립트
  • 알고리즘
  • 코딩테스트
  • 리액트

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Poylib

기록형 프론트엔드

[BEAKJOON / node.js] 1302 베스트셀러
Study/Algorithm

[BEAKJOON / node.js] 1302 베스트셀러

2022. 6. 21. 22:07
https://www.acmicpc.net/problem/1302

//test.txt
9
table
chair
table
table
lamp
door
lamp
table
chair

sol1

let [N,...input] = require('fs').readFileSync('test.txt').toString().trim().split('\n');
let map = new Map();
let answer = input.reduce((acc,cur) => {
  let best = (map.get(cur)||0) +1;
  let max = (map.get(acc)||0);
  map.set(cur,best);
  if(best>max) acc=cur;
  else if(best === max) cur<acc ? acc=cur : acc;
  return acc
},0);
console.log(answer)
//table

map에 중복 횟수를 체크해서 담고 가장 높은 값을 출력한다. 만약 가장 높은 값이 두 개라면 사전 순으로 빠른 제목이 출력된다. 

for문으로 map에 담을 수도 있지만 reduce() 메서드를 이용한 방법을 찾게돼서 적용해보았다. 

 

1.

let map = new Map();
let answer = input.reduce((acc,cur) => {
  let best = (map.get(cur)||0) +1;
  map.set(cur,best);
  return acc
},0);
console.log(map)
//Map(4) { 'table' => 4, 'chair' => 2, 'lamp' => 2, 'door' => 1 }

map에 중복 횟수를 체크해서 담는 단계까지다.

 

2.

let answer = input.reduce((acc,cur) => {
  let best = (map.get(cur)||0) +1;
  let max = (map.get(acc)||0);
  //최댓값을 따로 저장해 둠
  map.set(cur,best);
  
  if(best>max) acc=cur;
  else if(best === max) cur<acc ? acc=cur : acc;
  
  return acc
},0);

localeCompare() 메서드 대신 reduce() 메서드 안에서 바로 비교 가능하다.

저작자표시 비영리 변경금지 (새창열림)

'Study > Algorithm' 카테고리의 다른 글

[BEAKJOON / node.js] 17298 오큰수  (0) 2022.06.25
[programmers / JavaScript] 기능 개발  (0) 2022.06.22
[BEAKJOON / node.js] 1744 수 묶기  (0) 2022.06.17
[BEAKJOON / node.js] 12904 A와 B  (0) 2022.06.16
[BEAKJOON / node.js] 9935 문자열 폭발  (0) 2022.06.15
    'Study/Algorithm' 카테고리의 다른 글
    • [BEAKJOON / node.js] 17298 오큰수
    • [programmers / JavaScript] 기능 개발
    • [BEAKJOON / node.js] 1744 수 묶기
    • [BEAKJOON / node.js] 12904 A와 B
    Poylib
    Poylib
    모시깽 기록

    티스토리툴바