donqo88682 2015-11-21 20:50
浏览 40
已采纳

查找go中2D切片的长度

I want to check if the matrices are of the same size: if both matrices have the same number of rows and the same number of columns.

matrix1 := [][]int{{1,2,3} ,{4,5,6}}
matrix2 := [][]int{{7,8,9}, {10,11,12}}

I get len(matrix1) == len(matrix2) == 2. Which is the correct number of rows.

How can I check the length of each row (i.e. the number of columns, which should be 3) if I'm declaring the matrices as shown above?

  • 写回答

1条回答 默认 最新

  • dongli5785 2015-11-21 21:04
    关注

    Note that since every "row" in a 2D slice may have arbitrary length, you should check the length of each of the corresponding rows (having the same index) if they are equal.

    Here's a function that does that:

    func match(m1, m2 [][]int) bool {
        if len(m1) != len(m2) {
            return false
        }
    
        for i, row1 := range m1 {
            row2 := m2[i]
            if len(row1) != len(row2) {
                return false
            }
        }
    
        return true
    }
    

    See usage examples:

    m1 := [][]int{{1, 2, 3}, {4, 5, 6}}
    m2 := [][]int{{7, 8, 9}, {10, 11, 12}}
    fmt.Println(match(m1, m2))
    
    m1 = [][]int{{1, 2, 3}, {4, 5, 6, 7, 8}}
    m2 = [][]int{{7, 8, 9}, {10, 11, 12, 12, 13}}
    fmt.Println(match(m1, m2))
    
    m1 = [][]int{{1, 2, 3}, {4, 5, 6, 7, 8}}
    m2 = [][]int{{7, 8, 9}, {10, 11, 12, 12}}
    fmt.Println(match(m1, m2))
    
    m1 = [][]int{{1, 2, 3}}
    m2 = [][]int{{7, 8, 9}, {10, 11, 12, 12}}
    fmt.Println(match(m1, m2))
    

    Output (as expected):

    true
    true
    false
    false
    

    Simplification for Special case:

    If you have guarantee that in all of your matrices all rows have the same length, you can make a big simplification: in this case if number of rows matches, it's enough to compare the length of one of the rows only from each matrices, practically the first row.

    It could look like this:

    func match2(m1, m2 [][]int) bool {
        if len(m1) != len(m2) {
            return false
        }
        return len(m1) == 0 || len(m1[0]) == len(m2[0])
    }
    

    Testing it:

    m1 = [][]int{{1, 2, 3}, {4, 5, 6}}
    m2 = [][]int{{7, 8, 9}, {10, 11, 12}}
    fmt.Println(match2(m1, m2))
    
    m1 = [][]int{{1, 2, 3, 4}, {5, 6, 7, 8}}
    m2 = [][]int{{7, 8, 9}, {10, 11, 12}}
    fmt.Println(match2(m1, m2))
    

    Output:

    true
    false
    

    Try these on the <kbd>Go Playground</kbd>.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角