Skip to content

[1차] 뉴스 클러스터링#34

Open
snughnu wants to merge 1 commit intomainfrom
oliver
Open

[1차] 뉴스 클러스터링#34
snughnu wants to merge 1 commit intomainfrom
oliver

Conversation

@snughnu
Copy link
Collaborator

@snughnu snughnu commented Feb 5, 2026

🔗 문제 링크

✔️ 소요된 시간

48m

📚 새롭게 알게된 내용

  • isLetter
  • 바로 집합 count 쓰기 아이디어

@snughnu snughnu self-assigned this Feb 5, 2026
@snughnu snughnu added the 구현 label Feb 5, 2026
@gemini-code-assist
Copy link

Summary of Changes

Hello @snughnu, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

이 PR은 프로그래머스 '뉴스 클러스터링' 문제를 해결하기 위한 Swift 코드를 추가합니다. 두 입력 문자열로부터 영문자로만 구성된 두 글자 쌍의 다중집합을 생성하고, 이들을 기반으로 자카드 유사도를 계산한 후, 문제에서 요구하는 특정 값으로 스케일링된 정수 결과를 반환합니다.

Highlights

  • 자카드 유사도 구현: jaccard 함수를 통해 두 문자열의 자카드 유사도를 계산합니다. 두 집합이 모두 비어있는 경우 유사도를 1.0으로 처리하는 예외 로직이 포함되어 있습니다.
  • 다중집합 생성 로직: makeSet 함수를 사용하여 입력 문자열에서 두 글자씩 짝지어 다중집합(multiset)을 생성합니다. 이때, 영문자로만 구성된 쌍만 포함하고 모든 문자를 소문자로 변환합니다.
  • 최종 결과 스케일링: 계산된 자카드 유사도에 65536을 곱하여 정수형으로 반환하는 solution 함수가 구현되었습니다.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • WEEK03/프로그래머스_[1차] 뉴스 클러스터링/Oliver.swift
    • '뉴스 클러스터링' 문제 해결을 위한 Swift 코드 파일이 새로 추가되었습니다.
    • solution, jaccard, makeSet 세 가지 핵심 함수가 포함되어 있습니다.
    • makeSet 함수는 입력 문자열을 소문자로 변환하고, 영문자로만 구성된 두 글자 쌍을 추출하여 다중집합을 생성합니다.
    • jaccard 함수는 두 다중집합의 교집합과 합집합을 계산하여 자카드 유사도를 반환하며, 두 집합이 모두 비어있을 경우 1.0을 반환하는 예외 처리가 포함되어 있습니다.
    • solution 함수는 jaccard 함수를 호출하여 얻은 유사도에 65536을 곱한 정수 값을 최종 결과로 반환합니다.
Activity
  • snughnu님이 프로그래머스 '뉴스 클러스터링' 문제 해결을 위한 Swift 코드를 추가했습니다.
  • 문제 해결에 48분이 소요되었습니다.
  • isLetter 사용법과 집합의 count를 직접 활용하는 아이디어를 새롭게 알게 되었다고 언급했습니다.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This PR adds Swift code to solve the news clustering problem. A potential Denial of Service (DoS) vulnerability was identified in the makeSet function, where an empty input string leads to a runtime crash due to an invalid range construction. Beyond this, while the Jaccard similarity calculation logic is correctly implemented, there's room for performance improvement in calculating multiset intersection and union. The current approach using array's firstIndex(of:) and remove(at:) can be inefficient for large inputs; using a dictionary to manage bigram counts would offer a more efficient O(N+M) time complexity.

Comment on lines +7 to +25
func jaccard(_ s1: String, _ s2: String) -> Double {
let set1 = makeSet(s1)
var set2 = makeSet(s2)

if set1.isEmpty && set2.isEmpty { return 1.0 }

var intersection: [String] = []
var unionCount: Int = 0

for element in set1 {
if let idx = set2.firstIndex(of: element) {
intersection.append(element)
set2.remove(at: idx)
}
}

unionCount = set1.count + set2.count
return Double(intersection.count) / Double(unionCount)
}

Choose a reason for hiding this comment

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

high

jaccard 함수에서 교집합과 합집합을 계산하는 현재 방식은 배열에 대해 firstIndex(of:)remove(at:)를 반복적으로 사용합니다. 이 배열 연산은 최악의 경우 O(N*M)의 시간 복잡도를 가질 수 있어, 입력 크기가 커질수록 성능 저하가 발생할 수 있습니다.
makeSet 함수에서 반환하는 딕셔너리(다중집합)를 활용하면, 교집합과 합집합을 O(N+M) 시간 복잡도로 효율적으로 계산할 수 있습니다. 제안된 코드는 다중집합의 합집합 공식인 |A ∪ B| = |A| + |B| - |A ∩ B|를 사용합니다.

func jaccard(_ s1: String, _ s2: String) -> Double {
    let multiset1 = makeSet(s1)
    let multiset2 = makeSet(s2)

    if multiset1.isEmpty && multiset2.isEmpty { return 1.0 }

    var intersectionCount = 0

    // 교집합 계산
    for (bigram, count1) in multiset1 {
        if let count2 = multiset2[bigram] {
            intersectionCount += min(count1, count2)
        }
    }

    // 합집합 계산: |A U B| = |A| + |B| - |A intersect B|
    let sumOfCounts1 = multiset1.values.reduce(0, +)
    let sumOfCounts2 = multiset2.values.reduce(0, +)
    let unionCount = sumOfCounts1 + sumOfCounts2 - intersectionCount

    // unionCount가 0인 경우 (두 다중집합 모두 비어있거나, 교집합이 전체를 상쇄하는 경우 등)
    if unionCount == 0 { return 1.0 }

    return Double(intersectionCount) / Double(unionCount)
}

let chars = Array(string.lowercased())
var result: [String] = []

for i in 0..<chars.count-1 {

Choose a reason for hiding this comment

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

security-medium medium

The makeSet function has a potential Denial of Service (DoS) vulnerability. If an empty string is passed, the range 0..<chars.count-1 becomes 0..<-1, causing a runtime crash in Swift. A robust implementation should handle empty inputs to prevent this. Additionally, for better performance and clearer multiset representation, consider changing makeSet to return a dictionary [String: Int] to store bigram counts, which would also improve the efficiency of jaccard function calculations.

Suggested change
for i in 0..<chars.count-1 {
for i in 0..<max(0, chars.count - 1) {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant