[과제] JS 프로그래머스 입문 15문제 & 머쓱이 획득 (25.02.19)

2025. 2. 19. 21:50·LG 유플러스 유레카 SW/과제

1. 등수 매기기

function solution(score) {
    let avg = score.map(s => (s[0] + s[1]) / 2);
    let sorted = avg.slice().sort((a, b) => b - a); // slice로 원본 배열 변경 방지

    return avg.map(v => sorted.indexOf(v) + 1);
    
}

2. 저주의 숫자 3

function solution(n) {
    let answer = 0;
    for(let i = 1, j = 0; i <= n; i++){
        answer++;
        
        while(true){
            if(answer % 3 === 0 || String(answer).includes("3")){
                answer += 1;
                continue;
            }
            break;
        }
    }
    return answer;
}

3. 유한소수 판별하기

function GCD(num1, num2) {
    let gcd = 1;
    for(let i = 2; i <= Math.min(num1, num2); i++) {
        if(num1 % i === 0 && num2 % i === 0) {
            gcd = i;
        }
    }
    return gcd;
}

function solution(a, b) {
    let gcd = GCD(a, b);
    b /= gcd;
    
    while(b > 1) {
        if(b % 2 === 0) b /= 2;
        else if(b % 5 === 0) b /= 5;
        else break;
    }
    return b === 1 ? 1 : 2;
}

4. 문자열 밀기

function solution(A, B) {
    let answer = 0;
    let aArr = A.split("");

    if(A === B) return 0;
    for(let i = 0; i < A.length; i++) {
        aArr.unshift(aArr.pop());
        answer++;
        if(aArr.join("") === B) {
            break;
        }
        
    }

    return aArr.join("") === B ? answer : -1;
}

5. 특이한 정렬

function solution(numlist, n) {
    return numlist.sort((a, b) => {
            const diffA = Math.abs(n - a);
            const diffB = Math.abs(n - b);

            if (diffA === diffB) return b - a; // 거리가 같다면 큰 숫자를 먼저
            return diffA - diffB; // 거리가 가까운 순서대로 정렬
        });
}

6. 다항식 더하기

function solution(polynomial) {
    const terms = polynomial.split(/\s*\+\s*/); // '+' 기준으로 분리 후 공백 제거
    let xSum = 0, numSum = 0;

    terms.forEach(term => {
        if (term.includes('x')) {
            let coeff = term.replace('x', ''); // 'x' 제거
            xSum += coeff === '' ? 1 : parseInt(coeff); // 계수 처리
        } else {
            numSum += parseInt(term); // 상수 처리
        }
    });

    let result = [];
    if (xSum) result.push(xSum === 1 ? 'x' : `${xSum}x`); 
    if (numSum) result.push(numSum.toString());

    return result.join(' + ');
}

7. 최빈값 구하기

function solution(array) {
    let map = new Map();
    for (let n of array) {
        map.set(n, (map.get(n) || 0) + 1);
    }
    map = [...map].sort((a, b)=> b[1] - a[1]);
    return map.length === 1 || map[0][1] > map[1][1] ? map[0][0] : -1;
}

8. OX퀴즈

function solution(quiz) {
    let answer = [];
    quiz.forEach((q) => {
        let arr = q.split(/\s*\=\s*/);
        if(eval(arr[0]) === Number(arr[1])) answer.push("O");
        else answer.push("X");
    })
    return answer;
}

9. 다음에 올 숫자

function solution(common) {
    let a = common[1] - common[0];
    let b = common[1] / common[0];
    
    if(a === common[2] - common[1]) {
        return common[common.length - 1] + a;
    } else {
        return common[common.length - 1] * b;
    }
}

10. 연속된 수의 합

function solution(num, total) {
    let answer = [];
    let start = (total - (num * (num - 1)) / 2) / num;

    for (let i = 0; i < num; i++) {
        answer.push(start + i);
    }

    return answer;
}

// 연속된 num개의 정수를 x, x+1, ..., x+(num-1)로 표현 가능
// 이들의 합은 num * x + (0 + 1 + ... + (num-1))
// total = num * x + (num * (num - 1)) / 2
// x =(total - (num * (num - 1)) / 2) / num

11. 분수의 덧셈

function gcd(a, b) {
    return b === 0 ? a : gcd(b, a % b);
}

function lcm(a, b) {
    return (a * b) / gcd(a, b);
}

function solution(numer1, denom1, numer2, denom2) {
    
    let denom = lcm(denom1, denom2);
    
    numer1 = numer1 * (denom / denom1);
    numer2 = numer2 * (denom / denom2);
    let numer = numer1 + numer2;
    
    let g = gcd(numer, denom);
    return [numer / g, denom /g];
}

