Skip to content

Instantly share code, notes, and snippets.

@natecook1000
Created December 4, 2021 06:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natecook1000/76f05f1956f501cd6c2e9bf9d641f4d7 to your computer and use it in GitHub Desktop.
Save natecook1000/76f05f1956f501cd6c2e9bf9d641f4d7 to your computer and use it in GitHub Desktop.
struct Transposition<Base: Collection>: RandomAccessCollection
where Base.Element: RandomAccessCollection
{
typealias Index = Int
typealias Indices = Range<Int>
var base: Base
struct Transposed: Collection {
typealias Index = Base.Index
var base: Base
var offset: Int
var startIndex: Base.Index { base.startIndex }
var endIndex: Base.Index { base.endIndex }
subscript(position: Base.Index) -> Base.Element.Element {
let subCollection = base[position]
let subIndex = subCollection.index(subCollection.startIndex, offsetBy: offset)
return subCollection[subIndex]
}
func index(after i: Base.Index) -> Base.Index {
base.index(after: i)
}
}
var startIndex: Int { 0 }
var endIndex: Int { base.first?.count ?? 0 }
subscript(i: Int) -> Transposed {
Transposed(base: base, offset: i)
}
}
extension Collection where Element: RandomAccessCollection {
func transposed() -> Transposition<Self> {
Transposition(base: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment