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>.

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

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?