fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. public static class Utils
  6. {
  7. public static T Add<T>(T a, T b)
  8. {
  9. if (typeof(T) == typeof(double))
  10. return (T)(object)((double)(object)a + (double)(object)b);
  11.  
  12. if (typeof(T) == typeof(float))
  13. return (T)(object)((float)(object)a + (float)(object)b);
  14.  
  15. if (typeof(T) == typeof(int))
  16. return (T)(object)((int)(object)a + (int)(object)b);
  17.  
  18. throw new Exception("fuck you");
  19. }
  20. }
  21.  
  22. public class Vector<T>
  23. {
  24. public Vector(int size)
  25. {
  26. Size = size;
  27. }
  28.  
  29. public int Size { get; set; }
  30.  
  31. public T[] Data { get; set; }
  32.  
  33. public Matrix<T> Add<U>(U matrix) where U : Matrix<T>
  34. {
  35. if (matrix.Len2 != Size)
  36. throw new Exception("error");
  37.  
  38. var data = new List<List<T>>();
  39.  
  40. for (int i = 0; i < matrix.Len1; i++)
  41. {
  42. var row = new List<T>();
  43. for (int j = 0; j < matrix.Len2; j++)
  44. {
  45. var val1 = matrix.Data[i][j];
  46. var val2 = Data[j];
  47. row.Add(Utils.Add(val1, val2));
  48. }
  49. data.Add(row);
  50. }
  51.  
  52. return new Matrix<T>(matrix.Len1, matrix.Len2)
  53. {
  54. Data = data.Select(x => x.ToArray()).ToArray()
  55. };
  56. }
  57. }
  58.  
  59. public class Matrix<T>
  60. {
  61. public Matrix(int len1, int len2)
  62. {
  63. Len1 = len1;
  64. Len2 = len2;
  65. }
  66.  
  67. public int Len1 { get; set; }
  68.  
  69. public int Len2 { get; set; }
  70.  
  71. public T[][] Data { get; set; }
  72. }
  73.  
  74. public class Test
  75. {
  76. public static void Main()
  77. {
  78. var vector = new Vector<double>(3) { Data = new double[] { 1, 3, 4} };
  79. var matrix = new Matrix<double>(2, 3) { Data = new[] { new double[] { 1, 3, 2 }, new double[] { 34, 2, 4 } } };
  80.  
  81. var res = vector.Add(matrix);
  82.  
  83. Console.WriteLine(res.Data[0][1]);
  84. }
  85. }
Success #stdin #stdout 0.02s 15868KB
stdin
Standard input is empty
stdout
6