#java #matrix #addition
Вопрос:
В этой программе я пытаюсь создать новый метод, который может добавить две созданные матрицы. Для этого мне нужно проверить, имеют ли матрицы одинаковые размеры, а затем распечатать добавленные матрицы. Матрицы заполняются случайными числами, заданными в коде. Может ли кто-нибудь помочь создать метод, который позволит мне сложить два из них вместе?
public class Matrix { private int [][] grid; /** * default constructor: creates 3x3 matrix with random values * in the range 0..9 */ public Matrix() { grid = new int[3][3]; for(int x=0; xlt;3; x ) for(int y=0; ylt;3; y ) grid[x][y] = (int)(Math.random()*10); } /** * Creates matrix of specified size with random values 0..9 * @param size positive integer that represents the number of rows * and columns in the matrix */ public Matrix(int size) { grid = new int[size][size]; for(int x=0; xlt;size; x ) for(int y=0; ylt;size; y ) grid[x][y] = (int)(Math.random()*10); } /** * Creates a matrix of specified size with random values 0..9 * @param rows number of rows in matrix * @param columns number of columns int matrix */ public Matrix(int rows, int columns) { grid = new int[rows][columns]; for(int x=0; xlt;rows; x ) for(int y=0; ylt;columns; y ) grid[x][y] = (int)(Math.random()*10); } /** * @return String formatted as an m x n matrix of m rows and * n columns */ public String toString() { int rows = grid.length; int columns = grid[0].length; String table = new String(""); for(int x=0; xlt;rows; x ) { table = table '|' 't'; for(int y=0; ylt;columns; y ) table = table grid[x][y] 't'; table = table '|' 'n'; } return table; } /** * @return true if number of rows equals number of columns */ public boolean isSquare() { return grid.length == grid[0].length; } /** * @param other another matrix to compare to this one * @return true if this matrix and the other have the same * number of rows and columns */ public boolean sameSize(Matrix other) { return grid.length == other.grid.length amp;amp; grid[0].length == other.grid[0].length; } // main method: for testing public static void main(String[] args) { Matrix m = new Matrix(); Matrix n = new Matrix((int)(Math.random()*5) 2); Matrix o = new Matrix(((int)(Math.random()*5) 2), ((int)(Math.random()*5) 2)); System.out.println ("First matrix:"); System.out.print(m); System.out.println ("Second matrix:"); System.out.println(n); System.out.println ("Third matrix:"); System.out.println(o); if(m.sameSize(n)) System.out.println("First two are the same size"); else System.out.println("First two are not the same size"); if(o.isSquare()) System.out.println("All three are square matrices"); else System.out.println("Only first two are square matrices"); } }
Комментарии:
1. Что вы уже пробовали? Пожалуйста, предоставьте свой код.
2. Эскиз алгоритма: — Проверьте, что оба параметра матрицы
a
иb
имеют одинаковый размер — Создайте новую матрицуc
того же размера,a
что и иb
— Повторите все строки, установитеc[i][j] = a[i][j] b[i][j]
Ответ №1:
Добавьте это в класс Matrix:
/** * Creates a new Matrix with the values of * both Matrix(s) added together. * @param otherMatrix The Matrix to be added. * @return The new Matrix. */ public Matrix add(Matrix otherMatrix) { if (sameSize(otherMatrix)) { Matrix newMatrix = new Matrix(grid.length, grid[0].length); for (int x = 0; x lt; grid.length; x ) { for (int y = 0; y lt; grid[0].length; y ) { newMatrix.grid[x][y] = grid[x][y] otherMatrix.grid[x][y]; } } return newMatrix; } else { throw new Error("The Matrix(s) aren't the same size."); } }
Затем назовите это с:
Matrix addedMatrix = matrix.add(otherMatrix);
Ответ №2:
Сначала вы проверяете, что матрицы имеют одинаковый размер, а затем суммируете каждое значение в обеих матрицах одно за другим, например
public Matrix sum(Matrix other) { if (this.sameSize(other)) { Matrix result = new Matrix(this.grid.length, this.grid[0].length); for (int i=0; ilt;this.grid.length; i ) { for (int j=0; jlt;this.grid.length; j ) { result.grid[i][j] = this.grid[i][j] other.grid[i][j]; } } return result; } else { return null; // Can't sum those matrices } }
Ответ №3:
public class Matrix { private final int[][] grid; private final int width; private final int height; public Matrix() { this(3); } public Matrix(int size) { this(size, size); } public Matrix(int rows, int cols) { grid = createGrid(rows, cols); width = cols; height = rows; } @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append('['); for (int row = 0; row lt; grid.length; row ) { if (buf.length() gt; 1) buf.append(','); buf.append('['); for (int col = 0; col lt; grid[row].length; col ) { if (col gt; 0) buf.append(','); buf.append(grid[row][col]); } buf.append(']'); } return buf.append(']').toString(); } public boolean isSquare() { return width == height; } public boolean isSameSize(Matrix m) { return m != null amp;amp; width == m.width amp;amp; height == m.height; } public void add(Matrix m) { if (!isSameSize(m)) return; for (int row = 0; row lt; grid.length; row ) for (int col = 0; col lt; grid[row].length; col ) grid[row][col] = m.grid[row][col]; } private static int[][] createGrid(int rows, int cols) { Random random = new Random(); int[][] grid = new int[rows][cols]; for (int row = 0; row lt; grid.length; row ) for (int col = 0; col lt; grid[row].length; col ) grid[row][col] = random.nextInt(10); return grid; } public static void main(String... args) { Random random = new Random(); Matrix m = new Matrix(); Matrix n = new Matrix(random.nextInt(7)); Matrix o = new Matrix(random.nextInt(7), random.nextInt(7)); System.out.println("First matrix:"); System.out.print(m); System.out.println("Second matrix:"); System.out.println(n); System.out.println("Third matrix:"); System.out.println(o); if (m.isSameSize(n)) System.out.println("First two are the same size"); else System.out.println("First two are not the same size"); if (o.isSquare()) System.out.println("All three are square matrices"); else System.out.println("Only first two are square matrices"); n.add(o); System.out.println(n); } }