Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions WEEK03/프로그래머스_[1차] 뉴스 클러스터링/JSON.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
func solution(_ str1:String, _ str2:String) -> Int {
var result = 65536
let (lhs, rhs) = (parse(str1), parse(str2))

let intersection = getIntersection(lhs, rhs)
let union = lhs.values.reduce(0, +) + rhs.values.reduce(0, +) - intersection

guard union != 0 else { return 65536 }

result = Int(Double(intersection) / Double(union) * 65536)

return result
Comment on lines +10 to +12

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

result 변수에 값을 할당한 후 바로 반환하는 대신, 계산된 값을 직접 반환하여 코드를 간결하게 만들 수 있습니다. 이 변경으로 인해 2행의 var result = 65536 선언이 불필요해지므로 함께 제거하는 것이 좋습니다. Swift에서는 불필요한 가변 상태를 줄이는 것이 권장됩니다.

Suggested change
result = Int(Double(intersection) / Double(union) * 65536)
return result
return Int(Double(intersection) / Double(union) * 65536)

}

func getIntersection(_ lhs: [String: Int], _ rhs: [String: Int]) -> Int {
var result = 0

for word in lhs.keys {
result += min(lhs[word, default: 0], rhs[word, default: 0])
}

return result
Comment on lines +16 to +22

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

for 루프를 사용하여 합계를 계산하는 대신 reduce 고차 함수를 사용하면 코드를 더 간결하고 함수형 프로그래밍 스타일에 가깝게 작성할 수 있습니다.

    return lhs.keys.reduce(0) { result, word in
        result + min(lhs[word, default: 0], rhs[word, default: 0])
    }

}

func parse(_ str: String) -> [String: Int] {
var result = [String: Int]()
let arr = Array(str)

for i in 0..<str.count - 1 {
guard arr[i].isLetter && arr[i + 1].isLetter else { continue }

let word = String(arr[i]) + String(arr[i + 1])
result[word.lowercased(), default: 0] += 1
}

return result
Comment on lines +26 to +36

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

parse 함수 내에서 루프가 반복될 때마다 lowercased()가 호출되고 있습니다. 입력 문자열을 루프 시작 전에 한 번만 소문자로 변환하면 성능을 개선할 수 있습니다. 또한, 두 문자를 합쳐 문자열을 만들 때 String의 이니셜라이저에 배열 슬라이스를 전달하는 것이 문자열 덧셈보다 약간 더 효율적입니다.

    var result = [String: Int]()
    let arr = Array(str.lowercased())

    for i in 0..<(arr.count - 1) {
        guard arr[i].isLetter && arr[i + 1].isLetter else { continue }
        
        let word = String(arr[i...i+1])
        result[word, default: 0] += 1
    }

    return result

}