#include using namespace std; string ltrim(const string &); string rtrim(const string &); vector split(const string &); enum struct OutputMode { HackerRank, Linux }; OutputMode outputMode = OutputMode::Linux; /* * Complete the 'weightedMean' function below. * * The function accepts following parameters: * 1. INTEGER_ARRAY X * 2. INTEGER_ARRAY W */ void weightedMean(vector X, vector W) { int numerator = 0, denominator = 0; for (size_t i = 0; i < X.size(); i++) { numerator += X[i] * W[i]; denominator += W[i]; } cout << fixed << setprecision(1) << numerator/double(denominator) << endl; } int main() { string n_temp; int n; if (outputMode == OutputMode::HackerRank) { getline(cin, n_temp); n = stoi(ltrim(rtrim(n_temp))); } else n = 5; string vals_temp_temp; if (outputMode == OutputMode::HackerRank) getline(cin, vals_temp_temp); else vals_temp_temp = "10 40 30 50 20"; vector vals_temp = split(rtrim(vals_temp_temp)); vector vals(n); for (int i = 0; i < n; i++) { int vals_item = stoi(vals_temp[i]); vals[i] = vals_item; } string weights_temp_temp; if (outputMode == OutputMode::HackerRank) getline(cin, weights_temp_temp); else weights_temp_temp = "1 2 3 4 5"; vector weights_temp = split(rtrim(weights_temp_temp)); vector weights(n); for (int i = 0; i < n; i++) { int weights_item = stoi(weights_temp[i]); weights[i] = weights_item; } weightedMean(vals, weights); return 0; } std::function f_isspace = [](int x){ return isspace(x); }; string ltrim(const string &str) { string s(str); s.erase( s.begin(), find_if(s.begin(), s.end(), not_fn(f_isspace)) ); return s; } string rtrim(const string &str) { string s(str); s.erase( find_if(s.rbegin(), s.rend(), not_fn(f_isspace)).base(), s.end() ); return s; } vector split(const string &str) { vector tokens; string::size_type start = 0; string::size_type end = 0; while ((end = str.find(" ", start)) != string::npos) { tokens.push_back(str.substr(start, end - start)); start = end + 1; } tokens.push_back(str.substr(start)); return tokens; }