Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Building on the work we did in class on the 21st, add new methods to the classes

ID: 3890333 • Letter: B

Question

Building on the work we did in class on the 21st, add new methods to the classes Vector, DenseVector, and SparseVector:

1. Scalar Multiplication

A version of this operation should appear in both the DenseVector class as

public DenseVector scale (double scalar) {...}

as well as an analogous version in SparseVector.

public SparseVector scale (double scalar) {...}

Implement each method appropriately for the class it is found in.

Scalar multiplication is defined as follows:

scalar × ( a1, a2, ... , an ) (scalar × a1, scalar × a2, ... , scaler ×an )

Note that each method returns an object in the class in which the method is defined.

2. Scale a Vector

The method should appear in the abstract class Vector as

public void scaleBy (double scalar) {...}

In contrast to the previous method, which returns a new vector object, this method should alter the contents of the object which calls it. A successful implementation will result in that the following code

double data[] = { 1.0, 2.0, 3.0 };
Vector v = new DenseVector(data);
v.scaleBy(2);
System.out.println(v);

prints

( 2.0, 4.0, 6.0 )

Explanation / Answer

Here are the three methods defined

public DenseVector scale (double scalar) {

//assuming here that the vecData is the variable that holds the array elements

double data[] = new double[vecData.length];

for(int i=0; i<data.length; i++)

{

if(vecData[i] != null)

data[i] = vecData[i] * scalar;

}

new DenseVector(data);

}

public SparseVector scale (double scalar) {

//assuming here that the vecData is the variable that holds the array elements

double data[] = new double[vecData.length];

for(int i=0; i<data.length; i++)

{

if(vecData[i] != null)

data[i] = vecData[i] * scalar;

}

new SparseVector (data);

}

public void scaleBy (double scalar) {

//assuming here that the vecData is the variable that holds the array elements

for(int i=0; i<vecData.length; i++)

{

if(vecData[i] != null)

vecData[i] *= scalar;

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at drjack9650@gmail.com
Chat Now And Get Quote