Journey to the Moon

  • + 0 comments

    JavaScript

    function journeyToMoon(n, astronaut) {
        // Write your code here
        let arr = []
        for (let i = 0; i < n; i++) arr[i] = [i]
        for (let i = 0; i < astronaut.length; i++) {
            let [m, n] = astronaut[i]
            if (arr[m] === arr[n]) continue
            if (arr[m].length < arr[n].length) [m, n] = [n, m]
            for (let temp of arr[n]) arr[m].push(temp), arr[temp] = arr[m]
        }
        let groups = new Set()
        for (let temp of arr) groups.add(temp)
        // console.log(arr)
        // console.log(groups)
        let countries = Array.from(groups), sum = 0
        for (let i = 0; i < countries.length - 1; i++) {
            for (let j = i + 1; j < countries.length; j++) {
                sum += countries[i].length * countries[j].length
            }
        }
        return sum
    }