Suppose you are given any list of numbers
Question
1) Suppose you are given any list of numbers e.g. List(1, 3, 3, 4, 2, 5, 9, 6, 1) and you are asked to return the highest even number. Which of the following set of functions best solves the problem?
a. reduce, max
b. filter, reduce, max
c. filter, map
d. reduce, map, max
2)Given the following scala code: val cost = 29.19 Which of the following statements is false?
a. You can pass cost as an argument into a scala function that accepts arguments of type Double.
b. Scala automatically assigns a type of Double to the variable cost.
c. You can assign cost to a different value but the new value must be of type Double.
d. You cannot change the value of cost to any other value.
3) Given a scala list called numbers initialized with integer values. What does the following line of Scala code do?
numbers.map(_ / 2.0).reduce(_ * _)
a. Divides each value in the numbers list by 2.0 and then computes the sum of all the values in the numbers list.
b. Divides each value in the numbers list by 2.0 and then computes the product of each pair of values in the numbers list.
c. Divides each value in the numbers list by 2.0 and then computes the product of all the values in the numbers list.
d. Computes the product of all the values in the numbers list then divides it by 2.0.
Explanation
1)
b. filter, reduce, max
Reduce in scala is used to reduce the list by one.
the map takes the function, list, and array. And after that, it will be implemented on the numbers present in the list.
the max function will return the maximum number in the list.
2)
There are two types of variables in scala. And they are mutable variables and immutable variables. The difference between them is. If we declare the variable and we change it after its declaration then it is called mutable. Whereas if we declare the variable and we cannot change it then it is called immutable. They are defined with the variable ‘val’. In our question, val cost = 29.19 while declaration, ‘val’ keyword is used, which makes code immutable. So, it cannot be changed after declaration.
3)
The given statement numbers.map(_ / 2.0).reduce(_ * _) does:
c. Divides each value in the numbers list by 2.0 and then computes the product of all the values in the numbers list.
Since the map will apply ‘/2.0 ‘ function on elements in the numbers list and reduce will reduce the list based on, So it will first divide the numbers list by 2.0 and after that, it will reduce the list. By applying operation on all elements.
Also read, Robin hood in the terms of a Strategic Impact Grid