본문 바로가기
알고리즘

[JS] 코딩테스트

by 측면삼각근 2020. 3. 17.
728x90
반응형

이력서를 쓰기 시작한지 조금 되다보니 면접을 (조금씩) 보고다니고 있는데,
몇번 안되는 코딩테스트 경험상는 집에서 편안히 알고리즘을 푸는 것 보다 정말 5~6배쯤 헤메는것같다.
또.. 헤메기 시작하면 당황해서 더 헤메는 것 같다.

물론.. 내가 한동안 알고리즘에 너-무 소홀해서 .. 그런탓이 크긴하다..반성..

아래는 몇일전에 실제로 코딩테스트로 받았던 것인데, 일단.. 문제가 영어여서 1차로 당황했고..
해석이 안되서 2차 당황했고..(동사가 없는 문장이라니..)
당황하니까 풀이법이 전혀 생각이 안나서 3차 당황했다..
제한시간이 40분이었는데, 적어도 10분은 뇌정지가 와서 거의 풀지 못하고 결국에는 시간초과로 한문제는 풀지는 못했다..시간이 없어서 풀다가 수도코드만 적어 내었다..8_8
메일로 사정을 해서 추가 제출을 하긴했지만, 아마도 연락이 없는것을 보면 불합격이 아닐까 ^^;
면접때도 좀 분수에 안맞게 거만한 발언을 한 느낌도있고.. (앗차) 실수했다 싶은 발언도 있기도 하고..! T.T

아무튼..!
짧은 시간이였지만 아마도 더 좋은 풀이법이 있을 거라고 생각되어서 문제와 나의 풀이를 올린다.
(이번주 내로 알고리즘을 고칠예정! 그럴 수 있었으면!)

1

Maximum number of chocolates to be distributed equally among k students
Given n boxes containing some chocolates arranged in a row. There are k number of students.
The problem is to distribute maximum number of chocolates equally among k students
by selecting a consecutive sequence of boxes from the given lot.
We have to select a group of boxes which are in consecutive order that could provide
An array arr[] is given representing the row arrangement of the boxes and arr[i] represents
number of chocolates in that box at position ‘i’.

Examples:
Input : arr[] = [2, 7, 6, 1, 4, 5], k = 3
Output : 6
The subarray is [7, 6, 1, 4] with sum 18.
Equal distribution of 18 chocolates among
3 students is 6.
Note that the selected boxes are in consecutive order
with indexes {1, 2, 3, 4}.

나의 답안

// 1번
// 초콜릿, 학생 숫자
// ! input : arr[] = [2, 7, 6, 1, 4, 5], k = 3
// ! output : 6 <- 최대 갯수
const divideChocolate = (chocolates, studentsNum) => {
    let max = 0; //최대값 체크
    let sum = 0;

    // * 0 번부터 차례대로 더함 [0], [0,1], [0, 1, 2] ...
    for(let i = 0; i < chocolates.length ; i++){
        // * sum 초기화
        sum = chocolates[i];

        for(let j = i+1; j < chocolates.length ; j++){
            const comparision = sum / studentsNum;
            if( Number.isInteger(comparision) && comparision > max) max = comparision;
            sum += chocolates [ j ];
        }

    }
    return max;
}

지금 보니, 위 답은 array의 마지막 Index 에는 적용되지 않을 것 같아서 수정이 필요해보인다.

2

Given an array of distinct elements. The task is to find triplets in array whose sum is zero.
Examples :
Input : arr[] = [0, -1, 2, -3, 1]
Output : 0 -1 1
2 -3 1
Input : arr[] = [1, -2, 1, 0, 5]
Output : 1 -2 1

나의 답안

// 2번
// ! Input : arr[] = [0, -1, 2, -3, 1]
// ! 콘솔로그를 찍어라 - 0 -1 1
const logTriple = (inputArr) => {
    // * 가능한 구간을 모두 돌면서 0인 조합을 모두 찾음
    const length = inputArr.length;
    for(let i = 0 ; i < length-2 ; i++){
        for(let j = i +1 ; j < length-1 ; j++){
            for (let k = j+1 ; k < length; k++){
                if( inputArr[i]+ inputArr[j]+inputArr[k]=== 0){
                    console.log(`${inputArr[i]} ${inputArr[j]} ${inputArr[k]}`);
                }
            }
        }
    }
}

시간복잡도가 너무 높은것같다.
분명 더 줄이는 방법이 있을 것 같다.

3

Given an array, find the difference between highest occurrence and least occurrence of any number in an array

Examples:
Input : arr[] = [7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5, 5]
Output : 2
Lowest occurring element (2) occurs once.
Highest occurring element (5 or 7) occurs 3 times
Input : arr[] = [1, 1, 1, 3, 3, 3]
Output : 0

// 3번 
// ! input : [7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5, 5]
// ! oupit : 2
const returnDifference = (inputArr) => {
    // * key를 숫자의 string으로 변환하여 카운팅하는 object
    const checkObj = inputArr.reduce((acc, currVal)=>{
        const key = currVal+ "";
        if(acc.hasOwnProperty(key)) acc[key]++;
        else acc[key] = 1;
        return acc;
    },{});

    // console.log(checkObj);

    const keys = Object.values(checkObj);
    const highest = Math.max.apply(null, keys);
    const least = Math.min.apply(null, keys);
    return highest - least;
}

 

반응형