Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- /**
- * Created by max on 10.12.2016.
- * класс Matrix для операций над матрицами
- */
- public class Matrix {
- int rows; // количество строк матрицы
- int columns; // количество столбцов матрицы
- int[][] x; // исходный массив для матрицы
- // Конструктор №1: Создание пустой матрицы (заполненной нулями)
- public Matrix(int rows, int columns) {
- this.rows = rows;
- this.columns = columns;
- x = new int[rows][columns];
- }
- // Конструктор №2: Создание матрицы заполненной случайными числами от нуля до limit
- public Matrix(int rows, int columns, int limit) {
- this.rows = rows;
- this.columns = columns;
- x = new int[rows][columns];
- fillRnd(limit);
- }
- // произведение исходной матрицы на даную (версия для однопоточной обработки)
- public Matrix multiply(Matrix m) {
- // проверка согласования матриц
- if (isProduct(m)) {
- Matrix z = new Matrix(rows, m.columns);
- int sum;
- for (int i = 0; i < rows; i++) {
- for (int j = 0; j < m.columns; j++) {
- sum = 0;
- for (int k = 0; k < columns; k++) {
- sum += this.x[i][k] * m.x[k][j];
- }
- z.x[i][j] = sum;
- }
- }
- return z;
- } else {
- // если матрицы не согласоаны выбросить исключение
- throw new ArithmeticException("Матрицы не согласованы");
- }
- }
- // проверка на согласованность
- public boolean isProduct(Matrix m) {
- if (this.columns == m.rows) {
- return true;
- }
- else return false;
- }
- // заполнение матрицы случайными целыми числами от 0 до limit
- public void fillRnd (int limit) {
- Random rnd = new Random();
- for (int i = 0; i < rows; i++) {
- for (int j = 0; j < columns; j++) {
- x[i][j] = rnd.nextInt(limit);
- }
- }
- }
- // вывод матрицы на консоль
- public void show() {
- for (int i = 0; i < rows; i++) {
- for (int j = 0; j < columns; j++) {
- System.out.print(x[i][j] + " ");
- }
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement