Go 语言程序判断给定矩阵是否为稀疏矩阵
在本教程中,我们将编写一个 Go 语言程序来确定给定的矩阵是否为稀疏矩阵。如果矩阵中存在的零元素数量多于非零元素的数量,则称方阵为稀疏矩阵。
Go 语言程序检查矩阵是否为稀疏矩阵
在本例中,我们将编写一个 Go 语言程序来检查稀疏矩阵。我们将在程序的主体部分使用 for 循环以及 if 条件来实现结果。
算法
步骤 1 − 首先,我们需要导入 fmt 包。
步骤 2 − 然后开始 main() 函数。在 main() 中初始化变量。
步骤 3 − 现在,初始化一个矩阵并向其中存储值。此外,在屏幕上打印此矩阵。
步骤 4 − 使用 len() 函数将矩阵的行数和列数存储在 rows 和 cols 变量中。
步骤 5 − 使用 for 循环遍历矩阵的每个元素,并检查当前元素是否为零。如果元素为零,则递增 count 变量。
步骤 6 − 现在,如果 count 的值超过矩阵中元素的一半,则打印矩阵为稀疏矩阵,否则打印矩阵不是稀疏矩阵。
步骤 7 − 通过初始化另一个矩阵重复此过程。
示例
package main
import "fmt"
func main() {
// initializing variables
var i, j int
var count int = 0
matrixA := [3][3]int{
{0, 1, 2},
{4, 0, 0},
{0, 0, 0},
}
var rows int = len(matrixA)
var cols int = len(matrixA[0])
// printing matrix
fmt.Println("The first matrix is:")
for i = 0; i < rows; i++ {
for j = 0; j < cols; j++ {
fmt.Print(matrixA[i][j], "\t")
}
fmt.Println()
}
// checking if matrix is a sparce matrix
for i = 0; i < rows; i++ {
for j = 0; j < cols; j++ {
if matrixA[i][j] == 0 {
count++
}
}
}
if count > (rows*cols)/2 {
fmt.Println("The above matrix is a sparce matrix")
} else {
fmt.Println("The given matrix is not sparce")
}
fmt.Println()
// initializing another matrix
matrixB := [3][3]int{
{0, 11, 12},
{13, 0, 15},
{16, 0, 18},
}
count = 0
rows = len(matrixB)
cols = len(matrixB[0])
fmt.Println("The second matrix is:")
for i = 0; i < rows; i++ {
for j = 0; j < cols; j++ {
fmt.Print(matrixB[i][j], "\t")
}
fmt.Println()
}
fmt.Println()
for i = 0; i < rows; i++ {
for j = 0; j < cols; j++ {
if matrixB[i][j] == 0 {
count++
}
}
}
if count > (rows*cols)/2 {
fmt.Println("The above matrix is a sparce matrix")
} else {
fmt.Println("The above matrix is not sparce")
}
}
输出
The first matrix is: 0 1 2 4 0 0 0 0 0 The above matrix is a sparce matrix The second matrix is: 0 11 12 13 0 15 16 0 18 The above matrix is not sparce
结论
我们已经成功编译并执行了一个 Go 语言程序来检查给定的矩阵是否为稀疏矩阵,并附带示例。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP