Created
November 3, 2015 15:13
-
-
Save fancellu/de501ac3ce9a6cef5e1b to your computer and use it in GitHub Desktop.
Closest Numbers for HackerRank
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
def closestNumbers(s:String):String={ | |
val sorted=s.split(" ").map(_.toInt).toList.sorted | |
val zip=sorted.zip(sorted.tail) | |
val triples=for { | |
(x,y)<-zip | |
} yield (x,y,Math.abs(x-y)) | |
val (_,_,minDelta)=triples.minBy(_._3) | |
val smallest=triples.filter(_._3==minDelta) | |
smallest.map{case (x,y,_)=>(s"$x $y")} mkString(" ") | |
} | |
println(closestNumbers("-20 -3916237 -357920 -3620601 7374819 -7330761 30 6246457 -6461594 266854 100 150")) | |
// -20 30 100 150 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment