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
44 changes: 44 additions & 0 deletions WEEK03/프로그래머스_방금그곡/Liv.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// 프로그래머스 - 방금그곡

func solution(_ m: String, _ musicinfos: [String]) -> String {
var selected: (String, Int) = ("(None)", 0)
let heard = convertSheet(m)

for music in musicinfos {
let info = music.split(separator: ",").map { String($0) }
guard info.count == 4 else { continue }

let duration = toNumber(info[1]) - toNumber(info[0])
let sheet = convertSheet(info[3])
guard !sheet.isEmpty, duration > 0 else { continue }

let repeatCount = duration / sheet.count + 1
let played = String((String(repeating: sheet, count: repeatCount)).prefix(duration))
Comment on lines +15 to +16

Choose a reason for hiding this comment

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

high

재생 시간(duration) 만큼의 전체 멜로디를 생성하는 현재 방식은 매우 비효율적일 수 있습니다. String(repeating:count:)으로 악보를 duration / sheet.count + 1 만큼 반복하여 매우 긴 중간 문자열을 생성한 후, prefix(duration)으로 잘라내고 있습니다. 예를 들어, 재생 시간이 1400분이고 악보 길이가 2라면, 약 1400 * 701 = 981400 길이의 문자열을 생성하게 됩니다. 이는 불필요한 메모리 할당과 연산을 유발합니다. 필요한 길이만큼만 멜로디를 생성하는 것이 훨씬 효율적입니다.

Suggested change
let repeatCount = duration / sheet.count + 1
let played = String((String(repeating: sheet, count: repeatCount)).prefix(duration))
let sheetChars = Array(sheet)
let played = String((0..<duration).map { sheetChars[$0 % sheetChars.count] })


if played.contains(heard) && duration > selected.1 {
selected = (info[2], duration)
}
}

return selected.0
}

func toNumber(_ str: String) -> Int {
let sections = str.split(separator: ":").map { String($0) }
guard sections.count == 2,
let min = Int(sections[0]),
let sec = Int(sections[1])
else { return 0 }
return min * 60 + sec
}
Comment on lines +26 to +33

Choose a reason for hiding this comment

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

critical

toNumber 함수가 "HH:MM" 형식의 시간을 "분:초"로 잘못 파싱하고 있습니다. 문제의 요구사항에 따르면 시간은 "시:분" 형식이므로, Int(sections[0])은 시(hour), Int(sections[1])은 분(minute)이 되어야 합니다. 현재 구현은 min * 60 + sec으로 총 초를 계산하는 것처럼 보이지만, 실제로는 시 * 60 + 분으로 총 분을 계산해야 합니다. 또한, 변수명 min, sec이 혼동을 줄 수 있으니 hour, minute 등으로 변경하는 것이 좋겠습니다. 이 버그는 음악의 재생 시간을 잘못 계산하게 만들어 오답을 유발할 수 있습니다.

Suggested change
func toNumber(_ str: String) -> Int {
let sections = str.split(separator: ":").map { String($0) }
guard sections.count == 2,
let min = Int(sections[0]),
let sec = Int(sections[1])
else { return 0 }
return min * 60 + sec
}
func toNumber(_ str: String) -> Int {
let sections = str.split(separator: ":").map { String($0) }
guard sections.count == 2,
let hour = Int(sections[0]),
let minute = Int(sections[1])
else { return 0 }
return hour * 60 + minute
}


func convertSheet(_ str: String) -> String {
var sheet: String = str
while let point = sheet.firstIndex(of: "#") {
let target = sheet.index(before: point)
let note = sheet[target].lowercased()
sheet.removeSubrange(target...point)
sheet.insert(contentsOf: note, at: target)
}
return sheet
}
Comment on lines +35 to +44

Choose a reason for hiding this comment

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

medium

convertSheet 함수에서 while 루프를 사용하여 '#'이 포함된 음을 변환하는 방식은 문자열이 길고 '#'이 많을 경우 비효율적일 수 있습니다. 루프마다 firstIndex(of:)로 문자열을 탐색하고 removeSubrangeinsert로 문자열을 수정하는 과정은 많은 비용을 발생시킬 수 있습니다. 문제에서 변환해야 할 음표('#'이 붙는 음표)는 C#, D#, F#, G#, A#로 정해져 있으므로, replacingOccurrences(of:with:) 메소드를 연달아 사용하면 코드가 더 간결해지고 성능도 향상될 수 있습니다.

func convertSheet(_ str: String) -> String {
    return str
        .replacingOccurrences(of: "C#", with: "c")
        .replacingOccurrences(of: "D#", with: "d")
        .replacingOccurrences(of: "F#", with: "f")
        .replacingOccurrences(of: "G#", with: "g")
        .replacingOccurrences(of: "A#", with: "a")
}