Scala:Filter Array

This is a solution for the following assignment in hackerrank website  in refrence to functional programming

https://www.hackerrank.com/challenges/fp-filter-array?h_r=next-challenge&h_v=zen

Objective :-

Filter a given array of integers and output only those values that are less than a specified value X. The output integers should be in the same sequence as they were in the input. You need to write a function with the recommended method signature for the languages mentioned below. For the rest of the languages, you have to write a complete code.

Input Format

The first line contains the delimiter  X.
The next lines B each contain an integer , which represents the elements of the list/array. You have to read the input to the End-Of-File.

Output Format

Print all the integers from the array that are less than the given upper limit  X in value on separate lines. The sequence should be the same as it was in the original array.

Solution :- 

 

object FilterArray extends App{
def f(delim:Int,arr:List[Int]):List[Int] =
{ val l = scala.collection.mutable.ListBuffer.empty[Int]
arr.foreach { i => {if (i < delim) l+=i } }

l.toList

}
println(f(8,List(8,2,3,4,6,7,8,9)))
}

 

Output – List(2, 3, 4, 6, 7)

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s