문제 설명
배열에 있는 숫자들 중(1~5까지의 숫자) 가장 많이 나타난 숫자를 찾고,
가장 많이 나타난 숫자가 두개 이상이라면 그 중 더 작은 숫자를 리턴하는 문제
'use strict';
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', function(inputStdin) {
inputString += inputStdin;
});
process.stdin.on('end', function() {
inputString = inputString.split('\n');
main();
});
function readLine() {
return inputString[currentLine++];
}
/*
* Complete the 'migratoryBirds' function below.
*
* The function is expected to return an INTEGER.
* The function accepts INTEGER_ARRAY arr as parameter.
*/
function migratoryBirds(arr) {
// Write your code here
let array = arr.sort((a,b) => a-b).reduce((i,j) => {
i[j-1] ++
return i
},[0,0,0,0,0])
return array.findIndex(i => i === (Math.max(...array))) +1
}
function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const arrCount = parseInt(readLine().trim(), 10);
const arr = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
const result = migratoryBirds(arr);
ws.write(result + '\n');
ws.end();
}
처음엔 이중포문으로 복잡하게 풀다가 reduce를 이용해보자는 생각이 들었다
배열 속 숫자가 몇개던 무조건 1~5까지의 숫자밖에 없기 때문에
일단 배열을 작은 숫자부터 sort 해 준 뒤,
reduce를 사용해서 i의 j-1번째 인덱스마다 1씩 더해주었다
예를 들어
migratoryBirds([1 ,2 ,3 ,4 ,5 ,4 ,3 ,2 ,1 ,3 ,4])
가 들어왔을 때
최종적으로 array의 값은
[ 2, 2, 3, 3, 1 ]
가 된다.
array의 요소 중 가장 많이 나타난 인덱스를 찾아서 1을 더해주고 리턴해주면
해당 숫자의 등장 횟수가 리턴된다!
해결!
똑똑하시네요~