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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

class Solution {
    fun solution(array: IntArray): Int = array
            .groupBy{it}
            .map{it.value.size to it.key}
            .sortedByDescending { it.first }
            .let {
                if(it.size > 1 && it[0].first == it[1].first) -1 else it.first().second
            }
}

 

첫 번째 입출력 예를 통해 코드의 출력값을 흐름에 따라 알아보자. [1, 2, 3, 3, 3, 4]

 

우선 array를 가져와서 groupBy{ it } 으로 묶어준다.

 

groupBy 함수는 Map<K, List<V>> 형태의 결과를 반환한다.

즉, 키와 키에 해당하는 요소들을 리스트로 묶은 맵을 반환한다.

 

여기서는 it 자체로 키의 형태로 묶었기에 1,2,3,4를 키 형태로 가지고 그 키에 해당하는 원소들을 리스트에 넣는다.

{1=[1], 2=[2], 3=[3, 3, 3], 4=[4]}

 

이런 형태로 출력된다.

 

이후 .map을 통해 각 맵 컬렉션에 접근을 하고 우리는 지금 가장 많이 나온 value의 크기값을 알고 싶은 것이기에

it.value.size와 it.key를 to 를 통해 Pairing 시켜준다.

 

여기서 it.value.size 는 3을 예로 들자면 value인 3의 갯수이다. 그리고 key는 3이 될 것이다.

[(1, 1), (1, 2), (3, 3), (1, 4)]

 

이런 형태로 출력된다.

 

마찬가지로 우리는 가장 많이 나온 값에 관심이 있기에 it.value.size의 크기를 내림차순으로 해주기 위해 

.sortedByDescending { it.first } 을 이용한다. 여기서 it.first는 방금 전 pair로 묶어준 value.size다.

[(3, 3), (1, 1), (1, 2), (1, 4)]

 

이런 형태로 출력된다.

 

.let {
                 if(it.size > 1 && it[0].first == it[1].first) -1 else it.first().second
            }

 

이후 배열의 크기가 1 이상이면서 배열 0번째와 1번째의 first 즉 최빈값이 같다면 -1 을 내보내고 그 외에는 첫번째 배열의 second 즉 키 값을 내보낸다.

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

class Solution {
    fun solution(park: Array<String>, routes: Array<String>): IntArray {
        var answer: IntArray = intArrayOf(0,0)
        var command = HashMap<String, IntArray>()
        
        command.put("E", intArrayOf(0,1))
        command.put("W", intArrayOf(0,-1))
        command.put("S", intArrayOf(1,0))
        command.put("N", intArrayOf(-1,0))
        
        for (i in 0 .. park.size-1) {
            for (j in 0 .. park[i].length-1) {
                if (park[i][j] == 'S') {
                    answer = intArrayOf(i,j)
                }
            }
        }
        
        routes.forEach {
            var direction = command[it.split(" ")[0]]
            var count = it.split(" ")[1].toInt()
            var row = answer[0]
            var column = answer[1]
            
            for (i in 1..count) {
                row += direction!![0]
                column += direction!![1]
                if(row < 0 || column < 0 || row >= park.size || column >= park[0].length || park[row][column] == 'X') {
                    row = answer[0]
                    column = answer[1]
                    break
                }
            }
            answer[0] = row
            answer[1] = column
        }
        return answer
    }
}

 

 

fun solution(park: Array<String>, routes: Array<String>): IntArray {
        var currY = 0
        var currX = 0
        val moveY = mapOf('N' to -1, 'S' to 1, 'W' to 0, 'E' to 0)
        val moveX = mapOf('N' to 0, 'S' to 0, 'W' to -1, 'E' to 1)

        for (i in park.indices) {
            for (j in park[i].indices) {
                if (park[i][j] == 'S') {
                    currY = i
                    currX = j
                }
            }
        }

        for (route in routes) {
            val direction = route[0]
            val step = route.substring(2).toInt()
            var maxStep = step

            for (i in 1..step) {
                val newY = currY + moveY[direction]!! * i
                val newX = currX + moveX[direction]!! * i

                if (newY < 0 || newX < 0 ||newY >= park.size || newX >= park[0].length || park[newY][newX] == 'X') {
                    maxStep = 0
                    break
                }
            }

            currY += moveY[direction]!! * maxStep
            currX += moveX[direction]!! * maxStep
        }

        return intArrayOf(currY, currX)
    }

 

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

 

class Solution {
    fun solution(players: Array<String>, callings: Array<String>): Array<String> {
        val rankMap = mutableMapOf<String, Int>()
        
        players.forEachIndexed { index, player ->
            rankMap[player] = index
        }
        
        callings.forEachIndexed { index, player ->
            val calledPlayerRank = rankMap[player] ?: 0
            val frontPlayer = players[calledPlayerRank - 1]
            
            players[calledPlayerRank -1 ] = player
            players[calledPlayerRank] = frontPlayer
            
            rankMap[player] = calledPlayerRank - 1
            rankMap[frontPlayer] = calledPlayerRank
        }
        return players
    }
}

 

