DEV Community

Discussion on: Daily Challenge #6 - Grandma and her friends

Collapse
 
kesprit profile image
kesprit • Edited

My solution in Swift, first time I use nested functions :

let distanceReferences = [ "X1": 100.0, "X2": 200.0, "X3": 250.0, "X4": 300.0 ]
let friendsReferences = [ "A1": "X1", "A2": "X2", "A3": "X3", "A4": "X4" ]
let friendsOrder = [ "A1", "A2", "A3", "A4", "A5"]

func grandmaTravel(friendsToVisit: [String]) -> Int {
    func distanceBetween(firstPoint: String, to secondPoint: String) -> Int {
        let first = distanceReferences.first {
            $0.key == firstPoint
        }

        let second = distanceReferences.first {
            $0.key == secondPoint
        }

        guard let distanceToFirst = first?.value, let distanceToSecond = second?.value
            else { return 0 }
        let result = (pow(distanceToSecond, 2) - pow(distanceToFirst, 2)).squareRoot()

        return Int(result.rounded())
    }

    var distance = 0
    var points = friendsToVisit.compactMap {
        friendsReferences[$0]
    }
    var currentPoint = points.removeFirst()

    // X0 to fist town
    distance += Int(distanceReferences[currentPoint] ?? 0)

    points.forEach {
        distance += distanceBetween(firstPoint: currentPoint, to: $0)
        currentPoint = $0
    }

    // last town to X0
    distance += Int(distanceReferences[currentPoint] ?? 0)

    return distance
}

grandmaTravel(friendsToVisit: friendsOrder)