kotlin - 从 Kotlin 中每个坐标的坐标数组中找到 10 个最近的点
问题描述
我有一个数组
var poses = arrayOf<Array<Double>>()
我使用循环填充。
输出看起来像这样:
poses.forEach {
println(Arrays.toString(it))
}
[-71.42510166478651, 106.43593221597114]
[104.46430594348055, 78.62761919208839]
[100.27031925094859, 79.65568893000942]
[311.2433803626159, 233.67219485640456]
[330.3015877764689, -114.9000129699181]
[34.76986782382592, -383.71914014833436]
[355.477931403836, -173.29388985868835]
[322.72821807215564, -45.99138725647516]
...
有没有一种有效的方法可以从这个列表中为每个坐标找到 10 个最近的点?例如:找到 [-71.42510166478651, 106.43593221597114] 的 10 个最近点,然后[104.46430594348055, 78.62761919208839]等等。我尝试查看 Kotlin 的类似 numpy 的库,但似乎我是该语言的新手,但我不知道该怎么做。
解决方案
您可以使用勾股定理编写距离函数。(这个GeeksforGeeks 页面也可能有帮助。)
您还可以对点使用数据类,而不是使用具有两个双精度值的数组。下面的代码使用了Mateen Ulhaq在他的评论中建议的方法,有两个修改:
- 添加“指向”让我们可以创建一个从一个点到最近的十个点的地图(所以我们知道这十个点与哪个点相关)。
- 在“.take(10)”之前对“.drop(1)”的调用将点本身保留在其列表之外(因为到自身的距离为 0)。
此代码使用点列表,确定最近的点并为每个点打印它们:
fun main() {
val poses = listOf(
Point(-71.42510166478651, 106.43593221597114),
Point(104.46430594348055, 78.62761919208839),
Point(100.27031925094859, 79.65568893000942),
Point(311.2433803626159, 233.67219485640456),
Point(330.3015877764689, -114.9000129699181),
Point(34.76986782382592, -383.71914014833436),
Point(355.477931403836, -173.29388985868835),
Point(322.72821807215564, -45.99138725647516)
)
val nearestPoints = poses.map {
point -> point to poses.sortedBy { point.distance(it) }.drop(1).take(10)
}
println("Nearest points:")
nearestPoints.forEach {
println("${it.first} is closest to ${it.second}")
}
}
data class Point(val x: Double, val y: Double) {
fun distance(that: Point): Double {
val distanceX = this.x - that.x
val distanceY = this.y - that.y
return sqrt(distanceX * distanceX + distanceY * distanceY)
}
}
推荐阅读
- python - 无法在pycharm中创建文件
- r - R中的Neuralnet包不断在数字/向量/矩阵参数上给出错误消息
- cql - 为什么 CQL 建议我在更新时使用 ALLOW FILTERING?
- node.js - “错误:接收到的数据包顺序错误。” 当连接到无服务器极光时
- node.js - 为什么我无法更新 npm 包依赖关系?
- html - 如何使背景图像居中/覆盖div,但带有填充
- unity3d - 在渲染任何 ARCore 模型之前截图
- javascript - 使用谷歌脚本功能触发谷歌网络应用
- javascript - 选择/选项的重复键错误,但我正在使用 UUID
- php - 尽管 phpinfo() 和 php -m 将其显示为已启用,但 XMLWriter 无法正常工作