ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ํ–‰๋ ฌ์˜ ๊ณฑ์…ˆ(Swift)

2022. 10. 12. 10:39ใ†ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค-Swift

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ํ–‰๋ ฌ์˜ ๊ณฑ์…ˆ(Swift)

 

 

 ๋ฌธ์ œ ์„ค๋ช…

 

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

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

 ๋‚˜์˜ ํ’€์ด

 

ํ–‰๋ ฌ์˜ ๊ณฑ์…ˆ์€ aํ–‰๋ ฌ๊ณผ bํ–‰๋ ฌ์ด ์žˆ์„๋•Œ aํ–‰๋ ฌ์˜ ํ–‰๊ณผ bํ–‰๋ ฌ์˜ ์—ด์˜ ๊ฐœ์ˆ˜๊ฐ€ ๊ฐ™์•„์•ผ ๊ณฑํ•ด์งˆ ์ˆ˜ ์žˆ๋‹ค.

๊ทธ๋ฆฌ๊ณ  ๊ฒฐ๊ณผ ํ–‰๋ ฌ์€ a์˜ ํ–‰์˜ ๊ฐœ์ˆ˜, b์˜ ์—ด์˜ ๊ฐœ์ˆ˜๋ฅผ ๋”ฐ๋ฅด๊ฒŒ ๋œ๋‹ค.

 

import Foundation

func solution(_ arr1:[[Int]], _ arr2:[[Int]]) -> [[Int]] {
    
    var arr3: [[Int]] = [[Int]](repeating: [Int](repeating: 0, count: arr2[0].count), count: arr1.count)
    
    for i in 0..<arr1.count {
        for j in 0..<arr2[0].count {
            var sum = 0
            for k in 0..<arr1[i].count {
                sum += arr1[i][k] * arr2[k][j]
            }
            arr3[i][j] = sum    
        }
    }
    return arr3
}

 

 

 

 ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด

 

Arrayํƒ€์ž… ์•ˆ์— [Int]()๋ฅผ ํ†ตํ•ด์„œ 2์ฐจ์› ๋ฐฐ์—ด์„ ์ดˆ๊ธฐํ™” ํ•  ์ˆ˜ ์žˆ์—ˆ๋‹ค.

 

import Foundation

func solution(_ arr1:[[Int]], _ arr2:[[Int]]) -> [[Int]] {
    
    var arr3 = Array(repeating: [Int](), count: arr1.count)
    
    for i in 0..<arr1.count {
        for j in 0..<arr2[0].count {
            var sum = 0
            for k in 0..<arr1[0].count {
                sum += arr1[i][k] * arr2[k][j]
            }
            arr3[i].append(sum)
        }
    }
    
    return arr3
}

 

 ํ”ผ๋“œ๋ฐฑ

 

ํ–‰๋ ฌ์˜ ๊ณฑ์…ˆ์˜ ๊ฒฐ๊ณผ๋Š” a, b์ผ๋•Œ a์˜ ํ–‰์˜ ๊ฐœ์ˆ˜, b์˜ ์—ด์˜ ๊ฐœ์ˆ˜๋กœ ๊ตฌ์„ฑ๋œ๋‹ค.

arr1์ด๋ผ๋Š” 2์ฐจ์›๋ฐฐ์—ด์˜ ์—ด์˜ ๊ฐœ์ˆ˜๋Š” arr1[0].count์ด๋‹ค.