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

FULL DISCUSSION
 

Swift is the most elegant concise and bestest language... ;)

nums.reduce(nums[0]) { abs($0-given_num) < abs($1-given_num) ? $0 : $1 } 

Of course in actual usage we would make this an extension and check the validity of the array. I came across this post because I needed it so this one's for CGFloat, which is a Swift floating point type (Double, really)

extension CGFloat {    
    func nearest(arr: [CGFloat]) -> CGFloat {
        guard arr.count > 0 else {
            fatalError("array cannot be empty")
        }
        return arr.reduce(arr[0]) { abs($0-self) < abs($1-self) ? $0 : $1 } 
    }
}

let nums: [CGFloat] = [100, 200, 400, 800, 1600, 3200, 6400, 128000] 
let given_num = CGFloat(900)

let nearest = given_num.nearest(nums)

code of conduct - report abuse