BobbyB BobbyB - 1 year ago 159
Swift Question

Swift string iterate and compare

I'm new so bare with me.

I'm playing on the website CodinGame. The task is to find the number closest to zero. This is what you are given.

let n = Int(readLine()!)! // the number of temperatures to analyse
let temps = readLine()! // the n temperatures expressed as integers ranging from -273 to 5526

I have no idea what to do. I'm guessing there is many way to go about it.

Answer Source

So you have a String containing something like "4 -6 8 12 -12" and you want extract the Int closest to zero.

Here's the solution

import Foundation

let text = "4 -6 8 12 -12"
let numbers = text.componentsSeparatedByString(" ").flatMap { Int($0) }
if let closestToZero = numbers.minElement({ abs($0) < abs($1)}) {
    print(closestToZero) // -1

Compact version

Same logic, less code

let closestToZero = text.componentsSeparatedByString(" ")
    .flatMap { Int($0) }
    .minElement{ abs($0) < abs($1) }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download