如何从地图中获取最接近的值?

问题描述 投票:0回答:1

我有3个地图,一个密钥为Long,值为2个双元组的元组)

A : ( 123 -> (1.2,1.3), 567 -> (2.4,2.6), 1200 ->(3.6,5.9))  
B : ( 125 -> (1.22,1.33), 570 -> (2.44,2.66), 1205 ->(3.66,5.99))  
C:  ( 128 -> (1.222,1.3333), 575 -> (2.444,2.666), 1208 ->(3.666,5.999))  

对于A中的每个键,我想从B和C中检索最接近的值,并在结果映射中连接3。 由于上面的结果,我应该得到一个看起来像的结果图:

D : (123 -> ( (1.2,1.3), (1.22,1.33), (1.222,1.3333)), 567-> ((2.4,2.6),(2.44,2.66),(2.444,2.666)) , 1200-> ((3.6,5.9),(3.66,5.99), (3.666,5.999))  

我怎样才能以干净的scala方式实现这一目标?

scala maps binary-search
1个回答
1
投票

如果我理解你的要求,下面的内容应该得到你想要的:

def combineClosestKeys[V](m1: Map[Long, V], m2: Map[Long, V], m3: Map[Long, V]) = {
  def closest(x: Long, s: Iterable[Long]) = s.minBy(e => math.abs(e - x))

  m1.map{ case (k, v) =>
    (k, v :: m2(closest(k, m2.keys)) :: m3(closest(k, m3.keys)) :: Nil)
  }
}

请注意,上述方法假设提供的Maps非空。

使用方法:

val mapA = Map(123L -> (1.2, 1.3), 567L -> (2.4, 2.6), 1200L -> (3.6, 5.9))
val mapB = Map(125L -> (1.22, 1.33), 570L -> (2.44, 2.66), 1205L -> (3.66, 5.99))
val mapC = Map(128L -> (1.222, 1.3333), 575L -> (2.444, 2.666), 1208L -> (3.666, 5.999))

combineClosestKeys(mapA, mapB, mapC)
// res1: scala.collection.immutable.Map[Long,List[(Double, Double)]] = Map(
//   123 -> List((1.2,1.3), (1.22,1.33), (1.222,1.3333)),
//   567 -> List((2.4,2.6), (2.44,2.66), (2.444,2.666)),
//   1200 -> List((3.6,5.9), (3.66,5.99), (3.666,5.999))
// )
© www.soinside.com 2019 - 2024. All rights reserved.