Matrix Multiplication using different classes - Java - java

I have this assignment for my class where I have to create a Matrix Multiplication program. Here's the condition:
Implement two types of algorithms for multiplying two n × n matrices. Assume n is a power of 2:
The straight-forward O(n^3) matrix multiplication algorithm.
Strassen’s matrix multiplication algorithm.
Evaluate your different algorithms, and write a short report. Create test matrices for different values of n (4, 10, 20,100). Generate matrices using random numbers. Compute the running time of your algorithms. Your report should include the running times and conclusions.
Here's my code so far:
public class MatrixMultiplication
{
public static void main(String[] args)
{
Random rand = new Random();
int rows = rand.nextInt(7) + 2;
int columns = rand.nextInt(7) + 2;
System.out.println("The matrix has " + rows + " randomized rows");
System.out.println("The matrix has " + columns + " randomized column");
System.out.println();
double[][] a = new double[rows][columns];
double[][] b = new double[columns][rows];
System.out.println("The first matrix has the values: ");
Matrix m1 = new Matrix(a);
System.out.println("---------------------------------");
System.out.println("The second matrix has the values: ");
Matrix m2 = new Matrix(b);
System.out.println();
Matrix productRegular = m1.multiply(m2);
}
}
And here's my other class:
import java.util.Random;
class Matrix
{
double[][] arrayA;
double[][] arrayB;
private Matrix(double[][] a, double[][] b)
{
arrayA = a;
arrayB = b;
}
public Matrix(double[][] array) //Create matrix values
{
Random rand = new Random();
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
array[i][j] = rand.nextInt(10);
System.out.print(array[i][j] + " | ");
}
System.out.println();
}
}
public double multiply(double[][] a, double[][] b)
{
double[][] c = new double[a.length][b[0].length];
System.out.println("Product of A and B is");
for(int i = 0; i < a.length; i++)
{
for(int j = 0; j < b[0].length; j++)
{
for(int k = 0; k < a[0].length; k++)
{
c[i][j] += a[i][k] * b[k][j];
System.out.println(c[i][j] + " | ");
}
}
System.out.println();
}
return c;
}
}
I know I have to pass an object/Matrix for the multiply method, but how would I do that? There are other concerns in my code, but I want to focus on passing objects right now.

Let's take a deep look to your code:
Why do you have two double[][] inside the Matrix class? A Matrix is just one bidimensional array. You should delete the arrayB
double[][] arrayA;
double[][] arrayB;
What's the point of the private constructor? For you, it is useless right now.
private Matrix(double[][] a, double[][] b)
{
arrayA = a;
arrayB = b;
}
In the public constructor, you are printing a Matrix, but you are not saving anywhere.
public Matrix(double[][] array) //Create matrix values
{
Random rand = new Random();
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
array[i][j] = rand.nextInt(10);
System.out.print(array[i][j] + " | ");
}
System.out.println();
}
arrayA = array;
}
Anyway, I think it would be much better to make 2 constructors
public Matrix(double[][] array) //you just pass an array created outside the class
{
arrayA = array;
}
public Matrix(int rows, int columns) //Create matrix values
{
double[][] array = new double [rows][columns];
Random rand = new Random();
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
array[i][j] = rand.nextInt(10);
System.out.print(array[i][j] + " | ");
}
System.out.println();
}
arrayA = array;
}
Why your multiply method have 2 parameters? As it is inside the class Matrix (that have a double[][]variable). You only need a parameter (I think it is better to your example to have a Matrix parameter instead of a double[][]parameter and return also a Matrix).
I don't like printing when you are creating or multiplying. It's much better to create a method to print the Matrix, and calling it when you want to print them.
So....the final code would be something like this:
Main
public class MatrixMultiplication
{
public static void main(String[] args)
{
Random rand = new Random();
int rows = rand.nextInt(7) + 2;
int columns = rand.nextInt(7) + 2;
System.out.println("The matrix has " + rows + " randomized rows");
System.out.println("The matrix has " + columns + " randomized column");
System.out.println();
System.out.println("The first matrix has the values: ");
Matrix m1 = new Matrix(rows,columns);
m1.print();
System.out.println("---------------------------------");
System.out.println("The second matrix has the values: ");
Matrix m2 = new Matrix(columns, rows);
m2.print();
System.out.println();
System.out.println("Product of A and B is");
Matrix productRegular = m1.multiply(m2);
productRegular.print();
}
}
Matrix Class
import java.util.Random;
class Matrix
{
double[][] arrayA;
public Matrix(double[][] array) //Create matrix values
{
arrayA=array;
}
public Matrix(int rows, int columns) //Create matrix values
{
double[][]array= new double[rows][columns];
Random rand = new Random();
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < array[i].length; j++)
{
array[i][j] = rand.nextInt(10);
}
}
arrayA=array;
}
public Matrix multiply(Matrix m)
{
double[][]b=m.arrayA;
double[][] c = new double[arrayA.length][b[0].length];
for(int i = 0; i < arrayA.length; i++)
{
for(int j = 0; j < b[0].length; j++)
{
for(int k = 0; k < arrayA[0].length; k++)
{
c[i][j] += arrayA[i][k] * b[k][j];
}
}
}
return new Matrix(c);
}
public void print(){
for(int i=0;i<arrayA.length;i++){
for(int j=0;j<arrayA[0].length;j++){
System.out.print(arrayA[i][j] + " | ");
}
System.out.println();
}
}
}

