Bibi's DevLog ๐Ÿค“๐ŸŽ

[๋ฐฑ์ค€ 2822] ์ ์ˆ˜ ๊ณ„์‚ฐ (Swift) ๋ณธ๋ฌธ

ํ”„๋กœ๊ทธ๋ž˜๋ฐ/์•Œ๊ณ ๋ฆฌ์ฆ˜ ํ’€์ด 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: " ")
}