Sat
Sat

Reputation: 33

How to compare two integer array in Scala?

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

Upvotes: 2

Views: 1011

Answers (2)

Leo C
Leo C

Reputation: 22449

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.

Upvotes: 2

Puneeth Reddy V
Puneeth Reddy V

Reputation: 1568

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.

Upvotes: 0

Related Questions