[프로그래머스 고득점 Kit] 위장

김가희·2023년 3월 25일
0

PS

목록 보기
4/4

[Hash 4일차] 위장

⬇️ 나의 코드 v1 ⬇️(Kotlin)

class Solution {
    fun solution(clothes: Array<Array<String>>): Int {
        var m = mutableMapOf<String, Int>()
        clothes.forEach { it -> m.put(it[1], m.getOrDefault(it[1], 0) + 1) }
        
        var answer = 1
        m.values.forEach { it -> answer *= (it + 1) }
        
        return answer - 1
    }
}

⬇️ 나의 코드 v1 ⬇️(Java)

import java.util.*;

class Solution {
    public int solution(String[][] clothes) {
        int answer = 1;
        HashMap<String, Integer> m = new HashMap<String, Integer>();
        
        for(String[] it : clothes) {
            m.put(it[1], m.getOrDefault(it[1], 0) + 1);
        }
        
        for(int it : m.values()) {
            answer *= (it + 1);
        }
        
        return answer - 1;
    }
}

풀이 방식은 <옷의 종류, 개수> 로 map 을 만든 뒤 그 개수를 모두 곱한다. 이때 입지 않는다 라는 선택지도 있기 때문에 +1 을 한 상태로 곱한다. 이러면 아무것도 입지 않는 경우가 되기 때문에 마지막에 -1을 한다.

👀 다른 사람의 코드를 보고 배운점

class Solution {
    fun solution(clothes: Array<Array<String>>): Int {
        return clothes.groupBy { it[1] }.values.fold(1) { acc, v -> acc * (v.size + 1) }  - 1
    }
}

class Solution {
    fun solution(clothes: Array<Array<String>>) = clothes
        .groupBy { it[1] }.values   // group by type of clothes, keep only names of clothes
        .map { it.size + 1 }        // number of things to wear in a group (including wearing nothing)
        .reduce(Int::times)         // combine
        .minus(1)                   // remove the case where the spy wears nothing
}
  1. groupBy{ 기준 }을 사용하면 list를 map 형식으로 <기준, valueList>를 생성해준다.
var arr = listOf("One", "Two", "Three", "Four", "Five")
arr.groupBy { it.first().toUpperCase() } 

라고 사용했을 때
결과는 'O' -> ["One"], 'T' -> ["Two", "Three"], 'F' -> ["Four", "Five"]가 된다.

  1. reduce()fold()

둘 다 accumulate 를 위한 메소드이다.

accumulate란 컬렉션에 있는 모든 데이터를 순회하면서 축적(accumulate)하기 위한 함수이다. 물론 꼭 더하기가 아니여도 되는것 같다.

하지만 reduce()의 경우 초기값 없이 첫번째 원소부터 사용하고 fold()는 초기값이 있는 상태로 시작한다. 그렇다는건 reduce()는 빈 배열에서는 에러가 날 수 있다는점!

참고로 자바 stream 에서도 사용이 가능하다.

profile
안드로이드 개발자

0개의 댓글