๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
3๏ธโƒฃ Swift/Problem Solving

[Swift Algorithm] ํ–‰๋ ฌ์˜ ๋ง์…ˆ Programmers(Lv.1)

by seolhee2750 2021. 6. 6.
๋ฌธ์ œ ์„ค๋ช…

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

 

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

 

์ž…์ถœ๋ ฅ ์˜ˆ
arr1 arr2 return
[[1, 2], [2, 3]] [[3, 4], [5, 6]] [[4, 6], [7, 9]]
[[1], [2]] [[3], [4]] [[4], [6]]

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
func solution(_ arr1:[[Int]], _ arr2:[[Int]]) -> [[Int]] {
    var array1 = [Int]()
    var array2 = [[Int]]()
    var sum = 0
    
    for i in 0 ..< arr1.count {
        for j in 0 ..< arr1[i].count {
            sum = arr1[i][j] + arr2[i][j]
            array1.append(sum)
        }
        array2.append(array1)
        array1.removeAll()
    }
    
    return array2
}
  • ๊ฐ™์€ ์ž๋ฆฌ์˜ ์ˆ˜๋ฅผ ๋”ํ•œ ๊ฐ’์„ ์ €์žฅํ•ด ์ค„ ๋นˆ ๋ฐฐ์—ด array1, ๊ทธ๋ฆฌ๊ณ  ๊ฒฐ๊ณผ๋ฅผ ์ €์žฅํ•  array2๋ฅผ ์ƒ์„ฑ
  • ์ž…๋ ฅ ๋ฐ›์€ ์ฒซ ๋ฒˆ์งธ ๋ฐฐ์—ด์˜ ๊ธธ์ด๋ฅผ ๊ธฐ์ค€์œผ๋กœ 2์ค‘ for๋ฌธ ๋Œ๋ฆฌ๊ธฐ! (์–ด์ฐจํ”ผ ๋‘ ๋ฐฐ์—ด์˜ ๊ธธ์ด๋Š” ๊ฐ™์œผ๋ฏ€๋กœ)
  • array1์— ๊ฐ™์€ ์œ„์น˜์˜ ์ˆ˜๋ฅผ ๋”ํ•œ ๊ฒฐ๊ณผ๋ฅผ ์ถ”๊ฐ€ํ•ด์ฃผ๊ณ ,
    ์™„์„ฑ๋œ array1์€ array2์— ์ถ”๊ฐ€ํ•ด์ค€ ํ›„ removeAll๋กœ ๋น„์›Œ์ค€๋‹ค.
    ์ด๋Ÿฐ ์‹์œผ๋กœ array2๋ฅผ ๋ชจ๋‘ ์ฑ„์›Œ ๋ฆฌํ„ด

 

์ธ์ƒ์ ์ธ ํ’€์ด
import Foundation

func solution(_ arr1:[[Int]], _ arr2:[[Int]]) -> [[Int]] {
    return zip(arr1, arr2).map{zip($0,$1).map{$0+$1}}
}
  • zip ํ•จ์ˆ˜๋ฅผ ์ด์šฉ, ์Œ์œผ๋กœ ๋ฌถ์–ด์ฃผ์–ด ๊ณ„์‚ฐํ–ˆ๋‹ค.
  • ๋‚ด ํ’€์ด๋Š” ๋‚ด๊ฐ€ ํ’€๋ฉด์„œ๋„ ์ข€ ๋ณต์žกํ•˜๋‹ค๊ณ  ์ƒ๊ฐํ–ˆ๋Š”๋ฐ,
    zip๊ณผ map์„ ์ž˜ ์‚ฌ์šฉํ•˜๋‹ˆ ์ด๋ ‡๊ฒŒ ํ•œ ์ค„๋กœ๋„ ๊ฐ€๋Šฅํ•˜๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • zip ํ•จ์ˆ˜๋Š” ์˜ค๋Š˜ ์ธ์ƒ์ ์ธ ํ’€์ด๋ฅผ ํ†ตํ•ด ์ฒ˜์Œ ๋ฐฐ์šฐ๊ฒŒ ๋๋Š”๋ฐ,
    ๋‘ ๊ฐœ์˜ ์‹œํ€€์Šค๋ฅผ ์Œ์œผ๋กœ ๋ฌถ์–ด์ฃผ๋Š” ๊ฒƒ์„ ๋งํ•œ๋‹ค๊ณ  ํ•œ๋‹ค.. 
    ์ด๊ฑด ๋”ฐ๋กœ ๊ณต๋ถ€๊ฐ€ ํ•„์š”ํ•  ๋“ฏ ํ•˜๋‹ค.
  • map ํ•จ์ˆ˜๋Š” ์ •๋ง ๋‹ค์–‘ํ•˜๊ฒŒ ์“ฐ์ด๋Š” ๋“ฏ ํ•˜๋‹ค. ์ž์œ ์ž์žฌ๋กœ ์“ธ ์ˆ˜ ์žˆ๋„๋ก ์—ฐ์Šต์ด ํ•„์š”ํ•˜๊ฒ ๋‹ค.

 


 

๐Ÿ– [ ์ถ”๊ฐ€ ] 1์ฃผ์ผ ํ›„ ๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ

func solution(_ arr1:[[Int]], _ arr2:[[Int]]) -> [[Int]] {
    var result = arr1
    
    for i in 0..<arr1.count {
        for j in 0..<arr1[1].count {
            result[i][j] += arr2[i][j]
        }
    }
    return result
}
  • ์ฒซ ๋ฒˆ์งธ ํ’€์ด๋ณด๋‹ค ํ›จ์”ฌ ๊ฐ„๊ฒฐํ•˜๊ณ  ์“ธ๋ฐ ์—†๋Š” ์ฝ”๋“œ ์—†์ด ์ž˜ ํ‘ผ ๊ฒƒ ๊ฐ™๋‹ค.
  • ์ธ์ƒ์ ์ธ ํ’€์ด ํ™•์ธํ•ด๋ณด๋‹ˆ zip, map ํ™œ์šฉํ•˜๋ฉด ํ•œ ์ค„์— ๋๋‚ผ ์ˆ˜ ์žˆ๊ตฌ๋‚˜; 

 


 

๋ฌธ์ œ

https://programmers.co.kr/learn/courses/30/lessons/12950

๋Œ“๊ธ€