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

[Swift Algorithm] ํ–‰๋ ฌ์˜ ๊ณฑ์…ˆ Programmers(Lv.2)

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

2์ฐจ์› ํ–‰๋ ฌ arr1๊ณผ arr2๋ฅผ ์ž…๋ ฅ๋ฐ›์•„, arr1์— arr2๋ฅผ ๊ณฑํ•œ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜, solution์„ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

 

์ œํ•œ ์กฐ๊ฑด
  • ํ–‰๋ ฌ arr1, arr2์˜ ํ–‰๊ณผ ์—ด์˜ ๊ธธ์ด๋Š” 2 ์ด์ƒ 100 ์ดํ•˜์ž…๋‹ˆ๋‹ค.
  • ํ–‰๋ ฌ arr1, arr2์˜ ์›์†Œ๋Š” -10 ์ด์ƒ 20 ์ดํ•˜์ธ ์ž์—ฐ์ˆ˜์ž…๋‹ˆ๋‹ค.
  • ๊ณฑํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐฐ์—ด๋งŒ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

 

์ž…์ถœ๋ ฅ ์˜ˆ
arr1 arr2 return
[[1, 4], [3, 2], [4, 1]] [[3, 3], [3, 3]] [[15, 15], [15, 15], [15, 15]]
[[2, 3, 2], [4, 2, 4], [3, 1, 4]] [[5, 4, 3], [2, 4, 1], [3, 1, 1]] [[22, 22, 11], [36, 28, 18], [29, 20, 14]]

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
func solution(_ arr1:[[Int]], _ arr2:[[Int]]) -> [[Int]] {
    var result = [[Int]]()
    
    for i in 0..<arr1.count {
        var tempArr = [Int]() // ํ•œ ํ–‰์„ ๋งŒ๋“ค์–ด ๋„ฃ์„ ๋ฐฐ์—ด ์ƒ์„ฑ
        for j in 0 ..< arr2[0].count { // arr2[0]์˜ ๊ธธ์ด๋งŒํผ ๊ณฑ์…ˆ์ด ์‹œํ–‰๋  ๊ฒƒ,!,!,!
            var sum = 0 // ๊ฐ’์„ ๋”ํ•ด์ค„ ๋ณ€์ˆ˜ ์ƒ์„ฑ
            for k in 0 ..< arr1[0].count {
                sum += arr1[i][k] * arr2[k][j] // ๋ฉ”์ธ ๊ณ„์‚ฐ์‹
            }
            tempArr.append(sum)
        }
        result.append(tempArr)
    }
    
    return result
}
  • 3์ค‘ for๋ฌธ์„ ์‚ฌ์šฉํ•ด ํ–‰๋ ฌ์˜ ๊ณฑ์…ˆ์„ ๊ตฌํ˜„ํ•ด์ฃผ์—ˆ๋‹ค.
  • result ๋ฐฐ์—ด์— ํ•œ ํ–‰์”ฉ ๋งŒ๋“ค์–ด append ํ•ด์ฃผ์—ˆ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ํ–‰๋ ฌ ๊ณฑ์…ˆ์€ ์ฝ”๋“œ๋กœ ๊ตฌํ˜„ํ•˜๋ ค๊ณ  ํ•˜๋ฉด ์‰ฌ์šฐ๋ฉด์„œ ์ข€ ๋ณต์žกํ•ด์„œ ์‹œ๊ฐ„์ด ์˜ˆ์ƒ๋ณด๋‹ค ์˜ค๋ž˜๊ฑธ๋ฆฐ๋‹ค.ใ…œ
  • ๋งŽ์ด ํ’€์–ด๋ด์•ผ ํ•  ๊ฒƒ ๊ฐ™๋‹ค.

 


 

๋ฌธ์ œ

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

๋Œ“๊ธ€