In: Computer Science
Programing in Scala language: Create a class called “Array” that implements a fixed-sized two-dimensional array of floating-point numbers. Write separate methods to get an element (given parametersrow and col), set an element (given parametersrow, col, and value), and output the matrix to the console formatted properly in rows and columns. Next, provide an immutable method to perform array addition given two same-sized array.
Code:
object MyClass {
//creating a 2d array of fixed size
var myArr = Array.ofDim[Double](2,2);
//method to set an element of teh array
def setArrayElement(row: Int, col: Int, value: Double): Unit
=
{
myArr(row)(col) = value;
}
//method to return the element from the respective pos
def getElement(row: Int, col: Int): Double =
{
return myArr(row)(col);
}
//method to print the array
def printArr(arr: Array[Array[Double]]): Unit =
{
for(i<-0 to 1)
{
for(j<- 0 to 1)
{
// Accessing the values
print(arr(i)(j) + " ");
}
println()
}
}
//method used for array addition
def addintion(arr1: Array[Array[Double]], arr2:
Array[Array[Double]]): Unit =
{
var sum: Double = 0;
for(i<-0 to 1)
{
for(j<- 0 to 1)
{
arr1(i)(j) += arr2(i)(j);
}
}
println("\nNew Array after Addition: ");
printArr(arr1);
}
//main method
def main(args: Array[String]) {
//set the array element
setArrayElement(0,0,10.1);
setArrayElement(0,1,12.23);
setArrayElement(1,0,39.00);
setArrayElement(1,1,44.12);
//get array element
println("Element at pos 0,0: " + getElement(0,0));
println("Element at pos 0,1: " + getElement(0,1));
println("Element at pos 1,0: " + getElement(1,0));
println("Element at pos 1,1: " + getElement(1,1));
//print the array in matrix format
println("Array in Matrix Format: ")
printArr(myArr);
//method to add to array of sma size
var newArr= Array(Array(12.10, 43.29),
Array(88, 10.59)) ;
addintion(myArr, newArr);
}
}
----------------------------------------------------------------------------------------------------------------------------------------------------------------
Output: