본문 바로가기
[Developer]/ProblemSolving

[CodeSignal] alternatingSums

by 해피빈이 2019. 8. 17.

이번 문제는 쉬워서 올리지 않을까 했지만, 그냥 올리기로.

 

바로 풀었는데, 시간이 좀 이상하게 나온다. 아마도 활성화 시키고 난 뒤부터 카운트 한듯

 

문제

Several people are standing in a row and need to be divided into two teams. The first person goes into team 1, the second goes into team 2, the third goes into team 1 again, the fourth into team 2, and so on.

You are given an array of positive integers - the weights of the people. Return an array of two integers, where the first element is the total weight of team 1, and the second element is the total weight of team 2 after the division is complete.

문제는 간단하다. 몇몇의 사람들이 있는데, 두개의 팀으로 나누고 줄을 세운다. 배열이 하나 주어지는데, 아직 두 팀으로 나누기 전의 각 사람들 목록이다. 각 사람의 몸무게가 기록되어 있다.

간한디, 첫번째 사람은 첫번째 팀으로, 두번째 사람은 두번째 팀으로 간다. 그리고 세번째는 다시 첫번째 팀으로, 네번째는 두번째 팀으로,... 이렇게 하다보면 2개의 팀으로 나뉘게 되는데, 각 팀에 있는 사람들의 몸무게를 합산하여

배열 하나로 하여 첫번째 팀 몸무게 합산결과와 두번째 팀 몸무게의 합산결과를 놓고 리턴하는 문제이다.

 

 

주어진 테스트

1

Input: a: [50, 60, 60, 45, 70]

Expected Output: [180, 105]

2

Input: a: [100, 50]

Expected Output: [100, 50]

3

Input: a: [80]

Expected Output: [80, 0]

4

Input: a: [100, 50, 50, 100]

Expected Output: [150, 150]

5

Input: a: [100, 51, 50, 100]

Expected Output: [150, 151]

 

 

 

나의 해답

풀이는 간단하게 되었다. 사실 홀수팀, 짝수팀 문제이며, 심지어는 합산만 하면 되지, 각 element를 관리할 필요도 없다.

그래서 나머지 연산으로 2를 하여 홀수와 짝수를 가려내고, 홀수팀과 짝수팀의 수를 각각 합산하고, 그 결과를 MutableList로 리턴하면 끝이다. 예상했던대로 결과는 문제가 없었으며, 문제는 바로 해결되었다.

 

fun alternatingSums(a: MutableList<Int>): MutableList<Int> {
    val resultSums = mutableListOf<Int>()
    var firstTeamWeight = 0; var secondTeamWeight = 0
    
    for ((idx, personWeight) in a.withIndex()) {
        if(idx % 2 == 0) {
            firstTeamWeight += personWeight
        } else {
            secondTeamWeight += personWeight
        }
    }
    
    resultSums.apply {
        add(firstTeamWeight)
        add(secondTeamWeight)
    }
    
    return resultSums
}

 

코드를 더 줄일까도 싶었는데, 무슨 의미가 있나 싶어서 그대로 두었다.

시간복잡도는 O(n)이다.

 

마지막에 apply를 써서 조금 더 코드를 보기 편하게 만들었다.

사실 apply는 property로 되어있는 것을 사용하면 좀 의미가 있겠지만.. 그냥 사용하는데 의의를 두는 것으로...

어쨌든 List 내부의 값을 할당하는데 사용은 했다.

반응형

'[Developer] > ProblemSolving' 카테고리의 다른 글

[CodeSignal] Add Border  (0) 2019.08.17
[CodeSignal] reverseInParentheses  (0) 2019.08.16

댓글