arrays - 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))
解决方案
这就是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)
推荐阅读
- json - 如何在本地文件系统中将嵌套的 Dart 模型(和列表)保存为 JSON
- google-apps-script - 从 Google 表格复制到 Google 文档,无需更改格式
- php - 邮箱收到时如何隐藏回复标题?
- mysql - MySQL:在后台查询中使用索引
- web-applications -
web.config 中的标签使网站正常运行。没有它,它运行非常缓慢 - javascript - 如何在启动时加载 Outlook 365 Add in 以在 Add in 中运行特定代码?
- java - 应用程序未启动 - 内存不足
- java - 根据大小动态切换列
- html - 如何使表格中间变厚,如上面的示例图二
- c# - 无法将从 Arduino 读取的值分配到我的 Visual Studio 控件中,但值在 Visual Studio 的 MsgBox 中显示