Golang程序 判断给定矩阵是否为稀疏矩阵

在本教程中,我们将编写一个go语言程序来确定一个给定的矩阵是否是稀疏的。如果一个正方形矩阵中存在的零数多于矩阵中的非零元素,则称为稀疏矩阵。

判断矩阵是否为稀疏的Golang程序

在这个例子中,我们将写一个Golang程序来检查sparce矩阵。我们将在程序的主要部分使用for循环和if条件来实现结果。

算法

第1步 – 首先,我们需要导入fmt包。

第2步 – 然后启动main()函数。在main()中初始化各变量。

第3步 – 现在,初始化一个矩阵,并向其存储数值。此外,在屏幕上打印这个矩阵。

第4步 – 使用len()函数将矩阵的行数和列数存储在rows和cols变量中。

第5步 – 使用for循环遍历矩阵的每个元素,并检查当前元素是否为零。如果该元素为零,则递增计数变量。

第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语言程序,以检查一个给定的矩阵是否是稀疏的,并附有例子。