Last active
August 31, 2018 11:46
-
-
Save ptrdom/87152a56d0f4522bff871845711713fc to your computer and use it in GitHub Desktop.
Finding closest number in sequence to given number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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