Programmers ํ์ค๋ ์๋ฅผ ํ๊ณ ๋์, reduce๋ฅผ ์ด์ฉํ ํ์ด๋ฅผ ๋ง์ฃผ์ณ๋ฒ๋ ธ๋ค.
// Programmers ํ์ค๋ ์ ํ์ด
func solution(_ x:Int) -> Bool {
var sum_x = String(x).map{ Int(String($0))! }.reduce(0, +)
return x % sum_x == 0
}
ใ ใ .. ๋๋ ๊ณต๋ถํด์ค๊ฒ
reduce
์ปจํ ์ด๋ ๋ด๋ถ์ ๊ฐ์ ํ๋๋ก ํตํฉ(์ฐ์ฐ)ํ์ฌ return
* Swift์์๋ Python๊ณผ๋ ๋ฌ๋ฆฌ ๋ฐฐ์ด์ ์ด ํฉ์ ๊ตฌํ๋ ๋ด์ฅ ํจ์ sum์ด ์๋ค. ๋์ reduce๋ฅผ ์์ฉํด์ฃผ๋ฉด ๋๋ค.
(1) reduce(_: _:)
public func reduce<Result>(_ initialResult: Result,
_ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result
- ํด๋ก์ ๊ฐ ๊ฐ ์์๋ฅผ ์ ๋ฌ๋ฐ์ ์ฐ์ฐํ ํ ํด๋ก์ ์คํ์ ์ํด ๊ฐ์ ๋ค์ ๋ฐํํ์ฌ ์ปจํ ์ด๋๋ฅผ ์ํ
- ์ฒซ ๋ฒ์งธ ์ธ์๋ก ์ด๊น๊ฐ์ ์ง์ ํด์ฃผ์ด์ผํ๋ค.
let numbers: [Int] = [1, 2, 3]
var sum: Int = numbers.reduce(0, { (result: Int, element: Int) -> Int in
print("\(result) + \(element)")
// 0(=์ด๊ธฐ๊ฐ) + 1
// 1(=0+1) + 2
// 3(=1+2) + 3
return result + element // ์ํ
})
print(sum) // 6
// Closure ํํ์์ ์ฌ์ฉํ์ฌ ๊ฐ๊ฒฐํ๊ฒ ํํ
var sum2: Int = numbers.reduce(0) {
print("\($0) + \($1)")
// 0 + 1
// 1 + 2
// 3 + 3
return $0 + $1
}
print(sum2) // 6
reduce์ ์ฒซ๋ฒ์งธ ์ธ์ 0์ ์ง์ ํ๋ฉฐ, result ๋ด์ง $0๋ก ๊ฒฐ๊ณผ๊ฐ์ return ๋ฐ์ ์ปจํ ์ด๋ ๋ด๋ถ๋ฅผ ์ํํ๋ ๊ฒ์ ํ์ธํ ์ ์๋ค.
(2) reduce(into:_:)
public func reduce<Result>(into initialResult: Result,
_ updateAccumulatingResult: (inout Result, Element) throws -> () rethrows -> Result)
- ์ปจํ ์ด๋๋ฅผ ์ํํ์ฌ ํด๋ก์ ๊ฐ ์คํ๋์ง๋ง ํด๋ก์ ๊ฐ ๋ฐ๋ก ๊ฒฐ๊ณผ๊ฐ์ ๋ฐํํ์ง ์์. ๋์ inout ๋งค๊ฐ๋ณ์๋ฅผ ์ฌ์ฉํ์ฌ ์ด๊น๊ฐ์ ์ง์ ์ฐ์ฐ ์คํ
let numbers: [Int] = [1, 2, 3]
var sum = numbers.reduce(into: 0, { (result: inout Int, element: Int) in
// 0 + 1
// 1 + 2
// 3 + 3
print("\(result) + \(element)")
result += element // !!ํด๋ก์ ๊ฐ์ ๋ฐํํ์ง ์์!!
})
print(sum) // 6
map vs reduce
: ๊ฐ์ ์คํ ๊ฒฐ๊ณผ๋ฅผ ๋ค๋ฅธ ์ฝ๋๋ก ํํํด๋ณด๊ธฐ
- reduce(into:_:)๋ก color ๊ฐ์ ๋๋ฌธ์๋ก ๋ณํ
let colors: [String] = ["orange", "yellow", "green", "blue", "purple"]
var rainbowColors: [String] = colors.reduce(into: [], {
$0.append($1.uppercased())
})
print(rainbowColors) // ["ORANGE", "YELLOW", "GREEN", "BLUE", "PURPLE"]
- map์ผ๋ก color ๊ฐ์ ๋๋ฌธ์๋ก ๋ณํ
let colors: [String] = ["orange", "yellow", "green", "blue", "purple"]
var rainbowColors: [String] = colors.map { $0.uppercased() }
print(rainbowColors) // ["ORANGE", "YELLOW", "GREEN", "BLUE", "PURPLE"]
'๐ iOS > Swift' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Swift] self (0) | 2023.05.06 |
---|---|
[Swift] Guard๋ฌธ๊ณผ If๋ฌธ (0) | 2023.05.06 |
[Swift] map, flatMap, compactMap ? (0) | 2022.06.28 |
[Swift] inout? | ํจ์ ๋ด๋ถ์์ ํ๋ผ๋ฏธํฐ์ ๊ฐ์ ๋ณ๊ฒฝํ๊ณ ์ง์ํ๊ธฐ (0) | 2022.06.23 |
[Swift] Protocols | Delegate๋ฅผ ์ด์ง ๊ณ๋ค์ธ (0) | 2022.02.25 |