Scala:Filter Positions in a List

Hacker Rank – https://www.hackerrank.com/challenges/fp-filter-positions-in-a-list?h_r=next-challenge&h_v=zen

 

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) }
l.toList

}

Result –List(1, 3)

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