Help with java 2d arrays import javautilRandom public class
Help with java 2d arrays
import java.util.Random;
public class Matrix {
private static final Random rand = new Random(17);
// Create a matrix of size m x n filled with 0s
public static int[][] newMatrix(int m, int n) {
return new int[m][n];
}
// Create a matrix of size m x n
// that is filled with random numbers from [10,100)
public static int[][] newRandom(int m, int n) {
return null; // TODO
}
// Transpose matrix m1 and return the result.
public static int[][] transpose(int[][] matrix) {
return null; // TODO
}
// Multiplies matrix with scalar x and returns result
// No input validation is performed
public static int[][] multiply( int x, int[][] matrix ) {
return null; // TODO
}
// Adds two matrices and returns the result.
public static int[][] add( int[][] m1, int[][] m2) {
return null; // TODO
}
public static void printMatrix( int[][] matrix ) {
// TODO
// use nested foreach loops to print the matrix
// It should list each row in a separate line
// and all elements separated by a single blank (no brackets)
}
Solution
Matrix.java
import java.util.Random;
public class Matrix {
private static final Random rand = new Random(17);
// Create a matrix of size m x n filled with 0s
public static int[][] newMatrix(int m, int n) {
return new int[m][n];
}
// Create a matrix of size m x n
// that is filled with random numbers from [10,100)
public static int[][] newRandom(int m, int n) {
int a[][] = new int[m][n];
for(int i=0; i<m; i++){
for(int j=0;j<n;j++){
a[i][j] = rand.nextInt(100-10+1)+10;
}
}
return a; // TODO
}
// Transpose matrix m1 and return the result.
public static int[][] transpose(int[][] matrix) {
int transpose[][] = new int[matrix.length][matrix[0].length];
for ( int c = 0 ; c < matrix.length ; c++ )
{
for ( int d = 0 ; d < matrix[c].length ; d++ )
transpose[d][c] = matrix[c][d];
}
return transpose; // TODO
}
// Multiplies matrix with scalar x and returns result
// No input validation is performed
public static int[][] multiply( int x, int[][] matrix ) {
for(int i=0; i<matrix.length; i++){
for(int j=0;j<matrix[i].length;j++){
matrix[i][j] = matrix[i][j] * x;
}
}
return matrix; // TODO
}
// Adds two matrices and returns the result.
public static int[][] add( int[][] m1, int[][] m2) {
int a[][] = new int[m1.length][m1[0].length];
for(int i=0; i<a.length; i++){
for(int j=0;j<a[i].length;j++){
a[i][j] = m1[i][j] + m2[i][j];
}
}
return a; // TODO
}
public static void printMatrix( int[][] matrix ) {
// TODO
// use nested foreach loops to print the matrix
// It should list each row in a separate line
// and all elements separated by a single blank (no brackets)
for(int i=0; i<matrix.length; i++){
for(int j=0;j<matrix[i].length; j++){
System.out.print(matrix[i][j]+\" \");
}
System.out.println();
}
}
}

