mean, mode and median

#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <utility> using namespace std; vector<double> remove1elem(vector<double> a, double elem) { vector<double> retvect; for (int i = 0; i < a.size(); i++) { if (a[i]!=elem) { retvect.push_back(a[i]); } } return retvect; } double sum(vector<double> a) { double s = 0; for (int i = 0; i < a.size(); i++) { s += a[i]; } return s; } float mean(vector<double> a) { return sum(a) / a.size(); } double median(vector<double> a) { sort(a.begin(), a.end()); int sz = a.size(); if (sz % 2) { return a[(sz + 1) / 2 - 1]; } else { return (a[sz / 2 - 1] + a[sz / 2]) / 2; } } double mode(vector<double> a) { vector<double> nums; vector<int> counts; while (a.size()!=0) { nums.push_back(a[0]); counts.push_back(count(a.begin(), a.end(), nums[nums.size()-1])); //remove(a.begin(), a.end(), nums.end()); a=remove1elem(a, nums[nums.size() - 1]); } int maxcount = counts[0]; double modeval = nums[0]; for (int i = 0; i < counts.size(); i++) { if (counts[i]>maxcount) { maxcount = counts[i]; modeval = nums[i]; } if (counts[i] == maxcount) { if (nums[i] < modeval) { modeval = nums[i]; } } } return modeval; } int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ double N; cin >> N; vector<double> num(N); for (int i = 0; i < num.size(); i++) { cin >> num[i]; } cout << mean(num) << endl << median(num) << endl << mode(num) << endl; return 0; }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.