How to transpose a matrix of unequal array length in Swift 3

天涯浪子 提交于 2021-01-28 07:52:48

问题


My array is of type [[Int]]

array = [[1,2,3],
         [4,5,6],
         [7,8,9,10],
         [11,12,13],
         [14,15,16]]

I want the transpose result as:

array = [[1,4,7,11,14],
         [2,5,8,12,15],
         [3,6,9,13,16],
         [0,0,10,0,0]]

How to pad 0's to an array which does not have an equal row or column mapping.

I want the transpose to work for both rows and columns with unequal mapping elements. Please help.


回答1:


Here is an implementation that does what you want:

func transpose(_ input: [[Int]]) -> [[Int]] {
    let columns = input.count
    let rows = input.reduce(0) { max($0, $1.count) }

    var result: [[Int]] = []

    for row in 0 ..< rows {
        result.append([])
        for col in 0 ..< columns {
            if row < input[col].count {
                result[row].append(input[col][row])
            } else {
                result[row].append(0)
            }
        }
    }

    return result
}

Or, alternatively:

func transpose(_ input: [[Int]]) -> [[Int]] {
    let columns = input.count
    let rows = input.reduce(0) { max($0, $1.count) }

    return (0 ..< rows).reduce(into: []) { result, row in
        result.append((0 ..< columns).reduce(into: []) { result, column in
            result.append(row < input[column].count ? input[column][row] : 0)
        })
    }
}



回答2:


You should try this:

Swift 3

var array = [[1,2,3,4],[5,6,7,8],[9,10,11],[12,13,14]]
var arraytrans = [[Int]]()

override func viewWillAppear(_ animated: Bool)
{
    for i in stride(from: 0, to: array.count, by: 1)
    {
        var subArray = [Int]()
        for j in stride(from: 0, to: array.count, by: 1)
        {
            if array[i].count < array.count
            {
                array[i].append(0)
            }
            subArray.append(array[j][i])
        }
        arraytrans.append(subArray)
    }
    print(self.arraytrans) 
}



回答3:


Thanks..! @Pragnesh Vitthani I just modified your answer.

var array = [[1,2,3],
             [4,5,6],
             [7,8,9,10],
             [11,12,13],
             [14,15,16]]

var transposedArray = [[Int]]

for i in stride(from: 0, to: array.count, by: 1)
{
    var subArray = [Int]()
    for j in stride(from: 0, to: array.count, by: 1)
    {
        if array[j].count < array.count
        {
            array[j].append(0)
        }
        subArray.append(array[j][i])
    }
    transposedArray.append(subArray )
}
print(transposedArray)


来源:https://stackoverflow.com/questions/45412684/how-to-transpose-a-matrix-of-unequal-array-length-in-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!