Related

is there any way to simplify my code for matrix multiplication?

public class J1_LAB08_1 {
public static void main(String[] args) {
int r1 = 5, c1 = 3;//rows and column for matrix a
int r2 = 3, c2 = 4;//rows and column for matrix b
int matrixA[][] = new int[5][3];//initialize matrix a
System.out.println("Matrix A");
for (int i = 0; i < matrixA.length; i++) {
for (int j = 0; j < matrixA[i].length; j++) {//create random single integer matrix
matrixA[i][j] = ((int) (Math.random() * 10));
System.out.print(matrixA[i][j]);//print matrix a
}
System.out.println();
}
System.out.println();
System.out.println("Matrix B");
int matrixB[][] = new int[3][4];
for (int i = 0; i < matrixB.length; i++) {
for (int j = 0; j < matrixB[i].length; j++) {//create random single integer matrix
matrixB[i][j] = ((int) (Math.random() * 10));
System.out.print(matrixB[i][j]);//print matrix b
}
System.out.println();
}
System.out.println();
int[][] matrixC = multiplyMatrices(matrixA, matrixB, r1, c1, c2);//pass variables to multiply matrices function
printC(matrixC);//print matrix c
}
public static int[][] multiplyMatrices(int[][] matrixA, int[][] matrixB, int r1, int c1, int c2){//multiply the 2 given matrices and return the product
int[][] matrixC = new int[r1][c2];//initialize the product matrix using row a and column 2 as its parameters
for(int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
for (int k = 0; k < c1; k++) {
matrixC[i][j] += matrixA[i][k] * matrixB[k][j];//multiply using textbook formula
}
}
}
return matrixC;
}
public static void printC(int[][] matrixC) {//print the matrix
System.out.println("A x B is: ");
for(int[] row : matrixC) {
for (int column : row) {
System.out.print(column + " ");
}
System.out.println();
}
}
}
is there any way to simplify my code for matrix multiplication?
the resulting matrix should be 3 x 5 after multiplication
any help would be greatly appreciated, thank you for your time and consideration.

How do I add two different arrays and print the result?

I had to make an array that counted the seating in a movie theater, the second class m2 represents another showtime. I do not know how to add both arrays together and print the result of the sum of these two arrays.
This the MovieSeats tester file:
public class MovieSeatsTester
{
public static void main(String[] args)
{
MovieSeats m = new MovieSeats(3,3);
MovieSeats m2 = new MovieSeats(3,3);
m.seating(0,0);
m.seating(0,1);
m.seating(1,0);
m.seating(2,2);
m.seating(2,2);
m2.seating(0,0);
m2.seating(0,0);
m.print();
m.reset();
m2.print();
m2.reset();
}
}
This is the MovieSeats file:
public class MovieSeats
{
private int attendance[][];
public MovieSeats()
{
}
public MovieSeats(int rows, int columns)
{
attendance = new int[rows][columns];
}
public void seating(int r, int c)
{
attendance[r][c] += 1;
}
public void print()
{
for (int r = 0; r < attendance.length; r++)
{
for (int c = 0; c < attendance.length; c++)
{
System.out.println("At row " + r + " col " + c + ", There are " + attendance[r][c] + " Sitting here.");
}
}
System.out.println();
}
public void reset()
{
for (int r = 0; r < attendance.length; r++)
{
for (int c = 0; c < attendance.length; c++)
{
attendance[r][c] = 0;
}
}
System.out.println();
}
}
I assume that by "add two different arrays" you mean "create a third array where each element in the third array is the sum of the corresponding element of each of the first two arrays."
1. Access Each Array
In order to add the two arrays together, you would first need access to each array somehow. Since the attendance field is private, you should add a getter method for it to the MovieSeats class.
Get attendance without encapsulation:
public int[][] getAttendance() {
return attendance;
}
Get attendance with encapsulation:
public int[][] getAttendance() {
int rows = attendance.length();
int cols = attendance[0].length();
int[][] copy = new int[rows][cols];
for(int i = 0; i < rows; i++)
for(int j = 0; j < cols; j++)
copy[i][j]=current[i][j];
return copy;
}
2. Add Two Arrays Element-Wise
Next, once you have access to both arrays in the same place (probably inside your main), you would then have to add them together. I would recommend putting the result in a third array. The most rudimentary way of adding these two arrays is the following:
int[][] attendance1 = m.getAttendance();
int[][] attendance2 = m2.getAttendance();
int[][] sum = new int[3][3];
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
sum[i][j] = attendance1[i][j] + attendance2[i][j];
Then, you could print the total attendance by seat with the following:
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
System.out.printf("Total Attendance for seat (%d,%d): %d\n",
i, j, sum[i][j]);
Now, if instead what you want to do is to sum all of the elements of both arrays into a single value, then you would do the following.
Sum An Array
int sum = 0;
int[][] attendance1 = m.getAttendance();
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
sum += attendance1[i][j];
int[][] attendance2 = m2.getAttendance();
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
sum += attendance2[i][j];
You can add the following method to the MovieSeat class:
public int sum() {
int result = 0;
for (int r = 0; r < attendance.length; r++) {
for (int c = 0; c < attendance.length; c++) {
result += attendance[r][c];
}
}
return result;
}
And the call the sum method and find the total sum in the main method:
MovieSeats m = new MovieSeats(3, 3);
MovieSeats m2 = new MovieSeats(3, 3);
m.seating(0, 0);
m.seating(0, 1);
m.seating(1, 0);
m.seating(2, 2);
m.seating(2, 2);
m2.seating(0, 0);
m2.seating(0, 0);
m.print();
System.out.println("sum: " + m.sum());
System.out.println("---");
m2.print();
System.out.println("sum: " + m2.sum());
System.out.println("total sum: " + (m.sum() + m2.sum()));
m.reset();
m2.reset();
Note to reset after you call the sum method.

finding cofactor and determinant of a 3x3 matrix (java)

I computed the product, sum, and transpose(of product), but I have no clue where to start on the cofactor and determinent of the product matrix.
Ive seen a couple examples but none that resemble my particular code so if anyone could show me how i could incorporate these two methods into my program I'd high appreciate it.
please dont ask me what i've tried because as I stated I am clueless at the moment
//here is the code I wrote for the product:
package programEx;
import java.io.*;
import java.util.*;
import java.io.File.*;
import java.util.Scanner;
public class progEx {
public static void main(String[] args) {
//Establishing Input Stream
Scanner s = new Scanner(System.in);
System.out.print("Enter number of rows in A: ");
int rowsInA = s.nextInt();
System.out.print("Enter number of columns in A / rows in B: ");
int columnsInA = s.nextInt();
System.out.print("Enter number of columns in B: ");
int columnsInB = s.nextInt();
int[][] a = new int[rowsInA][columnsInA];
int[][] b = new int[columnsInA][columnsInB];
//Taking user input for 1st matrix
System.out.println("Enter matrix A");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
a[i][j] = s.nextInt();
}
}
//Taking user input for 2nd matrix
System.out.println("Enter matrix B");
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[0].length; j++) {
b[i][j] = s.nextInt();
}
}
//calling the multiplication method and passing it to both matrices
int[][] c = multiply(a, b);
System.out.println("Product of A and B is");
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < c[0].length; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
//Separate method for the multiplication of 1st and 2nd matrices
public static int[][] multiply(int[][] a, int[][] b) {
int rowsInA = a.length;
int columnsInA = a[0].length;
int columnsInB = b[0].length;
int[][] c = new int[rowsInA][columnsInB];
for (int i = 0; i < rowsInA; i++) {
for (int j = 0; j < columnsInB; j++) {
for (int k = 0; k < columnsInA; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
return c;
}
}
Well,a 3*3 matrix has 3 columns and 3 rows to begin with.
Each starts with an index 0.
Determinant can be calculated as:
int d=determinant();
int determinant()
{
int x=a[0][0]*((a[1][1]*a[2][2])-(a[2][1]*a[1][2]));
int y=-a[0][1]*((a[0][1]*a[2][2])-(a[2][0]*a[1][2]));
int z=a[0][2]*((a[1][0]*a[2][1])-(a[1][1]*a[2][0]));
int r=x+y+z;
return r;
}
This is only for finding the determinant of a 3*3 matrix.

Printing two 2D Arrays Next to Each Other

So I've been fiddling around with 2D arrays in java. I am practicing by using the arrays as matrices. I create 2 Matrix objects, which have a myMatrix 2D array field. In the main method, I call the first Matrix object to add itself to the second matrix if it is possible, through the addMatrix method. I have a printResultDetail method to actually print out what is happening. I want the first object's myMatrix to print out with rows and columns properly formatted. Then I want the second object's myMatrix object to print out on the right of the previous. I then want the new output matrix, given by the first object's myResultMatrix 2D array, to printed out again to the right.
How do I make the arrays print out side by side?
Note: the printResultDetail is incorrect. I was just trying to figure out how to do it.
import java.util.Arrays;
import java.util.Random;
public class Matrix {
int[][] myMatrix;
int[][] myResultMatrix;
int myMatrixRow;
int myMatrixCol;
Random rand = new Random();
public Matrix(int rowSize, int colSize, int maxVal, int minVal){
myMatrixRow = rowSize;
myMatrixCol = colSize;
myMatrix = new int[rowSize][colSize];
for(int i = 0; i < rowSize; i++){
for(int k = 0; k < colSize; k++){
myMatrix[i][k] = rand.nextInt((maxVal - minVal) + 1) + minVal; //assigns each part of array to rand #
}
}
for(int i = 0; i<myMatrixRow; i++){
System.out.print("[");
for(int j = 0; j<myMatrixCol; j++){
System.out.print(" " + myMatrix[i][j] + " ");
}
System.out.print("]");
System.out.println();
}
//System.out.println(Arrays.deepToString(myMatrix));
}
public int[][] multMatrix(Matrix matrix2){
if(canMultiply(matrix2) == true){
myResultMatrix = new int[myMatrixRow][matrix2.myMatrixCol];
for (int i = 0; i < myMatrixRow; i++) {
for (int j = 0; j < matrix2.myMatrixCol; j++) {
for (int k = 0; k < myMatrixCol; k++) {
myResultMatrix[i][j] += myMatrix[i][k] * matrix2.myMatrix[k][j];
}
}
}
return myResultMatrix;
}else{
myResultMatrix = null;
return null;
}
}
public boolean canMultiply(Matrix matrix2){ //can only multiply if the columns of
//first matrix is equal to the rows of the second
if(myMatrixCol == matrix2.myMatrixRow){
return true;
}else{
return false;
}
}
public int[][] addMatrix(Matrix matrix2){
if(myMatrixRow == matrix2.myMatrixRow && myMatrixCol == matrix2.myMatrixCol){
myResultMatrix = new int[myMatrixRow][myMatrixCol];
for(int i = 0; i < myMatrixRow; i++){
for(int k = 0; k < myMatrixCol; k++){
myResultMatrix[i][k] = myMatrix[i][k] + matrix2.myMatrix[i][k];
}
}
return myResultMatrix;
}else{
myResultMatrix = null;
return null;
}
}
public void printResultDetail(Matrix matrix2){
for(int i = 0; i<myMatrixRow; i++){
System.out.print("[");
for(int j = 0; j<myMatrixCol; j++){
System.out.print(" " + myMatrix[i][j] + " ");
}
System.out.print("] ");
System.out.println();
for(int k = 0; k<matrix2.myMatrixRow; k++){
System.out.print("[");
for(int x = 0; x<matrix2.myMatrixCol; x++){
System.out.print(" " + matrix2.myMatrix[k][x] + " ");
}
System.out.print("]");
}
}
}
public static void main(String[] args){
Matrix firstMatrix = new Matrix(3, 3, 5, 1);
Matrix secondMatrix = new Matrix(3, 3, 5, 1);
System.out.println(Arrays.deepToString(firstMatrix.addMatrix(secondMatrix)));
//System.out.println(Arrays.deepToString(firstMatrix.addMatrix(secondMatrix)));
}
}
This code below will print:
maybe you can use as sample.
public class Test {
public static void main(String[] args) {
double[][] matrixLeft = {{1,5,2,8,4,70,55,80},{3,7,4,2,6,60,30,70}};
double[][] matrixRight = {{8,1,6,4,2,10,40,60},{1,5,2,8,4,70,50,80},{3,7,4,2,6,60,30,70}};
int endOfLoop = matrixLeft.length > matrixRight.length ? matrixLeft.length : matrixRight.length;
for(int i = 0; i < endOfLoop; i++){
if(matrixLeft.length > i){
printLine(matrixLeft[i]);
System.out.print(" ");
} else {
printBlankLine(matrixLeft[0].length);
}
if(matrixRight.length > i){
printLine(matrixRight[i]);
}
System.out.println();
}
}
private static void printLine(double[] line){
for(double number : line){
System.out.print(number + " ");
}
}
private static void printBlankLine(int lenght){
for(int i=0; i < lenght; i++){
System.out.print(" ");
}
}
}

2D int array shuffle

im new to this but im tring to do a hotel reservation program.
So i have a 2D int array with ALL rooms, when i start the program i want them to be randomly shuffle in to an array called RoomNotInUse or RoomInUse (so evertime i start the program the rooms are randomly generated.
Would be awesome if anyone know a way around this :)
// ARRAYS
protected static int[][] rooms = {
{1,1}, {1,2}, {1,3}, {1,4}, {1,5},
{2,1}, {2,2}, {2,3}, {2,4}, {2,5},
{3,1}, {3,2}, {3,3}, {3,4}, {3,5},
{4,1}, {4,2}, {4,3}, {4,4}, {4,5},
{5,1}, {5,2}, {5,3}, {5,4}, {5,5}
};
//Declare all hotel rooms 5x5, the first number is the floor and the sec is the room
private char[][] ROIU = {
};
//Rooms not in use
private char[][] RIU = {
};
//Rooms in use
public class roomShuffle {
}
//Shuffle all rooms in 2 diffrent arrays, ROIN and RIU
public class RoomNotInUse {
}
//Displayes all the rooms thats not in use
public class RoomInUse {
}
//Displayes all rooms in use
}
You can use Fisher–Yates algorithm modified for two-dimensional arrays:
void shuffle(int[][] a) {
Random random = new Random();
for (int i = a.length - 1; i > 0; i--) {
for (int j = a[i].length - 1; j > 0; j--) {
int m = random.nextInt(i + 1);
int n = random.nextInt(j + 1);
int temp = a[i][j];
a[i][j] = a[m][n];
a[m][n] = temp;
}
}
}
Assign all array into list. Than use Collections.shuffle().
List<int[]> pair=new ArrayList<int[]>();
pair.addAll(Arrays.asList(rooms));
Collections.shuffle(pair);
You can use shuffle-
Collections.shuffle()
Here's a tutorial that describes with or without Collections.
A generic shuffle method in Java should me similar to this
The important thing is that you have to swap an item with a random element that comes after in the collection ;)
public void shuffle(Comparable [] a){
for(int i=0;i,a.length;i++)
swap(a,i,getRandom(i,a.length-1);
}
private int getRandom(int min, int max){
Random rnd = new Random();
return min + rnd.nextInt(max-min+1);
}
private void swap(Comparable [] a, int i, int j){
Comparable temp = a[i];
a[i]=a[j];
a[j]=temp;
}
Otherwise you can use the Collection.shuffle method.
Scanner scanner = new Scanner(System.in);
int n;
int m;
int selection;
System.out.println("Enter number of team");
n = scanner.nextInt();
m = (int) Math.sqrt(n);
int[][] matrix = new int[m][m];
List<Integer> listMatrix = new ArrayList<Integer>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = i * m + j + 1;
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}
for (int i = 0; i < m * m; i++) {
listMatrix.add(i + 1);
}
System.out.println();
do {
System.out.println("what line is the card?");
selection = scanner.nextInt();
} while (!(selection >= 1 && selection <= m));
selection -= 1;
int[] values = new int[m];
for (int i = 0; i < m; i++) {
values[i] = matrix[selection][i];
// System.out.print(values[i] + "\t");
}
System.out.println();
Collections.shuffle(listMatrix);
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = listMatrix.get(j + i * m);
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}
scanner.close();

Categories