user3030556
user3030556

Reputation:

Two Dimensional Matrix as Input

how to write two dimensional matrix as input and identifies the number with maximum number of occurrences in the matrix.

Example Input : 2 // no of rows 3 // no of columns 1 2 3 2 3 3 // here the matrix taken as input is 2 x 3 matrix. Remaining six numbers are values for the particular matrix. (elements in the first row are 1 2 3 and elements in the second row are 2 3 3)

Example output : 3

import java.util.*;

class ArrayOccurence
{
   public static void main(String args[])
   {
      Scanner sc = new Scanner(System.in);
      int row = sc.nextInt();
      sc.nextLine();
      int column = sc.nextInt();
      sc.nextLine();
      int element = 0;
      int occurence = 0;
      int arr[][] = new int[row][column]; // size of the array
      for(int i=0; i < row; i++)
      {
         for(int j=0; j < column ; j++)
            arr[i][j] = sc.nextInt();
      }
      //Do not modify the code above
      /* Enter your code here */
      // Do not modify code below
      System.out.println("Matrix element "+element+" occurs "+occurence+" times in the     matrix");
   }
}

Upvotes: 0

Views: 129

Answers (2)

luiscosta
luiscosta

Reputation: 855

Substitute your line which says Enter your code here with the following:

    ArrayList<Integer> a = new ArrayList<Integer>();
    int oc = 0;
    int number = 0;

    for(int i=0; i < row; i++)
    {
        for(int j=0; j < column ; j++){
            if(a.isEmpty()){
                a.add(arr[i][j]);
            }
            else if(a.contains(arr[i][j])){

                int temp=0;
                for(int k=0; k<a.size(); k++){
                    if(a.get(k) == arr[i][j]){
                        temp++;
                    }
                }
                if(temp > oc){
                    number = arr[i][j];
                    oc = temp;
                }

                a.add(arr[i][j]);
            }
            else{
                a.add(arr[i][j]);
            }
        }

    }

Hope this helps.

Upvotes: 0

Arkillon
Arkillon

Reputation: 49

You could use the double for loop again to count the occurence of each numbers:

for(int i=0; i < row; i++)
{
for(int j=0; j < column ; j++)
//count occurences with a HashMap<Integer,Integer> or something like that
}

Loop into your HashMap to find the one with most occurence..

Upvotes: 0

Related Questions