Skip to content

Instantly share code, notes, and snippets.

@benigumocom
Last active February 1, 2024 02:23
Show Gist options
  • Save benigumocom/64c6f780670b01541173bc4f78304d4c to your computer and use it in GitHub Desktop.
Save benigumocom/64c6f780670b01541173bc4f78304d4c to your computer and use it in GitHub Desktop.
【Swift】2次元配列 で 転置行列 ( transpose matrix ) 👉 https://android.benigumo.com/20240201/transpose-matrix/
extension Collection where Element: Collection,
Self.Index == Int, Element.Index == Int {
func transposed1() -> [[Element.Element]] {
let cols = 0 ..< (self.first?.count ?? 0)
let rows = 0 ..< self.count
var result: [[Element.Element]] = []
for col in cols {
var newRow: [Element.Element] = []
for row in rows {
newRow.append(self[row][col])
}
result.append(newRow)
}
return result
}
func transposed2() -> [[Element.Element]] {
let cols = 0 ..< (self.first?.count ?? 0)
let rows = 0 ..< self.count
return cols.map { col in
rows.map { row in
self[row][col]
}
}
}
func transposed3() -> [[Element.Element]] {
return (0 ..< (first?.count ?? 0)).map { col in
(0 ..< count).map { row in
self[row][col]
}
}
}
}
let d = [
[ 1, 2, 3, 4, 5],
["A", "B", "C", "D", "E"],
["あ", "い", "う", "え", "お"],
["か", "き", "く", "け", "こ"]
]
print(d)
print(d.transposed1())
print(d.transposed2())
print(d.transposed3())
// [[1, 2, 3, 4, 5], ["A", "B", "C", "D", "E"], ["あ", "い", "う", "え", "お"], ["か", "き", "く", "け", "こ"]]
// [[1, "A", "あ", "か"], [2, "B", "い", "き"], [3, "C", "う", "く"], [4, "D", "え", "け"], [5, "E", "お", "こ"]]
// [[1, "A", "あ", "か"], [2, "B", "い", "き"], [3, "C", "う", "く"], [4, "D", "え", "け"], [5, "E", "お", "こ"]]
// [[1, "A", "あ", "か"], [2, "B", "い", "き"], [3, "C", "う", "く"], [4, "D", "え", "け"], [5, "E", "お", "こ"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment