Robert Eisele
Engineer, Systems Architect and DBA

Codingame: Defibrillators

Original Problem

The Goal

The city of Montpellier has equipped its streets with defibrillators to help save victims of cardiac arrests. The data corresponding to the position of all defibrillators is available online.

Based on the data we provide in the tests, write a program that will allow users to find the defibrillator nearest to their location using their mobile phone.
The input data you require for your program is provided in text format.
This data is comprised of lines, each of which represents a defibrillator. Each defibrillator is represented by the following fields:
  • A number identifying the defibrillator
  • Name
  • Address
  • Contact Phone number
  • Longitude (degrees)
  • Latitude (degrees)
These fields are separated by a semicolon (;).

Beware: the decimal numbers use the comma (,) as decimal separator. Remember to turn the comma (,) into dot (.) if necessary in order to use the data in your program.
The distance d between two points A and B will be calculated using the following formula:
Note: In this formula, the latitudes and longitudes are expressed in radians. 6371 corresponds to the radius of the earth in km.

The program will display the name of the defibrillator located the closest to the user’s position. This position is given as input to the program.

Game Input


Line 1: User's longitude (in degrees)

Line 2: User's latitude (in degrees)

Line 3: The number N of defibrillators located in the streets of Montpellier

N next lines: a description of each defibrillator

The name of the defibrillator located the closest to the user’s position.
0 < N < 10000

Scala Solution

Given the formula, we can calculate the distance between the geo-locations and the given point to find the location with the minimum distance:

import math._
import scala.util._

object Geo {

    def dist(lat1:String, lon1:String, lat2:String, lon2:String):Double = {

        val la1 = lat1.replace(",", ".").toDouble;
        val lo1 = lon1.replace(",", ".").toDouble;
        val la2 = lat2.replace(",", ".").toDouble;
        val lo2 = lon2.replace(",", ".").toDouble;

        val x = (lo2 - lo1) * cos((la1 + la2) / 2);
        val y = (la2 - la1);

        return sqrt(x * x + y * y) * 6371;

object Solution extends App {

    var minName:String = ""
    var minDist:Double = 10000000000.0

    val lon = readLine
    val lat = readLine
    val n   = readInt

    for(i <- 0 until n) {
        val defib = readLine

        val e = defib.split(";")
        val d = Geo.dist(lat, lon, e(5), e(4))

        if (minDist > d) {
            minDist = d
            minName = e(1)

Go to overview

All images are copyright to Codingame