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

[๋ฐฑ์ค€ 6359] ๋งŒ์ทจํ•œ ์ƒ๋ฒ” (Swift) ๋ณธ๋ฌธ

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

[๋ฐฑ์ค€ 6359] ๋งŒ์ทจํ•œ ์ƒ๋ฒ” (Swift)

๋น„๋น„ bibi 2022. 11. 23. 11:54

6359๋ฒˆ: ๋งŒ์ทจํ•œ ์ƒ๋ฒ”

์ค‘์ฒฉ ๋ฐ˜๋ณต๋ฌธ์„ ํ—ท๊ฐˆ๋ฆฌ์ง€ ์•Š๊ณ  ์ž˜ ์‚ฌ์šฉํ•˜๋ฉด ํ’€ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ๋‹ค.

  • n๊ฐœ์˜ ๋ฐฉ์ด ์žˆ๋Š” ๊ฐ์˜ฅ์ด ์ฃผ์–ด์ง„๋‹ค
    • ์ฒ˜์Œ์—” ๋‹น์—ฐํžˆ ๋ชจ๋‘ ์ž ๊ฒจ ์žˆ๋‹ค.
  • ๋งค k๋ฒˆ์งธ ์‹œํ–‰๋งˆ๋‹ค, k์˜ ๋ฐฐ์ˆ˜์— ํ•ด๋‹นํ•˜๋Š” ๋ฌธ์ด ์—ด๋ ค์žˆ๋‹ค๋ฉด ๋‹ซ๊ณ , ๋‹ซํ˜€ ์žˆ๋‹ค๋ฉด ์—ฐ๋‹ค.
  • n๋ฒˆ์งธ ์‹œํ–‰๊นŒ์ง€ ๋ฐ˜๋ณต ํ›„ ์—ด๋ ค ์žˆ๋Š” ๋ฌธ์˜ ๊ฐฏ์ˆ˜๋ฅผ ์„ธ๋ฉด ๋œ๋‹ค.
  • 5 โ‰ค n โ‰ค 100 ์ด๋ฏ€๋กœ ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ๋„ ์ถฉ๋ถ„ํžˆ ํ’€ ์ˆ˜ ์žˆ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด n=3 ์ด๋ผ ๊ฐ์˜ฅ์— ๋ฐฉ์ด 3๊ฐœ์ผ ๋•Œ,
(false, false, false)
1๋ฒˆ์งธ ์‹œํ–‰์—๋Š” 1์˜ ๋ฐฐ์ˆ˜์˜ ๋ฌธ(1, 2, 3..๋ฒˆ์งธ ๋ฌธ)์ด ์—ด๋ ค์žˆ๋‹ค๋ฉด ๋‹ซ๊ณ , ๋‹ซํ˜€ ์žˆ๋‹ค๋ฉด ์—ฐ๋‹ค. (๋งจ ์ฒ˜์Œ์—๋Š” ๋ชจ๋‘ ์ž ๊ฒจ ์žˆ์œผ๋ฏ€๋กœ, ๋ชจ๋‘ ์—ฐ๋‹ค)
(true, true, true)
2๋ฒˆ์งธ ์‹œํ–‰์—๋Š” 2์˜ ๋ฐฐ์ˆ˜์˜ ๋ฌธ์ด ์—ด๋ ค์žˆ๋‹ค๋ฉด ๋‹ซ๊ณ , ๋‹ซํ˜€ ์žˆ๋‹ค๋ฉด ์—ฐ๋‹ค.
(true, false, true)
3๋ฒˆ์งธ ์‹œํ–‰์—๋Š” 3์˜ ๋ฐฐ์ˆ˜์˜ ๋ฌธ์ด ์—ด๋ ค์žˆ๋‹ค๋ฉด ๋‹ซ๊ณ , ๋‹ซํ˜€ ์žˆ๋‹ค๋ฉด ์—ฐ๋‹ค.
(true, false, false)
๋”ฐ๋ผ์„œ ๋„๋ง์น  ์ˆ˜ ์žˆ๋Š” ํ•™์ƒ์€ 1๋ช…์ด๋‹ค.

ํ’€์ด

let count = Int(readLine()!)!
        (1...count).forEach { _ in
            let input = Int(readLine()!)!
            var prison = Array<Bool>(repeating: false, count: input)
            var k = 1
            while k <= input {
                (1...input).forEach { num in
                    let index = k * num - 1
                    if index < input {
                        prison[index] = !prison[index]
                    } else {
                        return
                    }
                }
                k += 1
            }
            print(prison.filter { $0 == true }.count)
        }
  • prison[index] = !prison[index] ์ด ๋ถ€๋ถ„์€ ์ฒ˜์Œ์—
if prison[index] == false {
    prison[index] = true
} else {
    prison[index] = false
}

์ด๋ ‡๊ฒŒ ์ž‘์„ฑํ–ˆ๋Š”๋ฐ, ๋‹ค๋ฅธ ํ’€์ด์—์„œ ! ๋กœ ํ›จ์”ฌ ์งง๊ฒŒ ํ‘œํ˜„ํ•˜๊ธธ๋ž˜ ๋‚˜๋„ ์ฐจ์šฉํ•ด ๋ณด์•˜๋‹ค. ๐Ÿ‘