Skip to content

Instantly share code, notes, and snippets.

@Dwite
Created March 14, 2023 22:22
Show Gist options
  • Save Dwite/1c193a5eb6521265eea9b4a77600c6ae to your computer and use it in GitHub Desktop.
Save Dwite/1c193a5eb6521265eea9b4a77600c6ae to your computer and use it in GitHub Desktop.
import kotlin.math.max
data class Location(val latitude: Double, val longitude: Double)
fun longestUncommonSubsequence(arr1: List<Location>, arr2: List<Location>): Pair<Int, Int> {
if (arr1 == arr2) {
// If both lists are equal, return -1 as both start and end indices
return Pair(-1, -1)
}
val m = arr1.size
val n = arr2.size
val lcs = Array(m + 1) { IntArray(n + 1) }
for (i in 0..m) {
for (j in 0..n) {
if (i == 0 || j == 0) {
lcs[i][j] = 0
} else if (arr1[i - 1].latitude == arr2[j - 1].latitude && arr1[i - 1].longitude == arr2[j - 1].longitude) {
lcs[i][j] = lcs[i - 1][j - 1] + 1
} else {
lcs[i][j] = max(lcs[i - 1][j], lcs[i][j - 1])
}
}
}
var start = -1
var end = -1
var maxLength = 0
var length = 0
for (i in 1..m) {
if (lcs[i][n] != lcs[i - 1][n]) {
if (length == 0) {
start = i - 1
}
length++
} else {
if (length > maxLength) {
maxLength = length
end = i - 1
}
length = 0
}
}
if (length > maxLength) {
maxLength = length
end = m
}
if (start == -1) {
start = 0
}
return Pair(start, end)
}
fun main() {
val arr1 = listOf(
Location(40.7128, -74.0060),
Location(37.7749, -122.4194),
Location(51.5074, -0.1278),
Location(35.6895, 139.6917),
Location(34.0522, -118.2437)
)
val arr2 = listOf(
Location(40.7128, -74.0060),
Location(37.7749, -122.4194),
Location(51.5074, -0.1278),
Location(35.6895, 139.6917),
Location(34.0522, -118.2437)
)
val (start, end) = longestUncommonSubsequence(arr1, arr2)
println("The longest uncommon subsequence starts at index $start and ends at index $end.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment