Advertisement
Guest User

Untitled

a guest
Dec 10th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.68 KB | None | 0 0
  1. import java.util.Random;
  2.  
  3. /**
  4. * Created by max on 10.12.2016.
  5. * класс Matrix для операций над матрицами
  6. */
  7.  
  8. public class Matrix {
  9.  
  10. int rows; // количество строк матрицы
  11. int columns; // количество столбцов матрицы
  12. int[][] x; // исходный массив для матрицы
  13.  
  14. // Конструктор №1: Создание пустой матрицы (заполненной нулями)
  15. public Matrix(int rows, int columns) {
  16. this.rows = rows;
  17. this.columns = columns;
  18. x = new int[rows][columns];
  19. }
  20.  
  21. // Конструктор №2: Создание матрицы заполненной случайными числами от нуля до limit
  22. public Matrix(int rows, int columns, int limit) {
  23. this.rows = rows;
  24. this.columns = columns;
  25. x = new int[rows][columns];
  26. fillRnd(limit);
  27. }
  28.  
  29. // произведение исходной матрицы на даную (версия для однопоточной обработки)
  30. public Matrix multiply(Matrix m) {
  31. // проверка согласования матриц
  32. if (isProduct(m)) {
  33. Matrix z = new Matrix(rows, m.columns);
  34. int sum;
  35. for (int i = 0; i < rows; i++) {
  36. for (int j = 0; j < m.columns; j++) {
  37. sum = 0;
  38. for (int k = 0; k < columns; k++) {
  39. sum += this.x[i][k] * m.x[k][j];
  40. }
  41. z.x[i][j] = sum;
  42. }
  43. }
  44. return z;
  45. } else {
  46. // если матрицы не согласоаны выбросить исключение
  47. throw new ArithmeticException("Матрицы не согласованы");
  48. }
  49. }
  50.  
  51. // проверка на согласованность
  52. public boolean isProduct(Matrix m) {
  53. if (this.columns == m.rows) {
  54. return true;
  55. }
  56. else return false;
  57. }
  58.  
  59. // заполнение матрицы случайными целыми числами от 0 до limit
  60. public void fillRnd (int limit) {
  61. Random rnd = new Random();
  62. for (int i = 0; i < rows; i++) {
  63. for (int j = 0; j < columns; j++) {
  64. x[i][j] = rnd.nextInt(limit);
  65. }
  66. }
  67. }
  68.  
  69. // вывод матрицы на консоль
  70. public void show() {
  71. for (int i = 0; i < rows; i++) {
  72. for (int j = 0; j < columns; j++) {
  73. System.out.print(x[i][j] + " ");
  74. }
  75. System.out.println();
  76. }
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement