Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Algorithm] 할인 행사 #24

Closed
hwangJi-dev opened this issue Oct 11, 2022 · 0 comments
Closed

[Algorithm] 할인 행사 #24

hwangJi-dev opened this issue Oct 11, 2022 · 0 comments

Comments

@hwangJi-dev
Copy link
Owner

hwangJi-dev commented Oct 11, 2022

💬 문제

[코딩테스트 연습 - 할인 행사](https://school.programmers.co.kr/learn/courses/30/lessons/131127)


💬 Idea

  • 원하는 품목과 개수를 dictionary로 짝지어준다.

  • 회원등록 날짜로부터 10일동안 할인되는 품목들 중 자신이 원하는 품목을 비교해야하므로 discount 배열의 총 길이에서 10을 뺀 개수동안 for문을 돌며 10 크기의 배열을 만들어 품목들을 비교한다.

  • 품목의 종류가 일치하는 배열을 찾은 경우 할인 기간동안 세일하는 품목의 개수보다 원하는 품목의 개수가 더 많을 때는 할인을 받을 수 없기 때문에 이 경우에는 할인 일자에서 제외한다.

  • 원하는 제품을 모두 할인 받을 수 있는 회원등록 날짜의 총 일수를 리턴한다.

  • 예외 케이스 할인 상품에 원하는 품목이 없는 경우 빠르게 0을 리턴해준다.


💬 풀이

func solution(_ want:[String], _ number:[Int], _ discount:[String]) -> Int {
    
    var wantDict: [String: Int] = [:]
    let discount = discount
    
    for i in 0..<want.count {
        wantDict[want[i]] = number[i]
    }
    
    // 할인 상품에 원하는 상품이 없는 경우
    for i in want {
        if discount.contains(i) == false {
            return 0
        }
    }
    
    var discountDay = 0
    
    for i in 0...discount.count - 10 {
        var discountArray: [String] = []
        var discountDict: [String: Int] = [:]
        
        for j in i..<i+10 {
            discountArray.append(discount[j])
            discountDict[discount[j]] = discountDict[discount[j]] != nil ? discountDict[discount[j]]! + 1 : 1
        }
        
        var validateArray: [Bool] = []
        for want in want {
            validateArray.append(discountArray.contains(want) ? true : false)
        }
        
        if !validateArray.contains(false) {
            var isCorrect: [Bool] = []
            
						// 원하는 품목의 개수가 더 많을 때는 할인을 받을 수 없으므로 이 경우를 계산해준다.
            for k in wantDict {
                isCorrect.append(k.value > discountDict[k.key] ?? 0 ? false : true)
            }
            
            if !isCorrect.contains(false) {
                discountDay += 1
            }
        }
    }
    
    return discountDay
}

💬 알게된 문법

allSatisfy()

  • 콜렉션의 모든 원소가 특정 조건을 만족시키는지 확인하고 싶을 때 사용

    let numbers = [28, 32, 64, 90]
    let passed = numbers.allSatisfy { $0 >= 28 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant