Skip to main content

Find the number of negative integers from row wise or column wise from a sorted matrix

Find the number of negative integers from row wise or column wise from a sorted matrix
This is a frequently asked question for a experienced interview.
Here i am trying to solve this in two different ways, normal way and an optimised method.

Main Class

/**
 * 
 */
package com.rakesh.matrix.bo;

/**
 * @author Rakesh KR
 * @since  August 19th 13:15 2k17
 */
public class RunMatrix {

 public static void main(String[] args) {
  
  MatrixUtils matrixUtils = new MatrixUtils();
  
  try{
   
   System.out.println("------ Matrix ------");
   
   matrixUtils.makeMartix();
  // matrixUtils.printMatrix();
   
   matrixUtils.sortRowMatrix();
   matrixUtils.transpose();
   matrixUtils.sortRowMatrix();
   matrixUtils.transpose(); 
  // matrixUtils.printMatrix();
   
   long t1 = System.currentTimeMillis();
   System.out.println("NegativeNumbers Count Normal    Way : "+matrixUtils.countNegativeNumbersNormal());
   long t2 = System.currentTimeMillis();
   System.out.println("Time for Normal Way :"+(t2-t1)+" ms");
   t1 = System.currentTimeMillis();
   System.out.println("NegativeNumbers Count Optimized Way : "+matrixUtils.countNegativeNumbersOptimized());
   t2 = System.currentTimeMillis();
   System.out.println("Time for Optimized Way :"+(t2-t1)+" ms");
   
  } catch(Exception e){
   e.printStackTrace();
  } finally{
   matrixUtils = null;
  }

 }

}


Sub Class

/**
 * 
 */
package com.rakesh.matrix.bo;

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

/**
 * @author Rakesh KR
 * @since  August 19th 13:17 2k17
 */
public class MatrixUtils {
 
 public int m;
 public int n;
 public int[][] matrix;
 
 public void makeMartix(){
  
  Scanner sc = new Scanner(System.in);
  
  try{
   System.out.println("Size Of Matrix (mxn) : ");
   n = sc.nextInt();
   m = sc.nextInt();
   matrix = new int[n][m];
  // System.out.println("Enter the details to matrix : ");
   int    max    = 99;
   int    min    = -99;
   Random random = new Random();
   for(int i=0; i<n; i++){
    for(int j=0; j<m; j++){
  //   matrix[i][j] = sc.nextInt();
     matrix[i][j] = random.nextInt(max + 1 -min) + min; 
    }
   }
  } catch(Exception e){
   e.printStackTrace();
  } finally{
   sc.close();
  }
  
 }
 
 public void printMatrix(){
  
  try{
   System.out.print("The matrix is : \n");
   for(int i=0; i<n; i++){
    for(int j=0; j<m; j++){
     System.out.print(" "+matrix[i][j]+" ");
    }
    System.out.print("\n");
   }
   System.out.print("\n");
  } catch(Exception e){
   e.printStackTrace();
  } finally{
   
  }
  
 }
 
 public void sortRowMatrix(){
  
  try{
   for(int i=0; i<matrix.length; i++){
    Arrays.sort(matrix[i]);
   }
  } catch(Exception e){
   e.printStackTrace();
  } finally{
   
  }
  
 }
 
 public void transpose(){
     for (int i = 0; i < matrix.length; i++) {
         for (int j = i; j < matrix[0].length; j++) {
             int tmp1 = matrix[i][j];
             int tmp2 = matrix[j][i];
             matrix[j][i] = tmp1;
             matrix[i][j] = tmp2;
         }
     }
 }
 
 public int countNegativeNumbersNormal(){
  
  int count = 0;
  
  try{
   for(int i=0; i<n; i++){
    for(int j=0; j<m; j++){
     if(matrix[i][j]<0){
      count ++;
     }
    }
   }
  } catch(Exception e){
   e.printStackTrace();
  } finally{
   
  }
  
  return count;
 }
 
 public int countNegativeNumbersOptimized(){
  
  int count = 0;
  
  try{
   int i = 0;
   int j = m-1;
   while(j>=0 && i<n){
    if(matrix[i][j]<0){
     count+=(j+1);
     i+=1;
    } else{
     j-=1;
    }
   }
  } catch(Exception e){
   e.printStackTrace();
  } finally{
   
  }
  
  return count;
 }
 
}

Methods:

makeMartix()
This method is used to make a random matrix which consists of positive and negative vales. 
Having min value as -99 and max value as 99.
printMatrix()
This method is used to print an mxn matrix in a user readable manner.
sortRowMatrix()
This method is used to sort an mxn matrix.
transpose()
This method is used to find the transpose of an mxn matrix.
countNegativeNumbersNormal()
An normal way to count the negative numbers from an mxn matrix. 
Its having an 0(n^2) complexity. 
countNegativeNumbersOptimized()
An optimized way to count the negative numbers from an mxn sorted matrix. 

Some tested Results : 
With an 2x2 matrix  :-
------ Matrix ------
Size Of Matrix (mxn) : 
2 2
The matrix is : 
 -53  40 
 -57  10 

The matrix is : 
 -57  10 
 -53  40 

NegativeNumbers Count Normal    Way : 2
Time for Normal Way :0 ms
NegativeNumbers Count Optimized Way : 2
Time for Optimized Way :0 ms

With an 100x100 matrix  :-

------ Matrix ------
Size Of Matrix (mxn) : 
100 100
NegativeNumbers Count Normal    Way : 4906
Time for Normal Way :1 ms
NegativeNumbers Count Optimized Way : 4906
Time for Optimized Way :0 ms

With an 5000x5000 matrix  :-

------ Matrix ------
Size Of Matrix (mxn) : 
5000 5000
NegativeNumbers Count Normal    Way : 12438372
Time for Normal Way :27 ms
NegativeNumbers Count Optimized Way : 12438372
Time for Optimized Way :1 ms

With an 10000x10000 matrix  :-

------ Matrix ------
Size Of Matrix (mxn) : 
10000 10000
NegativeNumbers Count Normal    Way : 49745496
Time for Normal Way :88 ms
NegativeNumbers Count Optimized Way : 49745496
Time for Optimized Way :2 ms

Comments

  1. Advertise what you do with a Home service websites templates from TemplateMonster. Easily customize using our drag-and-drop feature.

    ReplyDelete

Post a Comment

Popular posts from this blog

ജാവാ വളരെ സിമ്പിൾ ആണ് , പവർഫുൾ ഭയങ്കര പവർഫുൾ ആണ്.

ജാവ യെ  കുറിച്ച്  മലയാളത്തിൽ  ഡോകുമെന്റുകളോ  ബ്ലോഗ്‌കളോ  കൂടുതൽ ഇല്ലാത്തതുകൊണ്ട് എനികറിയവുന്നത് ഷെയർ ചെയ്യാം എന്ന് വിചാരിച്ചു .  ജവയെ കുറിച്ച് പറയുകയാണെങ്കിൽ  ജാവാ വളരെ സിമ്പിൾ ആണ് , പവർഫുൾ  ഭയങ്കര പവർഫുൾ ആണ്. :) 1. നമ്മടെ Sun MicroSystems 1995 ൽ തുടങ്ങി വച്ചാ സംഭവമാണിത് . 2. ഇപ്പൊ ജാവയുടെ എട്ടാമത്തെ വെർഷൻ  വരെ ഇറങ്ങികഴിഞ്ഞു . ജാവയുടെ തിയറിയെ കുറിച്ച് എനിക്ക് പറയാൻ താല്പര്യം  ഇല്ലാ, അത് അറിവിള്ളവർ നല്ലപോലെ പറഞ്ഞിടുണ്ട്. നമുക്ക് ഡയറക്റ്റ്  ആയി കോഡിംഗ് പാർട്ടിലേക്ക്  പോകാം. എങ്ങനെയാ ജാവ ഇൻസ്റ്റോൾ ചെയണ്ടേ എന്നൊക്കെ ഒന്ന് ഗൂഗിൾനോട് ചോദിച്ചാ മതി പുള്ളി പറഞ്ഞുതരും. പിന്നെ എല്ലാവരും പറയുന്നു ജാവാ Object  Oriented ആണെന്ന് . അതെ ജാവാ Object Oriented ആണ് . എന്താണ് Object ?, Object  നു വച്ചാ ഒരു സാധനം അത്രതന്നെ. ഇപ്പൊ example പറയുകയാണെങ്കിൽ Book ഒരു സാധനമാണ് . Book റ്റെ പ്രതേകത എന്തൊക്കെ അന്നെന്നുവച്ചാ ആതിനൊരു Auther ഉണ്ടാകും, അതൊരു Category ൽ പെട്ട book ആയിരിക്കും (Novel / Academic ) പിന്നെ ഓരോ bookനും അ...

Transform Ubuntu into Xubuntu

Installation 1. Open the terminal by Ctrl+Alt+T     and type    sudo apt-get install xubuntu-desktop gksu leafpad synaptic         2. Type your password & Press Enter. Now an intensive operation is being launched. Simply wait to complete the whole process. Login To Xubuntu 1. After completing the installation logout ubuntu. Note: logout not restart or shutdown. 2. In the login window click on the ubuntu logo, next to your userName & select Xubuntu Sesion 3. Enter your password and Now the Xubuntu desktop appears. :) The next thing is to clean up. Clean Up 1. Now its time to clean up, inorder to prevent system pollution problems. Note: The clean up will remove as much as possible ubuntu's desktop environment Unity. So after that you can't use Unity. 2. Open terminal by Ctrl+Alt+T and type the following  sudo apt-get remove nautilus gnome-power-manager gnome-screensaver gnome-termina*...

Object serialization in java

Serialization is the conversion of an object to a series of bytes, so that the object can be easily saved to persistent storage or streamed across a communication link. The byte stream can then be deserialized - converted into a replica of the original object. When you want to serialize an object, that respective class should implement the marker interface serializable. It just informs the compiler that this java class can be serialized. You can tag properties that should not be serialized as transient. You open a stream and write the object into it. Code for serialization of a java class : Data.java package com . codetalk . serialization ; import java.io.Serializable ; public class Data implements Serializable { private static final long serialVersionUID = 1L; private String firstName ; private String lastName ; /** * @return the firstName */ public String getFirstName () { return firstName ; } /** * @param firstNam...