JavaScripts 문제

문제 57. 모의고사 완전 탐색 (난이도 7)

kagan-draca 2024. 8. 19. 12:45

 

one, two, three 배열의 요소가 answers 요소에 얼마나 부합 하는가를 보는 문제로

먼저,

 

answers.forEach((element, index)=>

{

})

answers의 요소를 순회할 수 있게 만들었다.

 

그 후, 

 

one, two, three 배열의 요소와 element가

동일한지를 찾아야 하는데

 

one, two, three의 배열의 index가

0 ~ array.length - 1까지 반복적으로

순회해야 하기 때문에

 

answers.forEach((element, index)=>

{
    if(one[index % one.length] === element) count1++;
    if(two[index % two.length] === element) count2++;
    if(three[index % three.length] === element) count3++;
})

 

배열[index % 배열의 길이]로 순회할 수 있게 만들고,

element와 비교해서 같으면 각자의 count를 증가시켜줬다.

 

let max = Math.max(count1, count2, count3)

제일 많이 맞춘 사람의 개수를 정해주고,

 

let order = []

max == count1 ? order.push(1) : null;
max == count2 ? order.push(2) : null;
max == count3 ? order.push(3) : null;

 

으로 개수가 동일하면 1, 2, 3번 번호 순으로

순위 배열에 담아줬다.

 

제출한 코드 : 

 

function solution(answers) 
{
    let one = [1,2,3,4,5], two = [2, 1, 2, 3, 2, 4, 2, 5], three = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]
    let count1 = 0, count2 = 0, count3 = 0;
    answers.forEach((element, index)=>
    {
        if(one[index % one.length] === element) count1++;
        if(two[index % two.length] === element) count2++;
        if(three[index % three.length] === element) count3++;
    })
    let order = []
    let max = Math.max(count1,count2,count3)
    max == count1 ? order.push(1) : null;
    max == count2 ? order.push(2) : null;
    max == count3 ? order.push(3) : null;
    return order
}