rankMap에 {mumu=0, soe=1, poe=2, kai=3, mine=4} 이런 형식으로 플레이어와 그 인덱스 값을 저장해준다. 

 

이후 calling된 선수의 랭크를 통해 players안에 인덱스 값을 앞선수와 바꿔준다.

 

그리고 rankMap의 값도 변경시켜준다.

 

처음 temp에 서로 인덱스값을 바꿔주는 작업으로 접근했는데 시간 초과가 걸려 hashMap을 통해 검색 시간을 단축시켜서 해결하였다.

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

class Solution {
     fun solution(today: String, terms: Array<String>, privacies: Array<String>): IntArray {
        val answer = mutableListOf<Int>()
        val term = mutableMapOf<String, Int>()
        val todayInt = today.replace(".", "").toInt()

        terms.map {
            val (type, date) = it.split(" ")
            term[type] = date.toInt()
        }

        privacies.mapIndexed { i, it ->
            val (date, type) = it.split(" ")
            var year = term[type]!! / 12
            if (year < 1)
                year = 0

            val month = term[type]!! % 12
            val expiredDate = (date.replace(".", "").toInt() + year * 10000 + month * 100).toString()

            var temp = expiredDate.toInt()
            if (expiredDate[4].toString().toInt() * 10 + expiredDate[5].toString().toInt() > 12) {
                temp -= 1200
                temp += 10000
            }

            if (temp <= todayInt) {
                answer.add(i + 1)
            }
        }
        return answer.toIntArray()
    }
}

 

today 날짜를 점을 뺀 Int형식으로 날짜를 저장한다.

term 에 terms의 타입과 개월 수를 Map 형식으로 { A=6, B=12, C=3 } 이런식으로 저장한다.

 

이 후 유효기간의 소멸날짜를 구하기 위해 연수와 개월 수를 구하여 expiredDate에 저장한다.

월 수가 12를 초과했을 경우에 올림 계산을 위해 temp를 통해 연산을 해주고 temp와 오늘 날짜를 비교하여 오늘 날짜가 더 크다면 answer에 담아준다.

 

 

 

 

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

class Solution {
    fun solution(wallpaper: Array<String>): IntArray {
        var hashIndex = ArrayList<IntArray>()
        
        wallpaper.forEachIndexed { index, i ->
            i.forEachIndexed { index2, j ->
                if ( j == '#') {
                    hashIndex.add(intArrayOf(index, index2))
                }
            }
        }
        var minX = hashIndex.minOf{it[0]}
        var minY = hashIndex.minOf{it[1]}
        var maxX = hashIndex.maxOf{it[0]} + 1
        var maxY = hashIndex.maxOf{it[1]} + 1
        
        return intArrayOf(minX, minY, maxX, maxY)
    }
}

 

모든 #의 인덱스를 배열리스트에 넣어주고 X,Y좌표에서 최솟값과 최대값을 뽑아주면 되는 문제였다.

 

이중for문이어서 조금 걱정했으나 테스트케이스의 길이가 얼마 되지 않아 시간도 짧게 나왔다.

 

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

class Solution {
    fun solution(survey: Array<String>, choices: IntArray): String {
        var answer: String = ""
        
        var person: CharArray = charArrayOf('R', 'T', 'C', 'F', 'J', 'M', 'A', 'N')
        var score: IntArray = IntArray(8) { 0 }

        for (i in survey.indices) {
            score[person.indexOf(survey[i][1])] += choices[i] - 4
        }

        for (i in 0..7 step 2) {
            if (score[i] >= score[i + 1]) answer += person[i]
            else answer += person[i + 1]
        }
        return answer
    }
}

 

나와 같은 방식으로 푸신 분의 깔끔한 코드를 가져와봤다.

분석을 하면서 공부하고 내 것으로 만들어야겠다.

 

우선 동점일 경우 알파벳순으로 리턴해주기에 알파벳순으로 charArray에 담아주고 그 크기에 따른 정수 배열도 만들어준다.

 

그리고 어차피 choices의 숫자를 통해 알파벳들의 숫자 비교를 위한 것이므로 점수에 4를 빼주고 값을 score에 넣어준다.

'CF"일 때 choices가 3이었다면 F를 가져와서 -1을 넣어주면 사실상 C가 1득점한 것과 같은 효과이다.

 

이후 for문으로 score값들을 step2로 2씩 띄어서 값들을 비교해주고 동점이거나 높으면 우선순위가 높은 알파벳을 리턴해주고 반대는 뒤에 알파벳을 리턴한다.

 

 

맵 컬렉션을 좀 더 공부하고 맵을 이용해서 풀어 봐야겠다.

+ Recent posts