[๐Ÿ“ iOS TIL] #3 ... ๐ŸŽ Swift ๏ผ† Algorithm ๐Ÿ–ฅ๏ธ

TaeUkยท2024๋…„ 2์›” 1์ผ
0

๐ŸŽ iOS TIL

๋ชฉ๋ก ๋ณด๊ธฐ
2/18
post-thumbnail

0. ์‹œ์ž‘ํ•˜๊ธฐ ์•ž์„œ...

์ด์ „ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ ํ’€์ด์—์„œ๋Š” ์ต์ˆ™ํ•˜๋˜ C์–ธ์–ด๋ฅผ ํ™œ์šฉํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ๋‹ค. ํ•˜์ง€๋งŒ ์•ž์œผ๋กœ๋Š” IOS์— ์ ์‘ํ•˜๊ธฐ ์œ„ํ•ด Swift๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ’€ ๊ณ„ํš์ด๋‹ค!

Swift๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ช‡๋ช‡ ๋ฌธ์ œ๋ฅผ ํ’€์–ด๋ณด์•˜๋Š”๋ฐ, C์–ธ์–ด๋ณด๋‹ค ํŽธ๋ฆฌํ•˜๊ฒŒ ๋Š๊ปด์ง€์ง€๋งŒ ์•„์ง ์ต์ˆ™ํ•˜์ง€ ์•Š์•„ ํž˜๋“ค๋‹ค...


1. lv.0 ๋ชซ ๊ตฌํ•˜๊ธฐ

  • ๋ฌธ์ œ ์„ค๋ช…
    ์ •์ˆ˜ num1, num2๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, num1์„ num2๋กœ ๋‚˜๋ˆˆ ๋ชซ์„ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.
๋ฌธ์ œ ํ’€์ด

import Foundation

func solution(_ num1:Int, _ num2:Int) -> Int {
    var data = num1 / num2
    return data
}

์šฐ์„  lv.0 ๋ฌธ์ œ๋ฅผ Swift๋กœ ํ’€์–ด๋ณด์•˜๋‹ค. ๋งจ ์œ„์— ์„ ์–ธ๋˜์–ด ์žˆ๋Š” "import Foundation"์ด ๋ญ”์ง€ ๊ถ๊ธˆํ–ˆ๋‹ค. ๊ทธ๋ž˜์„œ ์ฐพ์•„๋ณด๋‹ˆ iOS ๊ฐœ๋ฐœ์— ์ „๋ฐ˜์ ์œผ๋กœ ์‚ฌ์šฉ๋˜๋Š” ํ”„๋ ˆ์ž„์›Œํฌ์˜€๋‹ค.

์ฐธ๊ณ  ์ž๋ฃŒ : iOS - Foundation


2. lv.1 ์ง์ˆ˜์™€ ํ™€์ˆ˜

  • ๋ฌธ์ œ ์„ค๋ช…
    ์ •์ˆ˜ num์ด ์ง์ˆ˜์ผ ๊ฒฝ์šฐ "Even"์„ ๋ฐ˜ํ™˜ํ•˜๊ณ  ํ™€์ˆ˜์ธ ๊ฒฝ์šฐ "Odd"๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜, solution์„ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.
๋ฌธ์ œ ํ’€์ด

func solution(_ num:Int) -> String {
    return num % 2 == 0 ? "Even" : "Odd"
}

ํ•ด๋‹น ๋ฌธ์ œ๋ฅผ ๋งจ ์ฒ˜์Œ ์ ‘ํ–ˆ์„ ๋•Œ, if ์กฐ๊ฑด๋ฌธ์„ ํ™œ์šฉํ•˜์˜€์ง€๋งŒ ๋” ๊ฐ„๋‹จํ•œ ๋ฐฉ๋ฒ•์ด ์ƒ๊ฐ๋‚˜์„œ ์œ„ ๋ฌธ์ œ ํ’€์ด์™€ ๊ฐ™์ด ์‚ผํ•ญ์—ฐ์‚ฐ์ž๋ฅผ ์‚ฌ์šฉํ•˜์˜€๋‹ค.

if ์กฐ๊ฑด๋ฌธ์„ ํ™œ์šฉํ•œ ๋ฌธ์ œ ํ’€์ด

func solution(_ num:Int) -> String {
    if (num % 2 == 0) {
        return "Even"
    }
    else {
        return "Odd"
    }
}

3. lv.1 ํ‰๊ท  ๊ตฌํ•˜๊ธฐ

  • ๋ฌธ์ œ ์„ค๋ช…
    ์ •์ˆ˜๋ฅผ ๋‹ด๊ณ  ์žˆ๋Š” ๋ฐฐ์—ด arr์˜ ํ‰๊ท ๊ฐ’์„ returnํ•˜๋Š” ํ•จ์ˆ˜, solution์„ ์™„์„ฑํ•ด๋ณด์„ธ์š”.
๋ฌธ์ œ ํ’€์ด

func solution(_ arr:[Int]) -> Double {
    var val = 0
    
    for i in 0..<arr.count {
        val += arr[i]
    }
    
    return Double(val) / Double(arr.count)
}

ํ•ด๋‹น ๋ฌธ์ œ์—์„œ ๋ฐฐ์—ด ๊ธธ์ด๋ฅผ arr.count๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ™•์ธํ•  ์ˆ˜ ์žˆ์—ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๋‹ค๋ฅธ ๋ฌธ์ œ ํ’€์ด๋ฅผ ์ฐพ์•„๋ณด๋‹ค ์•Œ๊ฒŒ๋œ ๋ฐฉ๋ฒ• ์ค‘, Swift ๊ณ ์ฐจํ•จ์ˆ˜์ธ reduce๋ฅผ ํ™œ์šฉํ•˜๋Š” ๋ฐฉ์•ˆ์ด ์žˆ๋‹ค.

์ฐธ๊ณ  ์ž๋ฃŒ : [Swift] ๊ณ ์ฐจํ•จ์ˆ˜ (map, filter, reduce)

reduce๋ฅผ ํ™œ์šฉํ•œ ๋ฌธ์ œ ํ’€์ด

func solution(_ arr:[Int]) -> Double {
    var val = Double(arr.reduce(0, +))
    
    return val / Double(arr.count)
}

reduce ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•จ์œผ๋กœ์จ ํ›จ์”ฌ ๋” ๊ฐ„๋‹จํ•˜์กŒ์œผ๋ฉฐ, ์ฝ”๋“œ ์ž‘์„ฑ ๋˜ํ•œ ๊ฐ„ํŽธํ•ด์กŒ๋‹ค!

0๊ฐœ์˜ ๋Œ“๊ธ€