首页 > 解决方案 > How can I transform a numeric Scala array to be an array of intervals of the values from array?

问题描述

The overall goal is to take a numeric array and convert it to an array of intervals from that array. The intervals can be represented as tuples or arrays. Ultimately these will be converted into strings anyway. For example I would like Array(0,1,2,3) to become Array("0 to 1", "1 to 2", "2 to 3")

Here are some examples:

Example 1

Input: Array(0,1,2,3)

Output: Array((0,1), (1,2), (2,3))

Example 2

Input: Array(Double.NegativeInfinity,0,1,2,3,Double.PositiveInfinity)

Output: Array((Double.NegativeInfinity,0), (0,1), (1,2), (2,3), (3,Double.PositiveInfinity))

标签: arraysscala

解决方案


这就是sliding(2)Scala 集合的作用

scala> Array(0,1,2,3).sliding(2).toList
val res1: List[Array[Int]] = List(Array(0, 1), Array(1, 2), Array(2, 3))
scala> Array(Double.NegativeInfinity,0,1,2,3,Double.PositiveInfinity).sliding(2).toList
val res7: List[Array[Double]] = List(Array(-Infinity, 0.0), Array(0.0, 1.0), Array(1.0, 2.0), Array(2.0, 3.0), Array(3.0, Infinity))

要从滑动中获取输出并使字符串“0 到 1”、“1 到 2”等,正如您所注意到的,您可以使用map字符串插值。{}括号是插入arr(i)数组中的值 ( )所必需的。

Array(0,1,2,3).sliding(2).map(arr => s"${arr(0)} to ${arr(1)}").toList
val res19: List[String] = List(0 to 1, 1 to 2, 2 to 3)

推荐阅读