Count Element In Row And Column Wise Sorted Matrix

package org.wesome.dsalgo;

public class SortedMatrixCount {
    public static int sortedMatrixCount(int[][] matrix, int dimension, int find) {

        int count = 0;
        int row = 0, col = dimension - 1;
        while (row < dimension && col >= 0) {
            if (matrix[row][col] == find) {
                System.out.println(find + " is present  at [" + row + "][" + col + "]");
                count++;
            }
            if (matrix[row][col] > find) {
                System.out.println(find + " is less then last element " + matrix[row][col] + " at [" + row + "][" + col + "], hence decrementing colum");
                col--;
            } else {
                System.out.println(find + " is greater then last element " + matrix[row][col] + " at [" + row + "][" + col + "], hence incrementing row");
                row++;
            }
        }
        System.out.println(find + " is present " + count + " times");
        return count;
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import static org.wesome.dsalgo.SortedMatrixCount.sortedMatrixCount;


public class SortedMatrixCountTest {
    @Test
    void sortedMatrixCountTest1() {
        int dimension = 4;
        int[][] arr = {{-4, -3, -1, 3},
                {-3, -2, 2, 4},
                {-1, 1, 3, 5},
                {3, 4, 7, 8}};
        int find = 3;
        Assertions.assertEquals(3, sortedMatrixCount(arr, dimension, find));
    }
}
plugins {
    id 'java'
    id "io.freefair.lombok" version "6.2.0"
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

follow us on