题解 | #矩阵乘法#

矩阵乘法

https://www.nowcoder.com/practice/ebe941260f8c4210aa8c17e99cbc663b

import java.util.Scanner

fun main(args: Array<String>) {
    val read = Scanner(System.`in`)
    val x = read.nextLine().toInt()
    val y = read.nextLine().toInt()
    val z = read.nextLine().toInt()
    val a = Array(x) {
        Array(y) {
            0
        }
    }
    val b = Array(y) {
        Array(z) {
            0
        }
    }
    val c = Array(x) {
        Array(z) {
            0
        }
    }
    for (i in 0 until x) {
        val ys = read.nextLine().split(' ').map {
            it.toInt()
        }
        ys.forEachIndexed { index, s ->
            a[i][index] = s
        }
    }
    for (i in 0 until y) {
        val ys = read.nextLine().split(' ').map {
            it.toInt()
        }
        ys.forEachIndexed { index, s ->
            b[i][index] = s
        }
    }
    for (i in 0 until x) {
        for(j in 0 until z) {
            var sum =0
            for(k in 0 until y) {
               sum += a[i][k] * b[k][j]
            }
            c[i][j] = sum
        }
    }
    c.forEach { its ->
        its.forEach {
            print("$it ")
        }
        println()
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务