Task
In this challenge, you were provided a range of numbers. Using the range of numbers, you had to create and populate an array. The final array could only consist of even multiples of 3.
Solution
Let’s go over the solution step-by-step.
The first thing you had to do was create an array, let’s call it array1
, using the range
method to which you had to pass minRange
and maxRange
.
val array1 = Array.range(minRange, maxRange)
Next, you had to create a new array, let’s call it array2
, by multiplying the elements of array1
with 3. This could be done using the map
method.
val array2 = array1.map(_ * 3)
Finally, the last step required you to create yet another array, finalArray
, by filtering out the even numbers from array2
. This could be done using the filter
method.
val finalArray = array2.filter(_ % 2 == 0)
You can find the complete solution below:
You were required to write the code from line 3 till line 5.
val minRange = 1val maxRange = 5val array1 = Array.range(minRange, maxRange)val array2 = array1.map(_ * 3)val finalArray = array2.filter(_ % 2 == 0)// Driver CodefinalArray.foreach(println)
In the next lesson, we will learn about the List collection.