On the following code that contains a method which returns a
On the following code that contains a method which returns a new matrix (2-d array) with same number of rows and columns as has its parameter (matrix). Each entry in the returned array should equal the result of multiplying the entry at the same row and column in matrix by the value of scalar.
code:
Solution
/**
* Class which contains a method which takes in a 2-dimensional array and a scalar value and returns their product.
*/
class ScalarMult {
/**
* Allocates a new 2-d array and then sets each entry to be the product of {@code scalar} and the entry in
* {@code matrix} at the same row and column. This was inspired by the only \"joke\" told by my calculus teacher:<br/>
* Why can\'t you cross a mountain climber and a grape? Because you cannot cross a scalar.<br/>
* <br/>
* Yeah, I did not find it funny either.
*
* @param matrix 2-d array which we would like to have multiplied by the given value.
* @param scalar The new matrix will be equal to having each entry in {@code matrix} multipled by this value.
* @return The product of this matrix and constant value.
*/
public int[][] scalarMult(int[][] matrix, int scalar) {
int row=matrix.length;
int column=matrix[0].length;
int result[][]=new int[row][column];
for(int i=0;i<row;i++)
{
for(int j=0;j<column;j++)
{
result[i][j]=scalar*matrix[i][j];
}
}
return result;
}
}
public class ScalarMulTest
{
public static void main(String args[])
{
ScalarMult smul=new ScalarMult();
int input[][]={{2,6},{4,3}};
smul.scalarMult(input,2);
}
}
