public class TriangularMatrix<T>
{
private readonly T[] arr;
private readonly int dim;
public TriangularMatrix(int n)
{
dim = n;
arr = new T[n * (n + 1) / 2];
}
// i = row, j = column
public T this[int row, int col]
{
get { return arr[row * (row + 1) / 2 + col]; }
set { arr[row * (row + 1) / 2 + col] = value; }
}
public T this[int i]
{
get { return arr[i]; }
set { arr[i] = value; }
}
public int Rows { get { return dim; } }
public int Columns { get { return dim; } }
public int Length { get { return arr.Length; } }
public void GetMatrixCoordinates(int i, out int row, out int col)
{
var root = TriangularRoot(i);
row = (int)Math.Floor(root);
col = i - row * (row + 1) / 2;
}
private static double TriangularRoot(double x) {
return (Math.Sqrt(8 * x + 1) - 1) / 2;
}
}
Comments