Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Text;
- //Write a class Matrix, to holds a matrix of integers. Overload the operators for adding, subtracting and multiplying
- //of matrices, indexer for accessing the matrix content and ToString().
- class Matrix
- {
- public int rows;
- public int cols;
- private int[,] matrix;
- public Matrix(int x,int y)
- {
- matrix = new int[x, y];
- rows = x;
- cols = y;
- }
- public int this[int x, int y]
- {
- get
- {
- return matrix[x, y];
- }
- set
- {
- matrix[x, y] = value;
- }
- }
- public static Matrix operator +(Matrix matrix1, Matrix matrix2)
- {
- Matrix result = new Matrix(matrix1.rows, matrix1.cols);
- for (int x = 0; x < matrix1.rows ; x++)
- {
- for (int y = 0; y < matrix1.cols; y++)
- {
- result[x, y] = matrix1[x, y] + matrix2[x, y];
- }
- }
- return result;
- }
- public static Matrix operator -(Matrix matrix1, Matrix matrix2)
- {
- Matrix result = new Matrix(matrix1.rows, matrix1.cols);
- for (int x = 0; x < matrix1.rows; x++)
- {
- for (int y = 0; y < matrix1.cols; y++)
- {
- result[x, y] = matrix1[x, y] - matrix2[x, y];
- }
- }
- return result;
- }
- public static Matrix operator *(Matrix matrix1, Matrix matrix2)
- {
- Matrix result = new Matrix(matrix1.rows, matrix1.cols);
- for (int x = 0; x < matrix1.rows; x++)
- {
- for (int y = 0; y < matrix1.cols; y++)
- {
- result[x, y] = matrix1[x, y] * matrix2[y, x];
- }
- }
- return result;
- }
- public override string ToString()
- {
- StringBuilder result = new StringBuilder();
- for (int x = 0; x < this.rows; x++)
- {
- for (int y = 0 ;y < this.cols;y ++)
- {
- if (y == 0)
- {
- result.Append("\n{").Append(this[x, y]);
- }
- else
- {
- result.Append(",").Append(this[x, y]);
- }
- if (y == this.cols - 1)
- {
- result.Append("}");
- }
- }
- }
- return result.ToString();
- }
- }
- class Program
- {
- static void Main()
- {
- Matrix m1 = new Matrix(5,5);
- Matrix m2 = new Matrix(5,5);
- Random generator = new Random();
- for (int x = 0; x < m1.rows; x++)
- {
- for (int y = 0; y < m1.cols; y++)
- {
- m1[x, y] = generator.Next(100);
- m2[x, y] = generator.Next(100);
- }
- }
- Console.Write("Adding:");
- Console.WriteLine((m1+m2).ToString());
- Console.Write("Subtracting:");
- Console.WriteLine((m1 - m2).ToString());
- Console.Write("Multiplying:");
- Console.WriteLine((m1 * m2).ToString());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement