ν”„λ‘œκ·Έλž˜λ°/μ•Œκ³ λ¦¬μ¦˜ 풀이 Swift

[λ°±μ€€ 2822] 점수 계산 (Swift)

λΉ„λΉ„ bibi 2022. 9. 22. 12:40

2822번: 점수 계산

  • μ£Όμ–΄μ§„ 점수 μ€‘μ—μ„œ κ°€μž₯ 높은 점수 5개의 ν•©κ³Ό, κ·Έ 5개의 인덱슀λ₯Ό κ΅¬ν•˜λŠ” 문제
  • 반볡문으둜 ν•΄κ²°ν–ˆλ‹€.
  • κ°€μž₯ 높은 μ μˆ˜λŠ” max() λ₯Ό ν™œμš©ν–ˆλ‹€.
    • λ‹€λ₯Έ 채점결과λ₯Ό λ³΄λ‹ˆ μ²˜μŒλΆ€ν„° μž…λ ₯된 점수 배열을 λ‚΄λ¦Όμ°¨μˆœμœΌλ‘œ μ •λ ¬ν•œ λ’€ μ•ž5개λ₯Ό 뽑아 κ³„μ‚°ν•˜λŠ” 방법도 μžˆμ—ˆλ‹€. 그게 더 μ μˆ˜κ°€ λ†’κ²Œ λ‚˜μ™”λ‹€πŸ€” 이 방법도 μƒκ°ν•˜κΈ΄ ν–ˆμ§€λ§Œ 인덱슀 μ²˜λ¦¬κ°€ μ–΄λ €μšΈ 것 κ°™μ•˜λŠ”λ°, λ‹€λ₯Έ μ‚¬λžŒλ“€μ€ (인덱슀, 점수) νŠœν”Œμ„ λ§Œλ“€μ–΄ ν™œμš©ν•˜λ”λΌ!

풀이1 : max() ν™œμš©

var scoreArr: [Int] = []
var sum = 0
var sumArr: [Int] = []
(1...8).forEach { _ in
    scoreArr.append(Int(readLine()!)!)
}
(1...5).forEach { _ in
    let max = scoreArr.max()!
    let maxIndex = scoreArr.firstIndex(of: max)!
    sum += max
    sumArr.append(maxIndex)
    scoreArr[maxIndex] = 0
}
sumArr.sort()
print(sum)
sumArr.indices.forEach { index in
    print(sumArr[index] + 1, terminator: " ")
}

풀이2 : sort(by:) ν™œμš©

var scoreArr: [(score: Int, index: Int)] = []
var sum = 0
var sumArr: [Int] = []
(1...8).forEach { i in
    scoreArr.append((score: Int(readLine()!)!, index: i))
}
scoreArr.sort { before, after in
    before.score > after.score // λ°©ν–₯이 μ€‘μš”..
}
(0..<5).forEach { i in
    sum += scoreArr[i].score
    sumArr.append(scoreArr[i].index)
}
sumArr.sort()
print(sum)
sumArr.indices.forEach { index in
    print(sumArr[index], terminator: " ")
}