Last active
January 5, 2016 06:08
-
-
Save rayfix/9d4e4d302a77fe1df5b8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct MultiArray<Element> { | |
private var data: [Element] // the actual data | |
private var counts: [Int] // the size of each dimension | |
private var offsets: [Int] // multipliers for accessing each dimension quickly | |
private func computeIndex(indices: [Int]) -> Int { | |
precondition(indices.count == counts.count) | |
for (index, count) in zip(indices, counts) { | |
precondition(index >= 0 && index < count) | |
} | |
return zip(indices, offsets).reduce(0) { $0 + $1.0 * $1.1 } | |
} | |
var dimensions: Int { | |
return counts.count | |
} | |
var count: Int { | |
return data.count | |
} | |
subscript(indicies: Int...) -> Element { | |
get { | |
let index = computeIndex(indicies) | |
return data[index] | |
} | |
set { | |
let index = computeIndex(indicies) | |
data[index] = newValue | |
} | |
} | |
init(counts: [Int], repeatedValue: Element) { | |
self.counts = counts | |
var offset = 1 | |
offsets = counts.map { input in | |
let output = offset | |
offset *= input | |
return output | |
} | |
let totalCount = counts.reduce(1) { $0 * $1 } | |
data = Array(count: totalCount, repeatedValue: repeatedValue) | |
} | |
} | |
// Usage: | |
var md = MultiArray(counts: [10,20,20], repeatedValue: 0) | |
md[1,1,1] = 10 | |
md[0,1,0] | |
md[1,1,1] | |
md.count |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment