Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- *
- * Lu Liu
- * 12/04/2015
- * CSCI-111-D01
- * Email: lliu0001@student.stcc.edu
- * Project:
- * Generate Even Number Ones Matrix V2
- * Description:
- * 1)Ask the user for the number of rows and the number of columns in the matrix
- * 2)Repeatedly randomly generate a matrix of ones and zeros with those dimensions
- * 3)Find the matrix that all rows and all columns have an even number of ones
- */
- import java.util.Scanner;
- public class EvenOnes {
- public static void main(String[] args) {
- final String TITLE = "Generate Even Number Ones Matrix";
- final String CONTINUE_PROMPT = "Do This Again?[y/N]";
- System.out.println("Welcome to " + TITLE);
- Scanner sc = new Scanner(System.in);
- System.out.println("Enter the number as rows: ");
- int rows = sc.nextInt();
- System.out.println("Enter the number as columns: ");
- int columns = sc.nextInt();
- int matrix[][] = new int[rows][columns];
- do {
- evenOnesMatrix(matrix);
- sc.nextLine();
- } while (doThisAgain(sc, CONTINUE_PROMPT));
- sc.close();
- System.out.println("\nThank you for using " + TITLE);
- }
- // ----------------------------------------------------------------------------
- private static boolean doThisAgain(Scanner sc, String prompt) {
- System.out.print(prompt);
- String doOver = sc.nextLine();
- return doOver.equalsIgnoreCase("Y");
- }
- // ----------------------------------------------------------------------------
- public static void evenOnesMatrix(int matrix[][]) {
- do {
- getRandomMatrix(matrix);
- System.out.println();
- } while (!hasEvenOnes(matrix));
- System.out.println("All rows and columns have even ones");
- }
- // ----------------------------------------------------------------------------
- public static int[][] getRandomMatrix(int[][] matrix) {
- for (int i = 0; i < matrix.length; i++) {
- for (int j = 0; j < matrix[i].length; j++) {
- matrix[i][j] = (int) (Math.random() * 2);
- System.out.print(matrix[i][j] + " ");
- }
- System.out.println();
- }
- return matrix;
- }
- // ----------------------------------------------------------------------------
- public static boolean hasEvenOnes(int matrix[][]) {
- for (int i = 0; i < matrix.length; i++) {
- int count = 0;
- for (int j = 0; j < matrix[i].length; j++) {
- if (matrix[i][j] == 1)
- count++;
- }
- if (count % 2 != 0)
- return false;
- }
- for (int j = 0; j < matrix[0].length; j++) {
- int count = 0;
- for (int i = 0; i < matrix.length; i++) {
- if (matrix[i][j] == 1)
- count++;
- }
- if (count % 2 != 0)
- return false;
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement