Create a basics.Matrix class (using a two-dimensional array of real numbers as a matrix) that has the following operations: construct an M × N zero matrix, construct an M × N matrix using an M × N array, create an N × N dimensional unit matrix ( the result matrix should be a return value), the matrix transposed resp. calculating the sum and difference of two matrices, representing the matrix as a string (use java.lang.StringBuilder to generate the text).
Also create a main program (Main.java) that tests these operations!
My problem is in my basicsMatrixMain.java code, that I do not know how can I print out thre results I get from difference or transpone. Can anybody help me to solve it ?
public class basicsMatrix {
private final int N;
private final int M;
private final double[][] matrix;
public basicsMatrix(int M, int N) {
this.N = N;
this.M = M;
matrix = new double[M][N];
}
public basicsMatrix(double[][] matrix) {
M = matrix.length;
N = matrix[0].length;
this.matrix = new double[N][M];
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
this.matrix[i][j] = matrix[i][j];
}
public void transzponalas(double[][] matrix1){
double[][] transpose = new double[M][N];
for(int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
transpose[j][i] = matrix1[i][j];
}
}
}
public void add(double[][] matrix1,double[][] matrix2){
double[][] osszeadas = new double[N][M];
for(int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
osszeadas[i][j] = (matrix1[i][j] + matrix2[i][j]);
}
}
}
public void difference(int matrix1[][], int matrix2[][]){
double[][] kivonas = new double[N][M];
for(int i = 0; i <= N; i++){
for(int j = 0; j <= M; j++){
kivonas[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
}
public String matrixtostring(double[][] matrix1){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
sb.append(matrix1);
}
}
return sb.toString();
}
}
public class basicsMatrixMain {
public static void main(String[] args) {
int N = 2;
int M = 3;
double[][] matrix1 = { {2, 3, 4}, {5, 2, 3} };
double[][] matrix2 = { {-4, 5, 3}, {5, 6, 3} };
System.out.println("\n");
System.out.print("Difference:");
for(int i = 0; i <= N; i++){
for(int j = 0; j <= M; j++){
System.out.println();
}
}
}
}
You have defined a lot of functions in basicsMatrix that you can use here.
However there are some changes that you need to make. In your add, difference and transpose methods, you define something but you never save the result. I would recommend something like this:
public double[][] transzponalas(double[][] matrix1){
double[][] transpose = new double[M][N];
for(int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
transpose[j][i] = matrix1[i][j];
}
}
return transpose;
}
public double[][] add(double[][] matrix1,double[][] matrix2){
double[][] osszeadas = new double[N][M];
for(int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
osszeadas[i][j] = (matrix1[i][j] + matrix2[i][j]);
}
}
return osszeadas;
}
public double[][] difference(int matrix1[][], int matrix2[][]){
double[][] kivonas = new double[N][M];
for(int i = 0; i <= N; i++){
for(int j = 0; j <= M; j++){
kivonas[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
return kivonas;
}
All these functions now return a matrix that you can print out.
Now you just print you matrices. Something like this should work.
System.out.println(matrixtostring(transzponalas(matrix1)));
System.out.println(matrixtostring(add(matrix1,matrix2)));
System.out.println(matrixtostring(difference(matrix1,matrix2)));
Looking at the question description.
"Create a basics.Matrix class (using a two-dimensional array of real numbers as a matrix) that has the following operations: construct an M × N zero matrix, construct an M × N matrix using an M × N array, create an N × N dimensional unit matrix ( the result matrix should be a return value), the matrix transposed resp. calculating the sum and difference of two matrices, representing the matrix as a string (use java.lang.StringBuilder to generate the text).
Also create a main program (Main.java) that tests these operations!"
I suspect that you are supposed to create a class that calls functions on itself. In other words the basicsMatrix will become your matrix.
For example, the transzponalas method would become
public void transzponalas(){
double[][] transpose = new double[M][N];
for(int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
transpose[j][i] = this.matrix[i][j];
}
}
int tmp = this.M
this.M = this.N
this.N = tmp
this.matrix = transpose;
}
This way, you change the matrix that is inside your basicsMatrix. You should make sure that you understand the assignment correctly.
I have a question. Can anyone help me with finding duplicates in submatrices?
I have a code which finds submatrices in 2d matrix, but I can't find duplicates. I thought to push the values onto the Stack (because in assignment I should use Stack), find all duplicates in each submatrix, and then compare them, but I don't really know how to do it. I'll be very gratefull, if anyone help me to finish this program.
My code:
public static void main(String[] args) throws Exception {
int[][] data = new int[3][3];
Random random = new Random();
for(int i=0; i<data.length;i++)
{
for(int j=0; j<data.length; j++)
{
data[i][j] = random.nextInt(10);
}
}
printSubMatrix(data);
}
private static void printSubMatrix(int[][] mat) {
int rows=mat.length;
int cols=mat[0].length;
Stack _stack = new Stack();
//prints all submatrix greater than or equal to 2x2
for (int subRow = rows; subRow >= 2; subRow--) {
int rowLimit = rows - subRow + 1;
for (int subCol = cols; subCol >= 2; subCol--) {
int colLimit = cols - subCol + 1;
for (int startRow = 0; startRow < rowLimit; startRow++) {
for (int startCol = 0; startCol < colLimit; startCol++) {
for (int i = 0; i < subRow; i++) {
for (int j = 0; j < subCol; j++) {
System.out.print(mat[i + startRow][j + startCol] + " ");
_stack.push(mat[i+startRow][j+startCol]);
}
System.out.print("\n");
}
System.out.print("\n");
}
}
}
}
System.out.printf(_stack.toString().replaceAll("\\[", "").replaceAll("]", ""));
}
I have implemented a chain matrix multiplication. Although I get correct chain order, but while doing actual multiplication, the given multiply algorithm is not working properly. My Java Code:-
package algopackage;
import java.util.ArrayList;
import java.util.List;
public class ChainMatrixMultiplication {
static int s[][];
static int x[][];
static int y[][];
public ChainMatrixMultiplication() {
}
static void chainMatrixMultiplication(int[] p) {
boolean isFirst = false;
int n = p.length-1;
int m[][] = new int[n][n];
s = new int[n][n];
for (int c = 0; c < n; c++)
m[c][c] = 0;
for (int counter = 1; counter < n; counter++) {
for (int i = 0;i < n; i++) {
isFirst = false;
int j = i + counter;
for (int k = i; k < j && j < n; k++) {
int result = m[i][k] + m[k+1][j] + p[i] * p[k+1] * p[j+1];
if (!isFirst) {
m[i][j] = result;
s[i][j] = k;
isFirst = true;
} else if (m[i][j] > result) {
m[i][j] = result;
s[i][j] = k;
}
}
}
}
}
static int[][] matrixMultiply(List<Matrix> matrices, int s[][], int i ,int j) {
if (i ==j) return matrices.get(i).getMatrix();
else {
int k = s[i][j];
x = matrixMultiply(matrices, s, i, k);
y = matrixMultiply(matrices, s, k+1, j);
return mult(x,y);
}
}
static int[][] mult(int[][] x, int[][] y) {
int [][] result = new int[x.length][y[0].length];
/* Loop through each and get product, then sum up and store the value */
for (int i = 0; i < x.length; i++) {
for (int j = 0; j < y[0].length; j++) {
for (int k = 0; k < x[0].length; k++) {
result[i][j] += x[i][k] * y[k][j];
}
}
}
return result;
}
public static void main(String[] args) {
int p[] = {5,4,6,2};
List<Matrix> matrices = new ArrayList<Matrix>();
Matrix m1 = new Matrix(5,4);
int arr[] = {1,2,40,2,3,29,10,21,11,120,23,90,24,12,11,1,11,45,23,21};
m1.addElementsToMatrix(5, 4, arr);
Matrix m2 = new Matrix(4,6);
int arr1[] = {1,1,1,2,3,12,12,3,10,12,12,29,22,11,22,11,11,11,13,1,2,12,4,2};
m2.addElementsToMatrix(4, 6, arr1);
Matrix m3 = new Matrix(6,2);
int arr2[] = {1,1,12,3,22,11,13,1,2,12,12,12};
m3.addElementsToMatrix(6, 2, arr2);
matrices.add(m1);
matrices.add(m2);
matrices.add(m3);
chainMatrixMultiplication(p);
matrixMultiply(matrices,s,0,2);
}
}
class Matrix {
private final int[][] matrix;
public Matrix(int rows, int cols) {
this.matrix = new int[rows][cols];
}
public void addElementsToMatrix(int rows, int cols, int[] arr) {
int counter = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = arr[counter++];
}
}
}
public int[][] getMatrix() {
return matrix;
}
}
In the above code matrixMultiply() function is throwing exception. Exception is caused as matrices are not being multiplied as expected. As recursion is not behaving as expected. I am missing something in this code. Any help will be appreciated.Thanks!
I'm not sure of the correctness of your code, but looking at the matrix multiplication output when you multiply matrix of dimension a*b and c*d after you multiply, you get a matrix of dimension a*d there by changing
for (int k = 0; k < x[0].length; k++) {
to
for (int k = 0; k < y[0].length; k++) {
should resolve the problem.
This:
x = matrixMultiply(matrices, s, i, k); // call A
y = matrixMultiply(matrices, s, k+1, j); // call B
return mult(x,y);
looks like it should multiply the result of call A by the result of call B. But in general, it doesn't.
x is not local, call B will usually overwrite it, except when call B immediately hits the base case.
This sort of thing tends to happen when you pass data around "to the side", not as function parameter or function return value. It is not reasonable to avoid that kind of data flow all the time, but you should avoid it here, especially since it's not even what you wanted.
I am trying to generate this 2D Array maze 10 by 10 with numbers 0-9 in each row for 10 rows, but I keep getting array out of bounds exception. I double checked my indexes and the loop format and everything looks standard.
public class MazeDemo {
public static void main(String[] args) {
Maze maze = new Maze(10, 10);
maze.generate();
}
}
class Maze {
int N, M;
int[][] cell = new int[N][M];
public Maze(int N, int M) {
this.N = N;
this.M = M;
}
public void generate() {
for (int i = 0; i < N; i++) {
int counter = 0;
for (int j = 0; i < M; j++) {
cell[i][j] = counter;
counter++;
}
}
display(cell, 10, 10);
}
public static void display(int a[][], int N, int M) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
System.out.print(a[i][j]);
}
}
}
}
What is going on here? Why am I getting the out of bounds exception?
When you declare cell, N and M are 0. Change it to something like
int N, M;
int[][] cell;
public Maze(int N, int M) {
this.N = N;
this.M = M;
this.cell = new int[N][M]; // <-- add this.
}
And in generate, this
for (int j = 0; i < M; j++) {
should be
for (int j = 0; j < M; j++) {
The problem is in the generate method in:
for (int j = 0; i < M; j++)
^
it should be:
for (int j = 0; j < M; j++)
I am trying to work through an assignment that is asking me to create a method in Java that, when given a desired height and width, create a row- or column- major matrix.
Here is what I have so far:
public static int[][] increasingMatrix(int width, int height, boolean format){
if (format) { // generate row-major matrix
int[][] array = new int[height][];
int count = 0;
for (int i = 0; i < height; i++) {
array[i] = new int[width];
for (int j = 0; j < width; j++) {
array[i][j] = count;
count++;
}
}
return array;
} else {
int[][] array = new int[width][];
int count = 0;
for (int i = 0; i < width; i++) {
array[i] = new int [height];
for (int j = 0; j < height; j++) {
array[j][i] = count;
count ++;
}
}
return array;
}
}
However, when I go and try to run tests on the generated array, the column-major matrix (from what I can tell) is being generated incorrectly. The row-major matrix seems to generate correctly.
Can you see anything that I am doing wrong? I have stared at this for hours but cant seem to get any breakthroughs.
Thanks!
Your code is wrong. The first index in the matrix is always the width.
Remember: a matrix is an array of arrays. The first index is the width of the matrix, the second is the height.
Try this:
if(format) {
return buildRowMajorMatrix(width, height);
} else {
return buildColumnMajorMatrix(width, height);
}
Where buildRowMajorMatrix looks like:
private int[][] buildRowMajorMatrix(int width, int height) {
int[][] matrix = new int[width][height];
int cellValue = 0;
for(int columnIndex = 0 ; columnIndex < width ; columnIndex++) {
for(int rowIndex = 0 ; rowIndex < height ; rowIndex++, cellValue++) {
matrix[columnIndex][rowIndex] = cellValue;
}
}
return matrix;
}
And buildColumnMajorMatrix looks like:
private int[][] buildColumnMajorMatrix(int width, int height) {
int[][] matrix = new int[width][height];
int cellValue = 0;
for(int rowIndex = 0 ; rowIndex < height ; rowIndex++) {
for(int columnIndex = 0 ; columnIndex < width ; columnIndex++, cellValue++) {
matrix[columnIndex][rowIndex] = cellValue;
}
}
return matrix;
}
In else condition:
else {
int[][] array = new int[width][];
int count = 0;
for (int i = 0; i < width; i++) {
array[i] = new int [height];
for (int j = 0; j < height; j++) {
array[j][i] = count;
count ++;
}
}
return array;
}
You are trying trying to iterate through arrays (rows of matrix, j-index) that are not yet initialized. To implement column-major matrix you need to first initialize all rows (or switch to more complex algorithm).
Also I think width and height of matrix in both formats should be same. Row- and column-majority only says whether we fill matrix iterating by columns or rows, but I guess wording of the task leaves room for interpretation.
My solution:
public static int[][] increasingMatrix(int width, int height, boolean format){
int[][] array = new int[height][width]; // Java's shortcut generating regular array of arrays for you
int count = 0;
if (format) { // generate row-major matrix
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
array[i][j] = count;
count++;
}
}
} else {
for (int j = 0; j < width; j++)) {
for (int i = 0; i < height; i++ {
array[i][j] = count;
count++;
}
}
}
return array;
}