Scala:Filter Positions in a List

Hacker Rank –


For a given list with integers, return a new list removing the elements at odd positions. The input and output portions will be handled automatically. You need to write a function with the recommended method signature.

Input Format

N integers contained in the list, each on a separate line.

Output Format

Output the list with the integers at odd positions removed i.e. the first element, the third element and so on. The relative positions of the remaining even-position elements should be the same as they were in the original array. Each integer will be on a separate line.


Solution – 

def f(arr:List[Int]):List[Int] = {

val l = scala.collection.mutable.ListBuffer.empty[Int]
val range=arr.indices.filter { x => x%2!=0 }
range.foreach { x => l += arr(x) }


Result –List(1, 3)


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s