Skip to content

Instantly share code, notes, and snippets.

@sodastsai
Last active May 28, 2017 17:17
Show Gist options
  • Save sodastsai/3b2498ea0ff648fdcbbb1cacd4aa096c to your computer and use it in GitHub Desktop.
Save sodastsai/3b2498ea0ff648fdcbbb1cacd4aa096c to your computer and use it in GitHub Desktop.
struct Matrix<Element> {
let dimensions: [Int]
var content: [Element]
init(_ dimensions: [Int], initial value: Element) {
self.dimensions = dimensions
let elementCount = self.dimensions.reduce(1, *)
self.content = [Element](repeatElement(value, count: elementCount))
}
func index(of indexes: [Int]) -> Int {
// To access [w][x][y][z] in matrix[a][b][c][d], the index is
// w*d*c*b + x*d*c + y*d + z
let reversedDimensions = Array(self.dimensions.reversed())
let dimensionLevels = (0..<(reversedDimensions.count-1)).map {
reversedDimensions[($0+1)..<reversedDimensions.count]
}
return zip(indexes, dimensionLevels).map { $1.reduce($0, *) }.reduce(indexes.last!, +)
}
subscript(indexes: Int...) -> Element {
get {
return self.content[self.index(of: indexes)]
}
set {
self.content[self.index(of: indexes)] = newValue
}
}
}
extension Matrix where Element: ExpressibleByIntegerLiteral {
init(_ dimensions: [Int]) {
self.init(dimensions, initial: 0)
}
}
var matrix32 = Matrix<Int>([3, 2])
matrix32[0, 1] = 5
matrix32[1, 0] = 7
print(matrix32.content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment