java-algorithms-implementation icon indicating copy to clipboard operation
java-algorithms-implementation copied to clipboard

The functions Matrix.add and Matrix.subtract have unneeded for loops

Open akerfel opened this issue 2 years ago • 1 comments

In the function Matrix.add (see code below), the innermost for-loop is unneeded (notice that the iterator i is not used at all). Removing this for-loop can reduce the time complexity from cubic to quadratic, in relation to the width of the matrix. I have tried removing it, and all tests still pass.

The exact same problem is apparent in Matrix.subtract.

These functions can be found in the filesrc\com\jwetherell\algorithms\data_structures\Matrix.java

public Matrix<T> add(Matrix<T> input) {
    Matrix<T> output = new Matrix<T>(this.rows, this.cols);
    if ((this.cols != input.cols) || (this.rows != input.rows))
        return output;
    for (int r = 0; r < output.rows; r++) {
        for (int c = 0; c < output.cols; c++) {
            for (int i = 0; i < cols; i++) {
                T m1 = this.get(r, c);
                T m2 = input.get(r, c);
                T result;
                /* TODO: This is ugly and how to handle number overflow? */
                if (m1 instanceof BigDecimal || m2 instanceof BigDecimal) {
                    BigDecimal result2 = ((BigDecimal)m1).add((BigDecimal)m2);
                    result = (T)result2;
                } else if (m1 instanceof BigInteger || m2 instanceof BigInteger) {
                    BigInteger result2 = ((BigInteger)m1).add((BigInteger)m2);
                    result = (T)result2;
                } else if (m1 instanceof Long || m2 instanceof Long) {
                    Long result2 = (m1.longValue() + m2.longValue());
                    result = (T)result2;
                } else if (m1 instanceof Double || m2 instanceof Double) {
                    Double result2 = (m1.doubleValue() + m2.doubleValue());
                    result = (T)result2;
                } else if (m1 instanceof Float || m2 instanceof Float) {
                    Float result2 = (m1.floatValue() + m2.floatValue());
                    result = (T)result2;
                } else {
                    // Integer
                    Integer result2 = (m1.intValue() + m2.intValue());
                    result = (T)result2;
                }
                output.set(r, c, result);
            }
        }
    }
    return output;
}

akerfel avatar Mar 04 '22 17:03 akerfel

I could fix this issue.

akerfel avatar Mar 04 '22 17:03 akerfel