Advertisement
bogdb

Triangular Matrix

Apr 25th, 2018
336
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.96 KB | None | 0 0
  1. public class TriangularMatrix<T>
  2. {
  3.     private readonly T[] arr;
  4.     private readonly int dim;
  5.  
  6.     public TriangularMatrix(int n)
  7.     {
  8.         dim = n;
  9.         arr = new T[n * (n + 1) / 2];
  10.     }
  11.  
  12.     // i = row, j = column
  13.     public T this[int row, int col]
  14.     {
  15.         get { return arr[row * (row + 1) / 2 + col]; }
  16.         set { arr[row * (row + 1) / 2 + col] = value; }
  17.     }
  18.  
  19.     public T this[int i]
  20.     {
  21.         get { return arr[i]; }
  22.         set { arr[i] = value; }
  23.     }
  24.  
  25.     public int Rows { get { return dim; } }
  26.     public int Columns { get { return dim; } }
  27.     public int Length { get { return arr.Length; } }
  28.  
  29.     public void GetMatrixCoordinates(int i, out int row, out int col)
  30.     {
  31.         var root = TriangularRoot(i);
  32.         row = (int)Math.Floor(root);
  33.         col = i - row * (row + 1) / 2;
  34.     }
  35.    
  36.     private static double TriangularRoot(double x) {
  37.         return (Math.Sqrt(8 * x + 1) - 1) / 2;
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement