[알고리즘] 양궁대회

Jay ·2023년 6월 23일
0

문제

2022 KAKAO BLIND RECRUITMENT
양궁대회

https://school.programmers.co.kr/learn/courses/30/lessons/92342

풀이

DFS로 경우의 수를 모두 구한 뒤
순회하여 Diff가 가장큰 배열을 찾는 방식으로 접근하였다.


function getCombinations (arr, n) {
    let res = [];
    
    function dfs(depth, temp, count) {
        if(count > n) return;
        if(temp.length > 11) return;
        if(count === n) {
             return res.push(temp.join("").padEnd(11, '0').split("").map((item) => +item));
        }
        
        for(let i=0; i<=(arr[depth] + 1); i++){
            dfs(depth+1, [...temp, i], count + i)
        }
    }
    
    dfs(0, [], 0);

    return res;
    }

function compareArrs (arr1, arr2) {
    let tempArr1 = [...arr1];
    let tempArr2 = [...arr2];
    
    let result = arr2;
    
    while(tempArr1.length){
        const first = tempArr1.pop();
        const latter = tempArr2.pop();
        if(first > latter) return arr1;
        else if (latter > first) return arr2;
        else continue;
    }
    
    return result;
}

function getMaxDiffArray(combinations, appeachBoard) {
    let maxDiff = 0;
    let answer =[];
    
    combinations.map((combination,i) => {
        let appeachScore = 0;
        let ryanScore = 0;
        
         // 점수 계산
        combination.map((item, j) => {
            const appeachItem = appeachBoard[j];
            const ryanItem = item;

            if(appeachItem >= ryanItem) {
                if(appeachItem !== 0) appeachScore += (10-j)
            } else {
                if(ryanItem !== 0) ryanScore += (10-j)
            }
        })
        
        // appeachScore vs ryanScore 값에 따라 연산
        if(appeachScore >= ryanScore) return;
        else {
            if(ryanScore - appeachScore > maxDiff) {
                maxDiff = ryanScore - appeachScore;
                answer = combination;
            }
            else if(ryanScore - appeachScore === maxDiff) {
            
                answer = compareArrs(answer, combination);
            }
            else return;
        }
    })
    return answer;
}


function solution(n, info) {
    // 모든 경우의 수 구하기
    const combinations = getCombinations(info, n);
    // 경우의 수 순회하여 maxTotal이 나오는 경우 arr 저장.
    const maxTotalArray = getMaxDiffArray(combinations, info);
    return maxTotalArray.length? maxTotalArray : [-1];
}
profile
Jay입니다.

0개의 댓글