re: Challenge: Get Closest Number in an Array VIEW POST

FULL DISCUSSION
 

Hey! Let's do it the Scala way:

def closestNumber(x: Int, y: Int, givenNumber: Int): Int = {
    if(abs(givenNumber-x) > abs(givenNumber-y)) {
        y
    } else {
        x
    }
}

val givenNumber = 900
val nums = List(100, 200, 400, 800, 1600, 3200, 6400, 128000)
println(nums.reduce((x, y) => closestNumber(x, y, givenNumber)))
//==> Prints 800

Thanks for the challenge!

code of conduct - report abuse