12. 안전지대

function solution(board) {
    var answer = 0;
    let dx = [0, 1, -1, 0, 1, -1, 1, -1];
    let dy = [1, 0, 0, -1, 1, -1, -1, 1];
    let n = board.length;

    let copyBoard = board.map(row => [...row]);

    for(let i = 0; i < board.length; i++) {
        for(let j = 0; j < board.length; j++) {
            if(board[i][j] === 1) {
                for(let k = 0; k < 8; k++) {
                    let ni = i + dx[k];
                    let nj = j + dy[k];

                    if(ni >= 0 && ni < n && nj >= 0 && nj < n) {
                        copyBoard[ni][nj] = 1;
                    }
                }
            }
        }
    }

    return copyBoard.flat().filter(v => v === 0).length;
}

13. 겹치는 선분의 길이

function solution(lines) {
    const overlap = new Map();

    lines.forEach(([start, end]) => {
        for (let i = start; i < end; i++) {
            overlap.set(i, (overlap.get(i) || 0) + 1);
        }
    });

    return [...overlap.values()].filter(count => count > 1).length;
}

14. 평향

function solution(dots) {
    // 기울기
    const getSlope = ([x1, y1], [x2, y2]) => (y2 - y1) / (x2 - x1);

    return (
        getSlope(dots[0], dots[1]) === getSlope(dots[2], dots[3]) ||
        getSlope(dots[0], dots[2]) === getSlope(dots[1], dots[3]) ||
        getSlope(dots[0], dots[3]) === getSlope(dots[1], dots[2])
    ) ? 1 : 0;
}

15. 옹알이 (1)

function solution(babbling) {
    const words = ["aya", "ye", "woo", "ma"];
    
    return babbling.filter(b => {
        let temp = b;
        for (const w of words) {
            temp = temp.replace(w, " ");
        }
        return temp.trim() === "";
    }).length;
}

 

입문 문제인데도 내가 스스로 푼 문제가 거의 없다... 많이 참고했는데도 어렵다 !!

그래도 머쓱이는 획득 ~ 🌟

728x90
반응형

'LG 유플러스 유레카 SW > 과제' 카테고리의 다른 글

[과제] JS 프로그래머스 Lv.2 4문제 (25.02.21-22)  (0) 2025.02.23
[과제] JS 프로그래머스 Lv.2 3문제 (25.02.20)  (0) 2025.02.20
[과제] JS 프로그래머스 입문 20문제 (25.02.18)  (0) 2025.02.18
[과제] JS 프로그래머스 입문 20문제 (25.02.17)  (0) 2025.02.17
[과제] JS 프로그래머스 입문 40문제 中 25문제🥲 (25.02.14-15)  (0) 2025.02.17
'LG 유플러스 유레카 SW/과제' 카테고리의 다른 글
  • [과제] JS 프로그래머스 Lv.2 4문제 (25.02.21-22)
  • [과제] JS 프로그래머스 Lv.2 3문제 (25.02.20)
  • [과제] JS 프로그래머스 입문 20문제 (25.02.18)
  • [과제] JS 프로그래머스 입문 20문제 (25.02.17)
nueos
nueos
  • nueos
    nueos 공부 기록
    nueos
  • 전체
    오늘
    어제
    • 분류 전체보기 (191)
      • 해커톤 (1)
      • 네이버 BoostCamp (6)
      • LG 유플러스 유레카 SW (3)
        • React (21)
        • TypeScript (2)
        • JavaScript (2)
        • HTML+CSS (5)
        • Spring (7)
        • Java (6)
        • SQL (2)
        • Algorithm (8)
        • CX (6)
        • Git (2)
        • 프로젝트 (2)
        • 스터디 (9)
        • 과제 (8)
        • 특강 (1)
      • React (3)
      • Next (0)
      • Javascript (2)
      • HTML (2)
      • CSS (9)
      • Algorithm (6)
      • Database (0)
      • OS (13)
      • C++ (24)
      • Python (1)
      • jQuery (1)
      • Django (1)
      • Git (1)
      • 개발 지식 (3)
      • 정보 보안 (22)
      • 포렌식 (1)
      • 암호 (2)
      • 기타 (4)
      • 패스트캠퍼스 FE 프로젝트십 (5)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    제주지역혁신플랫폼지능형서비스사업단
    기술로바꾸는세상
    큐
    Queue
    Stack
    힙
    exhaustive search
    제주해커톤
    디지털혁신
    heap
    디지랩챌린지
    완전 탐색
    스택
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
nueos
[과제] JS 프로그래머스 입문 15문제 & 머쓱이 획득 (25.02.19)
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.