//TODO: unit-test /// <summary> /// Creates a new instance of <see cref="DynamicJuggedMatrix{T}"/> which contains elements from /// <see cref="IEnumerable{T}"/> /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <returns></returns> public static DynamicJuggedMatrix <T> CreateDynamicJuggedMatrix <T>(this IEnumerable <IEnumerable <T> > source) { if (ReferenceEquals(source, null)) { throw new ArgumentNullException(nameof(source)); } var enumerables = source as IEnumerable <T>[] ?? source.ToArray(); if (enumerables.Any(item => ReferenceEquals(item, null))) { throw new ArgumentNullException(nameof(source) + ": one of enumerables was null"); } var columnsCounts = enumerables.Select(row => row.Count()); var matrix = new DynamicJuggedMatrix <T>(enumerables.Length, columnsCounts); var rowIndex = 0; var columnIndex = 0; foreach (var row in enumerables) { foreach (var item in row) { matrix[rowIndex, columnIndex] = item; columnIndex++; } rowIndex++; columnIndex = 0; } return(matrix); }
public void RowsAndColumns_test() { var matrix = new DynamicJuggedMatrix<int>(5, 5, 5, 5, 5, 5); Assert.AreEqual(5, matrix.RowsCount); Assert.IsTrue(matrix.IsSquare); }
//TODO: unit-test /// <summary> /// Creates a new instance of <see cref="DynamicJuggedMatrix{T}"/> from <see cref="IMatrix{T}"/> /// </summary> /// <typeparam name="T">ANY</typeparam> /// <param name="matrix">Initial matrix</param> /// <returns>A new instance of <see cref="DynamicJuggedMatrix{T}"/></returns> public static DynamicJuggedMatrix <T> ToDynamicJuggedMatrix <T>(this IMatrix <T> matrix) { var juggedMatrix = new DynamicJuggedMatrix <T>(matrix.RowsCount, Enumerable.Repeat(matrix.ColumnsCount, matrix.RowsCount) .ToArray()); for (var i = 0; i < juggedMatrix.RowsCount; i++) { for (var j = 0; j < matrix.ColumnsCount; j++) { juggedMatrix[i, j] = matrix[i, j]; } } return(juggedMatrix); }
//TODO: unit-test /// <summary> /// Converts a vanilla .NET matrix <see langword="T"/>[][] to <see cref="DynamicJuggedMatrix{T}"/> /// </summary> /// <typeparam name="T">ANY</typeparam> /// <param name="matrix">Initial matrix to convert</param> /// <returns><see cref="JuggedMatrix{T}"/>, made on base <paramref name="matrix"/></returns> public static DynamicJuggedMatrix <T> ToDynamicJuggedMatrix <T>(this T[][] matrix) { if (matrix == null) { throw new ArgumentNullException(nameof(matrix)); } if (matrix.Any(x => x == null)) { throw new NullReferenceException(nameof(matrix) + " one or more rows are null"); } var newJuggedMatrix = new DynamicJuggedMatrix <T>(matrix.Length, matrix.Select(row => row.Length)); for (var i = 0; i < matrix.Length; i++) { for (var j = 0; j < newJuggedMatrix.ElementsInRow(i); j++) { newJuggedMatrix[i, j] = matrix[i][j]; } } return(newJuggedMatrix); }