How to create an M x N matrix with random numbers, if an element is 0 set its row and col to 0 in Java

1 Answer

0 votes
import java.util.Random;
import java.util.Arrays;
    
public class Example {
    public static void printMatrix(int[][] matrix) {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 4; j++) {        
                System.out.printf("%3d", matrix[i][j]);      
            }
            System.out.println();    
        }
        System.out.println();    
    }
    public static void setZeroes(int[][] matrix) {
       int rows = matrix.length , cols = matrix[0].length;
       
        int acol = 1;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = 0;
                    if (j != 0)
                        matrix[0][j] = 0;   
                    else
                        acol = 0;
                }
            }
        }
    
        for (int i = 1; i < rows; i++) {
            for (int j = 1; j < cols; j++) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0)
                    matrix[i][j] = 0;
            }
        }

        if (matrix[0][0] == 0)
            for (int j = 0; j < cols; j++) matrix[0][j] = 0;
        if (acol == 0)
            for (int i = 0; i < rows; i++) matrix[i][0] = 0;
    }
    private static int[][] createMtrixWithRandomNumbers(int rows, int cols) {
        int[][] randomMatrix = new int[rows][cols];
        Random rand = new Random(); 
        rand.setSeed(System.currentTimeMillis()); 
  
        for (int i = 0; i < rows; i++) {   
            for (int j = 0; j < cols; j++) {
                Integer num = rand.nextInt() % 10; 
                randomMatrix[i][j] = Math.abs(num);
            }
        }
        
        return randomMatrix;
    }
     
    public static void main(String[] args) {
        int[][] randomMatrix = createMtrixWithRandomNumbers(4, 5);
        
        printMatrix(randomMatrix);
        
        setZeroes(randomMatrix);
        
        printMatrix(randomMatrix);
    }
}
 
    
    
/*
run1:
     
  3  4  9  4
  9  1  9  5
  6  0  1  8

  3  0  9  4
  9  0  9  5
  0  0  0  0
  
run2:

  9  1  9  0
  9  6  8  9
  2  4  1  5

  0  0  0  0
  9  6  8  0
  2  4  1  0
 
*/

 



answered May 14, 2024 by avibootz
...