Kotlin program to check sparse matrix

Kotlin | Sparse Matrix: Here, we are going to learn how to check given matrix is a sparse matrix or not in Kotlin programming language? Submitted by IncludeHelp, on May 06, 2020

Kotlin - Check sparse matrix

Given a matrix, we have to check whether it is a sparse matrix or not.

Example:

Input:
matrix:
[1, 0, 6]
[0, 0, 7]
[0, 3, 0]

Output:
Sparse Matrix !!

Program to check sparse matrix in Kotlin

package com.includehelp

import java.util.*

// Main function, Entry Point of Program
fun main(args: Array<String>) {

    //variable of rows and col
    val rows: Int
    val column: Int

    var noOfZeroElements=0
    var totalElementsInMatrix: Int

    //Input Stream
    val scanner = Scanner(System.`in`)

    //Input no of rows and column
    print("Enter the number of rows and columns of matrix : ")
    rows   = scanner.nextInt()
    column = scanner.nextInt()

    //no of Elements in matrix
    totalElementsInMatrix = rows*column

    //Create Array
    val matrixA     = Array(rows) { IntArray(column) }

    //Input Matrix
    println("Enter the Elements of First Matrix ($rows X $column} ): ")
    for(i in matrixA.indices){
        for(j in matrixA[i].indices){
            print("matrixA[$i][$j]: ")
            matrixA[i][j]=scanner.nextInt()

            //if value is zero then increase count by 1
            if(matrixA[i][j]==0) noOfZeroElements++
        }
    }

    //print Matrix A
    println("Matrix A : ")
    for(i in matrixA.indices){
        println("${matrixA[i].contentToString()} ")
    }

    //determine Zero noOfElements greater then Half of Total Elements
    if( noOfZeroElements>(totalElementsInMatrix/2) ) println("Sparse Matrix !! ") else println("Not a Sparse Matrix !!")
}

Output

Run 1:
Enter the number of rows and columns of matrix : 3
3
Enter the Elements of First Matrix (3 X 3} ):
matrixA[0][0]: 1
matrixA[0][1]: 0
matrixA[0][2]: 6
matrixA[1][0]: 0
matrixA[1][1]: 0
matrixA[1][2]: 7
matrixA[2][0]: 0
matrixA[2][1]: 3
matrixA[2][2]: 0
Matrix A :
[1, 0, 6]
[0, 0, 7]
[0, 3, 0]
Sparse Matrix !!
--------
Run 2:
Enter the number of rows and columns of matrix : 3
4
Enter the Elements of First Matrix (3 X 4} ):
matrixA[0][0]: 3
matrixA[0][1]: 0
matrixA[0][2]: 9
matrixA[0][3]: 8
matrixA[1][0]: 0
matrixA[1][1]: 5
matrixA[1][2]: 0
matrixA[1][3]: 3
matrixA[2][0]: 1
matrixA[2][1]: 0
matrixA[2][2]: 0
matrixA[2][3]: 7
Matrix A :
[3, 0, 9, 8]
[0, 5, 0, 3]
[1, 0, 0, 7]
Not a Sparse Matrix !!

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.