CodeWars 计算一个城市的降雨量

dataand data1 are two strings with rainfall records of a few cities for months from January to December. The records of towns are separated by \n. The name of each town is followed by :.

data and towns can be seen in “Your Test Cases:”.

Task:

function: mean(town, strng) should return the average of rainfall for the city town and the strng data or data1.
function: variance(town, strng) should return the variance of rainfall for the city town and the strng data or data1.
Examples:

mean(“London”, data), 51.19(9999999999996)
variance(“London”, data), 57.42(833333333374)
Notes:

if functions mean or variance have as parameter town a city which has no records return -1
Don’t truncate or round: the tests will pass if abs(your_result - test_result) <= 1e-2 or abs((your_result - test_result) / test_result) <= 1e-6 depending on the language (see function assertFuzzyEquals).
http://www.mathsisfun.com/data/standard-deviation.html
data and data1 are adapted from http://www.worldclimate.com

注意:城主名字的大小写

import static java.util.stream.Collectors.averagingDouble;

import java.util.ArrayList;
import java.util.List;

public class Rainfall {

  public static double mean(String town, String strng) {
    return parseTemp(town, strng).stream()
        .collect(averagingDouble(n -> n));
  }

  public static double variance(String town, String strng) {
    double mean = mean(town, strng);
    if (mean == -1.0) return -1.0;

    return parseTemp(town, strng).stream()
        .collect(averagingDouble(n -> (n - mean) * (n - mean)));

  }

  private static List<Double> parseTemp(String town, String strng) {
    List<Double> temps = new ArrayList<>();
    for (String line : strng.split("\\n")) {
      String[] data = line.split(":");
      if (town.equals(data[0])) {
        for (String weather : data[1].split(",")) {
          String[] temp = weather.split("\\s");
          temps.add(Double.parseDouble(temp[1]));
        }
        break;
      }
    }

    if (temps.isEmpty()) temps.add(-1.0);

    return temps;
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值