카테고리 없음
[프로그래머스 level.1] max, 반복되는 인덱스
고래강이
2023. 6. 20. 13:58
모의고사
function solution(answers) {
const first = [1, 2, 3, 4, 5]; //5
const second = [2, 1, 2, 3, 2, 4, 2, 5]; // 8
const third = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]; //10
let scores = [0, 0 ,0]
for (let i = 0; i < answers.length; i++) {
if (first[i % 5] === answers[i]) {scores[0] ++};
if (second[i % 8] === answers[i]) {scores[1] ++};
if (third[i % 10] === answers[i]) {scores[2] ++};
}
let answer = []
let max = Math.max(...scores)
if (scores[0] === max) {answer.push(1)};
if (scores[1] === max) {answer.push(2)};
if (scores[2] === max) {answer.push(3)};
return answer;
}
Math.max 값 안에 배열을 집어넣을 수 없다는 것을 다시 한번 기억하고 spread 함수 잘 써서 max 값 구하자
인덱스를 나누는 방식을 기억해 놓으면 좋을 것 같다 이거 은근 잘 써먹을 수 있을 지 않을까 생각이 든다
다 풀어놓고 보니까 반복문이랑 if문이 좀 많이 들어가서 filter함수나 삼항연산자와 && || 같은 애들로 리팩토링 하고 싶은 마음이 들다가 만다.