TIL 220826

신승준·2022년 8월 28일
0

알고리즘

프로그래머스

  1. Level 1 신고 결과 받기
function solution(id_list, report, k) {
    let result = new Object();
    let getReported = new Object();
    id_list.forEach((element) => {
        result[element] = 0;
        getReported[element] = new Array();
    })
    
    report.forEach((element) => {
        const [a, b] = element.split(' ');
        if (!getReported[b].includes(a)) {
            getReported[b].push(a);
        }
    })
    
    Object.keys(getReported).forEach((element) => {
        if (getReported[element].length >= k) {
            getReported[element].forEach((element2) => {
                result[element2] += 1;
            })
        }
    })
    
    return Object.values(result);
}
  1. Level 1 키패드 누르기
function distance(a, b) {
    return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]);
}

function solution(numbers, hand) {
    let result = '';
    let currentLeftHand = '*';
    let currentRightHand = '#';
    const graph = {
        1: [1, 1],
        2: [1, 2],
        3: [1, 3],
        4: [2, 1],
        5: [2, 2],
        6: [2, 3],
        7: [3, 1],
        8: [3, 2],
        9: [3, 3],
        '*': [4, 1],
        0: [4, 2],
        '#': [4, 3]
    }
    
    numbers.forEach((number) => {
        if ([1, 4, 7].includes(number)) {
            result += 'L';
            currentLeftHand = number;
        } else if ([3, 6, 9].includes(number)) {
            result += 'R';
            currentRightHand = number;
        } else {
            if (distance(graph[number], graph[currentLeftHand]) < distance(graph[number], graph[currentRightHand])) {
                result += 'L';
                currentLeftHand = number;
            } else if (distance(graph[number], graph[currentLeftHand]) > distance(graph[number], graph[currentRightHand])) {
                result += 'R';
                currentRightHand = number;
            } else {
                if (hand === 'left') {
                    result += 'L';
                    currentLeftHand = number;
                } else {
                    result += 'R';
                    currentRightHand = number;
                }
            }   
        }
    })
    
    return result;
}
profile
메타몽 닮음 :) email: alohajune22@gmail.com

0개의 댓글