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

[๋ฐฑ์ค€ 2947] ๋‚˜๋ฌด ์กฐ๊ฐ ๋ณธ๋ฌธ

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

[๋ฐฑ์ค€ 2947] ๋‚˜๋ฌด ์กฐ๊ฐ

๋น„๋น„ bibi 2022. 9. 28. 11:43

2947๋ฒˆ: ๋‚˜๋ฌด ์กฐ๊ฐ

  • 1, 2, 3, 4, 5๋กœ ๊ตฌ์„ฑ๋˜์–ด ์„ž์—ฌ ์žˆ๋Š” ๋ฐฐ์—ด์„ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•˜๋Š” ๋ฌธ์ œ.
  • ์•ž ์ˆ˜๊ฐ€ ๋’ค์˜ ์ˆ˜๋ณด๋‹ค ํฌ๋‹ค๋ฉด ๋‘˜์˜ ์œ„์น˜๋ฅผ ์„œ๋กœ ๋ฐ”๊พผ๋‹ค. (๋ฒ„๋ธ” ์ •๋ ฌ)

ํ’€์ด 1

ํƒ์ƒ‰ํ•  ์ธ๋ฑ์Šค๋ฅผ while๋ฌธ ๋ฐ”๊นฅ์— ๋‘๊ณ  ์•ž,๋’ค ์š”์†Œ๋ฅผ ๋น„๊ต

var inputArr = readLine()!.split(separator: " ").map { Int($0)! }
var index = 0
while true {
    if index == 4 {
        index = 0
        continue
    }
    if inputArr == [1, 2, 3, 4, 5] {
        break
    }
    if inputArr[index] > inputArr[index + 1] {
        let right = inputArr[index + 1]
        inputArr[index + 1] = inputArr[index]
        inputArr[index] = right

        inputArr.forEach{ print($0, terminator: " ") }
        print("")
    }
    index += 1
}

ํ’€์ด 2 (๊ฐœ์„ )

  • while true์™€ ํƒˆ์ถœ์กฐ๊ฑด์„ ๋”ฐ๋กœ ์ž‘์„ฑํ•˜์ง€ ์•Š๊ณ  while์กฐ๊ฑด์— ๋„ฃ์œผ๋ฉด ๋” ๊ฐ„๊ฒฐํ•ด์ง
  • ๋‹ค๋ฅธ ๋ถ„๋“ค์˜ ํ’€์ด๋ฅผ ๋ณด๋‹ˆ swapAt() ๋ฉ”์„œ๋“œ๊ฐ€ ์žˆ๊ธธ๋ž˜ ๋‚˜๋„ ์‚ฌ์šฉํ–ˆ๋‹ค.
    • swapAt(i, j) : ๋ฐฐ์—ด์—์„œ ์ธ๋ฑ์Šค i์— ์žˆ๋Š” ์š”์†Œ์™€ j์— ์žˆ๋Š” ์š”์†Œ์˜ ์œ„์น˜๋ฅผ ์„œ๋กœ ๋ฐ”๊พผ๋‹ค. O(1). ๊ณต์‹๋ฌธ์„œ
var inputArr = readLine()!.split(separator: " ").map { Int($0)! }
var index = 0
while inputArr != [1, 2, 3, 4, 5] {
    if index == inputArr.count - 1 {
        index = 0
        continue
    }
    if inputArr[index] > inputArr[index + 1] {
        inputArr.swapAt(index, index + 1)
        inputArr.forEach{ print($0, terminator: " ") }
        print("")
    }
    index += 1
}