๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“– Problem Solution/Programmers

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ํ–‰๋ ฌ์˜ ๋ง์…ˆ Swift

by Fomagran ๐Ÿ’ป 2020. 3. 1.
728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ ์„ค๋ช…

ํ–‰๋ ฌ์˜ ๋ง์…ˆ์€ ํ–‰๊ณผ ์—ด์˜ ํฌ๊ธฐ๊ฐ€ ๊ฐ™์€ ๋‘ ํ–‰๋ ฌ์˜ ๊ฐ™์€ ํ–‰, ๊ฐ™์€ ์—ด์˜ ๊ฐ’์„ ์„œ๋กœ ๋”ํ•œ ๊ฒฐ๊ณผ๊ฐ€ ๋ฉ๋‹ˆ๋‹ค. 2๊ฐœ์˜ ํ–‰๋ ฌ arr1๊ณผ arr2๋ฅผ ์ž…๋ ฅ๋ฐ›์•„, ํ–‰๋ ฌ ๋ง์…ˆ์˜ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜, solution์„ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

์ œํ•œ ์กฐ๊ฑด

  • ํ–‰๋ ฌ arr1, arr2์˜ ํ–‰๊ณผ ์—ด์˜ ๊ธธ์ด๋Š” 500์„ ๋„˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

์ž…์ถœ๋ ฅ ์˜ˆ

arr1 arr2 return
[[1],[2]] [[3],[4]] [[4],[6]]
[[1,2],[2,3]] [[3,4],[5,6]] [[4,6],[7,9]]

ํ’€์ด:๋ฐฐ์—ด array1์„ ๋งŒ๋“ค๊ณ  ์ด์ค‘๋ฐฐ์—ด array2๋ฅผ ๋งŒ๋“ค์–ด์ค€ ๋’ค

์ด์ค‘ํฌ๋ฌธ arr1์˜ ๋ฐฐ์—ด์˜ ๊ฐฏ์ˆ˜๋งŒํผ ๋Œ๋ฆฌ๊ณ  ๊ทธ ์•ˆ์— ๋ฐฐ์—ด์•ˆ์— ๋ฐฐ์—ด์•ˆ์˜ ์ˆซ์ž ๊ฐฏ์ˆ˜๋งŒํผ ๋Œ๋ฆฐ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๊ฐ ๊ฐ ํ–‰๊ณผ ์—ด์— ๋งž๊ฒŒ ๋”ํ•ด์„œ array1์— ๋„ฃ์–ด์ฃผ๊ณ  ๋‚˜์™€์„œ array2์— array1์„ ๋„ฃ์–ด์ฃผ๊ณ  array1์„ ๋ชจ๋‘ ์‚ญ์ œํ•ด์ค€๋‹ค,

1
2
3
4
5
6
7
8
9
10
11
12
13
func solution(_ arr1:[[Int]], _ arr2:[[Int]]) -> [[Int]] {
    var array1 = [Int]()
    var array2 = [[Int]]()
    for i in 0..<arr1.count{
        for j in 0..<arr1[i].count{
            let sum = arr1[i][j] + arr2[i][j]
            array1.append(sum)
        }
        array2.append(array1)
        array1.removeAll()
    }
    return array2
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

๋‹ค๋ฅธ ์‚ฌ๋žŒ ํ’€์ด ์ค‘ ๊ฐ€์žฅ ์ข‹๋‹ค๊ณ  ์ƒ๊ฐํ•˜๋Š” ๊ฒƒ

1
2
3
4
5
import Foundation
 
func solution(_ arr1:[[Int]], _ arr2:[[Int]]) -> [[Int]] {
    return zip(arr1, arr2).map{zip($0,$1).map{$0+$1}}
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

ํ’€์ด: zip์„ ์ด์šฉํ•ด์„œ ๋‘ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ง์ง€์–ด์„œ ํ•ฉ์ณ์ค„ ์ˆ˜ ์žˆ๋‹ค.

์šฐ์„  arr1,arr2๋ฅผ zip์œผ๋กœ ํ•ฉ์ณ์ฃผ๋ฉด ๊ฐ™์€ ์ธ๋ฑ์Šค์˜ ๋ฐฐ์—ด๋ผ๋ฆฌ ์ง์ง“๊ฒŒ ๋œ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด

solution([[1,2],[2,3]],[[3,4],[5,6]])์ผ ๊ฒฝ์šฐ

๋ฐฐ์—ด์˜ ์ฒซ ๋ฒˆ์งธ๋ผ๋ฆฌ ([1,2],[3,4]),([2,3],[5,6])ํ•ฉ์ณ์ง€๊ฒŒ ๋˜๊ณ 

๋‹ค์‹œ ํ•œ ๋ฒˆ zip($0,$1)์„ ํ•ด์ฃผ๋ฉด zip์„ ํ†ตํ•ด ๋งŒ๋“ค์–ด์ง„ ๋ฐฐ์—ด์˜ ์ฒซ ๋ฒˆ์งธ๋ผ๋ฆฌ ๋ฌถ์ด๋Š”๋ฐ (1,3),(2,4),(2,5),(3,6) ์ด๋ ‡๊ฒŒ ๋ฌถ์ธ ๊ฑธ map์œผ๋กœ ๋ฐฐ์—ด๋กœ ๋งŒ๋“ค์–ด์ค€๋‹ค. ๊ทธ๋ฆฌ๊ณ  map์„ ํ†ตํ•ด์„œ ์•ˆ์— ์žˆ๋Š” ๊ฒƒ๋“ค์„ ๊ฐ ๊ฐ ๋”ํ•ด์ค€๋‹ค.

728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€