2

Find a number available in first array with numbers in second. If number not found get the immediate lower.

val a = List(1,2,3,4,5,6,7,8,9)
val b = List(1,5,10)

expected output after comparing a with b

1 --> 1
2 --> 1
3 --> 1
4 --> 1
5 --> 5
6 --> 5
7 --> 5
8 --> 5
9 --> 5

Thanks

4
  • 1
    Why is this tagged apache-spark? Commented Apr 28, 2018 at 20:23
  • Possible duplicate of Find the first element that satisfies condition X in a Seq Commented Apr 28, 2018 at 20:24
  • To be fair, not quite a duplicate, but it's that question + map. Commented Apr 28, 2018 at 20:25
  • Can I assume both input lists are sorted? Commented Apr 30, 2018 at 7:51

2 Answers 2

2

You can use TreeSet's to() and lastOption methods as follows:

val a = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
val b = List(1, 5, 10)

import scala.collection.immutable.TreeSet

// Convert list `b` to TreeSet
val bs = TreeSet(b.toSeq: _*)

a.map( x => (x, bs.to(x).lastOption.getOrElse(Int.MinValue)) ).toMap
// res1: scala.collection.immutable.Map[Int,Int] = Map(
//   5 -> 5, 1 -> 1, 6 -> 5, 9 -> 5, 2 -> 1, 7 -> 5, 3 -> 1, 8 -> 5, 4 -> 1
// )

Note that neither list a or b needs to be ordered.


UPDATE:

Starting Scala 2.13, methods to for TreeSet is replaced with rangeTo.

Sign up to request clarification or add additional context in comments.

Comments

0

Here is another approach using collect function

val a = List(1,2,3,4,5,6,7,8,9)
val b = List(1,5,10)
val result = a.collect{
  case e if(b.filter(_<=e).size>0) => e -> b.filter(_<=e).reverse.head
}
//result: List[(Int, Int)] = List((1,1), (2,1), (3,1), (4,1), (5,5), (6,5), (7,5), (8,5), (9,5))

Here for every element in a check if there is a number in b i.e. which is greater than or equal to it and reverse the filter list and get its head to make it a pair.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.