DEV Community

loading...

Discussion on: Daily Challenge #216 - Rainfall

Collapse
mushtaqasif profile image
mushtaqasif

JS Solution

const [mean, variance] = (() => {
    const calc = (town, data, type = false) => {
        return data.split('\n').reduce((result, row) => {
            let [city, rainfallData] = row.split(':');

            if (city != town) return result;

            let rainfallMonthlyData = rainfallData.split(',');

            let rainfallAmounts = [];

            let mean = rainfallMonthlyData.reduce((total, record) => {
                let rainfallAmount = parseFloat(record.split(' ')[1]);

                rainfallAmounts.push(rainfallAmount);

                return total + rainfallAmount;
            }, 0) / rainfallMonthlyData.length; 

            return !type ? mean : rainfallAmounts.reduce((total, rainfallAmount) => 
                total + Math.pow((rainfallAmount - mean), 2)
            , 0) / rainfallMonthlyData.length; 
        }, -1);
    };

    return [
        (town, data) => calc(town, data),
        (town, data) => calc(town, data, true)
    ];
})();

console.log(JSON.stringify({
    London: {
        mean: mean("London", data),
        variance: variance("London", data)
    },
    mean: {
        Rome: mean('Rome', data1),
        Beijing: mean('Beijing', data)
    },
    variance: {
        Beijing: variance('Beijing', data1),
        Lima: variance('Lima', data)
    }
}, undefined, 4));

output:

{
    "London": {
        "mean": 51.199999999999996,
        "variance": 57.428333333333335
    },
    "mean": {
        "Rome": 71.77499999999999,
        "Beijing": 52.416666666666664
    },
    "variance": {
        "Beijing": 4437.038055555556,
        "Lima": 1.5790972222222222
    }
}