Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Implement the addition, subtraction and multiplication methods in LLSparseM. The algorithm has to be O(m), in which m is the maximum number of nonzero elements

Implement the addition, subtraction and multiplication methods in LLSparseM.

The algorithm has to be O(m), in which m is the maximum number of nonzero elements in

a matrix. Only algorithms with O(m) complexity will get credits.

All operations return a new sparse matrix object, storing the result. The method

subtraction(otherM) means the current vector minus otherM.

import java.util.Scanner;

import java.io.File;

class LLSparseM implements SparseM

{

private int nr, nc;

private int sparseArray[][];

public int nrows()

{

// //NEED CODE HERE

return nr;

}

public int ncols()

{

// NEED CODE HERE

return nc;

}

public LLSparseM(int nr, int nc)

{

this.nr = nr;

this.nc = nc;

sparseArray = new int[nr][nc];

}

public int numElements()

{

// NEED CODE HERE

int count = 0;

for (int i = 0; i < nr; i++)

{

for (int j = 0; j < nc; j++)

{

if (sparseArray[i][j] != 0)

{

count++;

}

}

}

return count;

}

public int getElement(int ridx, int cidx)

{

// NEED CODE HERE

return sparseArray[ridx][cidx];

}

public void clearElement(int ridx, int cidx)

{

// NEED CODE HERE

sparseArray[ridx][cidx] = 0;

}

public void setElement(int ridx, int cidx, int val)

{

// NEED CODE HERE

sparseArray[ridx][cidx] = val;

}

public void getAllElements(int[] ridx, int[] cidx, int[] val)

{

int k = 0;

// NEED CODE HERE

for (int i = 0; i < nr; i++)

{

for (int j = 0; j < nc; j++)

{

if (sparseArray[i][j] != 0)

{

ridx[k] = i;

cidx[k] = j;

val[k] = sparseArray[i][j];

k++;

}

}

}

}

public void addition(SparseM otherM)

{

// NEED CODE HERE

if (nr != otherM.nrows() && nc != otherM.ncols())

throw new RuntimeException("Dimensions disagree");

for (int i = 0; i < nr; i++)

for (int j = 0; j < nc; j++)

sparseArray[i][j] = sparseArray[i][j]

+ otherM.getElement(i, j);

}

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Machine Learning And Knowledge Discovery In Databases European Conference Ecml Pkdd 2014 Nancy France September 15 19 2014 Proceedings Part 2 Lnai 8725

Authors: Toon Calders ,Floriana Esposito ,Eyke Hullermeier ,Rosa Meo

2014th Edition

3662448505, 978-3662448502

More Books

Students also viewed these Databases questions