Skip to content

Instantly share code, notes, and snippets.

@ptrdom
Last active August 31, 2018 11:46
Show Gist options
  • Save ptrdom/87152a56d0f4522bff871845711713fc to your computer and use it in GitHub Desktop.
Save ptrdom/87152a56d0f4522bff871845711713fc to your computer and use it in GitHub Desktop.
Finding closest number in sequence to given number
val entryPoint = 0
val points = List(-2, -1, 0, 1, 2, 3, 4)
val closest = points
.reduceLeftOption {
(point1, point2) =>
val distance1 = Math.sqrt(Math.pow(entryPoint - point1, 2))
val distance2 = Math.sqrt(Math.pow(entryPoint - point2, 2))
if (distance1 < distance2) {
point1
} else {
point2
}
}
println(closest)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment