For my first attempt at Scala I decided to solve a simple exercise on codingame.com.
Based on a string input containing the user location, the defibrillators count and a list of defibrillators entries (id, name, address, phone number, longitude, latitude), I have to print the closest defibrillator from the user. The distance formula is given in the rules.
An example of input:
3,879483 43,608177 3 1;Maison de la Prevention Sante;6 rue Maguelone 340000 Montpellier;;3,87952263361082;43,6071285339217 2;Hotel de Ville;1 place Georges Freche 34267 Montpellier;;3,89652239197876;43,5987299452849 3;Zoo de Lunaret;50 avenue Agropolis 34090 Mtp;;3,87388031141133;43,6395872778854
import math._
import scala.util._
object Solution extends App {
val playerLongitude = readLine
val playerLatitude = readLine
val defibrilatorCount = readInt
def sanitizeString(string : String) : String = string.replace(',', '.')
def stringToDouble(string : String) : Double = sanitizeString(string).toDouble
val playerLongitudeValue = stringToDouble(playerLongitude)
val playerLatitudeValue = stringToDouble(playerLatitude)
def distanceToPlayer(long : Double, lat : Double) : Double = {
val x = (long - playerLongitudeValue) * cos((playerLatitudeValue + lat) / 2)
val y = lat - playerLatitudeValue
sqrt(x * x + y * y) * 6371;
}
def distanceToPlayer(stringInput : String) : Double = {
val tokens = sanitizeString(stringInput).split(";")
distanceToPlayer(tokens(4).toDouble, tokens(5).toDouble)
}
var smallestDistance = Double.MaxValue
var closestDefibName = ""
for(i <- 0 until defibrilatorCount) {
val defib = readLine
val distance = distanceToPlayer(defib)
if(distance < smallestDistance) {
smallestDistance = distance
closestDefibName = defib.split(";")(1)
}
}
println(closestDefibName)
}