Exploring Matricies in Java

Problem:

Write a program that prompts the user to enter the length of a square matrix, randomly fills in 0s and 1s into the matrix, prints the matrix, and finds the rows, columns, and diagonals with all 0s or 1s.


Output:

Enter the size for the matrix: 4
1000
0111
0101
0100
No same numbers on a column
No same numbers on a row
No same numbers on the major diagonal
No same numbers on the sub-diagonal


Solution:

import java.util.Scanner;
public class ExploringMatrix
{
  public static void main (String[] args)
  {
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter the size for the matrix: ");
    int size = scan.nextInt();
    int[][] m = new int[size][size];
    
    for (int i =0;i<size;i++)
    {
      for (int j =0;j<size;j++)
      {
        m[i][j] = (int) (Math.random()*2);
        System.out.print(m[i][j]);
      }
      System.out.println();
    }
    boolean letitbe;
    //Row
    int j =0;
    
    boolean row=false, column=false, major =false, sub = false;
    for(int i=0; i<size;i++)
    {
      letitbe = true;
      for (j =0;j<size-1;j++)
      {
        if (m[i][j] != m[i][j+1]) letitbe = false;
      }
      if (letitbe)
      {
        System.out.println("All " + m[i][j] + "s on row " + i);
        row = true;
      }
    }
    //Column
    for(int i=0; i<size;i++)
    {
      letitbe = true;
      for (j =0;j<size-1;j++)
      {
        if (m[j][i] != m[j+1][i]) letitbe = false;
      }
      if (letitbe)
      {
        System.out.println("All " + m[j][i] + "s on column " + i);
        column = true;
      }
      
    }
    //Major diagonal, there is only one eh?
    letitbe = true;
    for (int  i=0;i<size-1;i++)
    {
      if (m[i][i]!= m[i+1][i+1]) letitbe = false;
    }
    if (letitbe)
    {
      System.out.println("All " + m[0][0] + "s on major diagonal");
      major = true;
    }
    
    letitbe = true;
    for (int  i=0;i<size-1;i++)
    {
      if (m[i][size-i-1]!= m[i+1][size-i-1-1]) letitbe = false;
    }
    if (letitbe)
    {
      System.out.println("All " + m[0][size-1] + "s on sub-diagonal");
      sub = true;
    }
  
    if ( column == false) System.out.println("No same numbers on a column");
    if ( row == false) System.out.println("No same numbers on a row");
    if ( major == false) System.out.println("No same numbers on the major diagonal");
    if ( sub == false) System.out.println("No same numbers on the sub-diagonal");
  }
}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact