首页 > 解决方案 > 从 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 的库,但似乎我是该语言的新手,但我不知道该怎么做。

标签: kotlin

解决方案


您可以使用勾股定理编写距离函数。(这个GeeksforGeeks 页面也可能有帮助。)

您还可以对点使用数据类,而不是使用具有两个双精度值的数组。下面的代码使用了Mateen Ulhaq在他的评论中建议的方法,有两个修改:

  1. 添加“指向”让我们可以创建一个从一个点到最近的十个点的地图(所以我们知道这十个点与哪个点相关)。
  2. 在“.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)
    }
}

推荐阅读