Skip to content

Instantly share code, notes, and snippets.

@masiht
Created January 9, 2018 20:51
Show Gist options
  • Save masiht/ebb0bac71ef3e728807af95f5ce6e468 to your computer and use it in GitHub Desktop.
Save masiht/ebb0bac71ef3e728807af95f5ce6e468 to your computer and use it in GitHub Desktop.
use of functional dot product in matrix multiplication
struct Matrix {
let rows: Int
let columns: Int
var elements: [[Int]]
// MARK: - Constructors
private init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
elements = Array(repeating: Array(repeating: 0, count: columns), count: rows)
}
public init(elements: [[Int]]) {
self.rows = elements.count
self.columns = elements[0].count
self.elements = elements
}
// MARK: - Private methods
private func getRow(At i: Int) -> [Int] {
return self.elements[i]
}
private func getColumn(At j: Int) -> [Int] {
return self.elements.map { row in row[j] }
}
// MARK: - dot product
private func dotProduct(a: [Int], b: [Int]) -> Int {
return zip(a, b).reduce(0) { (result, pair) in
return result + pair.0 * pair.1
}
}
// MARK: - subscript
public subscript(row: Int, column: Int) -> Int {
get { return elements[row][column] }
set { return elements[row][column] = newValue }
}
// MARK: - multiply
public func multiply(by B: Matrix) -> Matrix {
let A = self
assert(A.columns == B.rows, "Invalid dimensions")
var C = Matrix(rows: A.rows, columns: B.columns)
for i in 0..<A.rows {
for j in 0..<B.columns {
C[i, j] = dotProduct(a: A.getRow(At: i), b: B.getColumn(At: j))
}
}
return C
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment