How to transpose a matrix (swap rows and columns) in Swift

3 Answers

0 votes
import Foundation

// using functional - map
func transpose<T>(_ matrix: [[T]]) -> [[T]] {
    guard let firstRow = matrix.first else { return [] }
    return firstRow.indices.map { col in
        matrix.map { row in row[col] }
    }
}

let matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

let t = transpose(matrix)
t.forEach { print($0.map(String.init).joined(separator: " ")) }


/*
run:

1 4 7
2 5 8
3 6 9

*/

 



answered 22 hours ago by avibootz
0 votes
import Foundation

// using loops
func transpose<T>(_ matrix: [[T]]) -> [[T]] {
    let rows = matrix.count
    let cols = matrix[0].count

    var result = Array(repeating: Array(repeating: matrix[0][0], count: rows), count: cols)

    for i in 0..<rows {
        for j in 0..<cols {
            result[j][i] = matrix[i][j]
        }
    }

    return result
}

let matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

let t = transpose(matrix)
t.forEach { print($0.map(String.init).joined(separator: " ")) }


/*
run:

1 4 7
2 5 8
3 6 9

*/

 



answered 22 hours ago by avibootz
0 votes
import Foundation

// using array‑of‑arrays with fixed types
func transpose(_ matrix: [[Int]]) -> [[Int]] {
    let rows = matrix.count
    let cols = matrix[0].count

    var result = Array(repeating: Array(repeating: 0, count: rows), count: cols)

    for i in 0..<rows {
        for j in 0..<cols {
            result[j][i] = matrix[i][j]
        }
    }

    return result
}

let matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

let t = transpose(matrix)
t.forEach { print($0.map(String.init).joined(separator: " ")) }



/*
run:

1 4 7
2 5 8
3 6 9

*/

 



answered 22 hours ago by avibootz
...