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

[๋ฐฑ์ค€ 2566] ์ตœ๋Œ“๊ฐ’ (Swift) ๋ณธ๋ฌธ

ํ”„๋กœ๊ทธ๋ž˜๋ฐ/์•Œ๊ณ ๋ฆฌ์ฆ˜ ํ’€์ด Swift

[๋ฐฑ์ค€ 2566] ์ตœ๋Œ“๊ฐ’ (Swift)

๋น„๋น„ bibi 2022. 9. 15. 12:21

2566 ์ตœ๋Œ“๊ฐ’

2566๋ฒˆ: ์ตœ๋Œ“๊ฐ’

  • 81๊ฐœ์˜ ์ž์—ฐ์ˆ˜ ์ค‘ ์ตœ๋Œ“๊ฐ’์„ ์ฐพ๊ณ , ๊ทธ ์œ„์น˜๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ

ํ’€์ด

๋‚˜๋Š” ํ•œ์ค„์”ฉ ์ž…๋ ฅ์„ ๋ฐ›๊ณ  ๊ฐ ์ค„์˜ ์ตœ๋Œ“๊ฐ’์„ ๋น„๊ตํ–ˆ๊ณ , ๋ณดํ†ต์€ ์ด์ค‘for๋ฌธ์œผ๋กœ ํ‘ธ๋Š” ๊ฒƒ ๊ฐ™๋‹ค.

(1) ๊ฐ ์ค„์˜ ์ตœ๋Œ“๊ฐ’ ๋น„๊ต

var maxNum = 0
var maxIndex: (x: Int, y: Int) = (0, 0)
(0..<9).forEach { index in
    let inputArr = readLine()!.split(separator: " ").map { Int($0)! }
    let currentMax = inputArr.max()!
    if currentMax > maxNum {
        maxNum = currentMax
        maxIndex.x = index
        maxIndex.y = inputArr.firstIndex(of: currentMax)!
    }
}
print(maxNum)
print(maxIndex.x + 1, maxIndex.y + 1)

(2) ์ด์ค‘for๋ฌธ์œผ๋กœ ๋น„๊ต

var maxNum = 0
var maxIndex: (x: Int, y: Int) = (0, 0)
(0..<9).forEach { indexX in
    let inputArr = readLine()!.split(separator: " ").map { Int($0)! }
    (0..<9).forEach { indexY in
        let input = inputArr[indexY]
        if input > maxNum {
            maxNum = input
            maxIndex.x = indexX
            maxIndex.y = indexY
        }
    }
}
print(maxNum)
print(maxIndex.x + 1, maxIndex.y + 1)

Edge case

์ฒ˜์Œ ํ’€ ๋•Œ๋Š” 100%๊นŒ์ง€ ๊ฐ”๋Š”๋ฐ ํ‹€๋ ธ์Šต๋‹ˆ๋‹ค ๊ฐ€ ๋‚˜์™”๋‹ค.

์ด์ƒํ•˜๋‹ค.. ํ•ด์„œ ์š”๋ฆฌ์กฐ๋ฆฌ ๊ณ ๋ฏผํ•ด๋ณด๋‹ค๊ฐ€ ๋ชจ๋ฅด๊ฒ ์–ด์„œ ์งˆ๋ฌธ๋ž€์„ ๋ณด๋‹ˆ,

81๊ฐœ ์ž์—ฐ์ˆ˜๊ฐ€ ๋ชจ๋‘ 0์ธ ๊ฒฝ์šฐ 0 ๊ณผ 1 1 ์„ ์ถœ๋ ฅํ•ด์•ผ ํ•˜๋Š”๋ฐ, ๊ธฐ์กด ํ’€์ด๋Š” 0 ๊ณผ 0 0 ์„ ์ถœ๋ ฅํ•˜๊ณ  ์žˆ๋˜ ๊ฒƒ..

ํ•œ ๋ฒˆ๋„ if ๋น„๊ต๋ฌธ์— ๋“ค์–ด๊ฐ€์ง€ ์•Š์œผ๋ฉด maxIndex๊ฐ€ ์ง€์ •๋  ์ผ์ด ์—†์–ด ์ดˆ๊ธฐ๊ฐ’์ธ 0, 0๊ฐ€ ์ถœ๋ ฅ๋˜๋˜ ๊ฒƒ์ด์—ˆ๋‹ค.

๊ธฐ์กด ํ’€์ด (ํ‹€๋ ธ์Šต๋‹ˆ๋‹ค)

// edge case๋ฅผ ํ†ต๊ณผํ•˜์ง€ ๋ชปํ•˜๋Š” ํ’€์ด.
var maxNum = 0
var maxIndex: (x: Int, y: Int) = (0, 0)
(0..<9).forEach { index in
    let inputArr = readLine()!.split(separator: " ").map { Int($0)! }
    let currentMax = inputArr.max()!
    if currentMax > maxNum {
        maxNum = currentMax
        maxIndex.x = index + 1
        maxIndex.y = inputArr.firstIndex(of: currentMax)! + 1
    }
}
print(maxNum)
print(maxIndex.x, maxIndex.y)

์ด๋ ‡๊ฒŒ ํ’€์ดํ•œ ๊ฒฝ์šฐ, if๋ฌธ ๋‚ด์—์„œ๋งŒ maxIndex๊ฐ€ ๋ณ€๊ฒฝ๋˜๋ฏ€๋กœ ์ „์ฒด ๊ฐ’์ด 0์ผ ๋•Œ ์ฒ˜๋Ÿผ if๋ฌธ์„ ํ†ต๊ณผํ•˜์ง€ ๋ชปํ•˜๋Š” ๊ฒฝ์šฐ๋ฅผ ์ฒ˜๋ฆฌํ•˜์ง€ ๋ชปํ•œ๋‹ค.

โœ… ๋‹จ์ˆœํžˆ ์ถœ๋ ฅ ํ˜•ํƒœ๋งŒ ์กฐ์ •ํ•˜๋Š” ๊ฒฝ์šฐ์—๋Š”, ๋ณ€์ˆ˜๊ฐ’์„ ์กฐ์ •ํ•˜๋Š” ๊ฒŒ ์•„๋‹ˆ๋ผ ์ถœ๋ ฅ ๊ฐ’๋งŒ ์กฐ์ •ํ•˜์ž๋Š” ๊ตํ›ˆ์„ ์–ป์—ˆ๋‹ค.