53. Average rating of movies

The problem requires the computing of a movie rating using a truncated mean. This is a statistical measure of a central tendency where the mean is calculated after discarding parts of a probability distribution or sample at the high and low ends. Typically, this is done by removing an equal amount of points at the two ends. For this problem, you are required to remove 5% of both the highest and lowest user ratings.

A function that calculates a truncated mean for a given range should do the following:

  • Sort the range so that elements are ordered (either ascending or descending)
  • Remove the required percentage of elements at both ends
  • Count the sum of all remaining elements
  • Compute the average by dividing the sum to the remaining count of elements

The truncated_mean() function shown here implements the described algorithm:

double truncated_mean(std::vector<int> values, double const percentage)
{
std::sort(std::begin(values), std::end(values));
auto remove_count = static_cast<size_t>(
values.size() * percentage + 0.5);

values.erase(std::begin(values), std::begin(values) + remove_count);
values.erase(std::end(values) - remove_count, std::end(values));

auto total = std::accumulate(
std::cbegin(values), std::cend(values),
0ull,
[](auto const sum, auto const e) {
return sum + e; });
return static_cast<double>(total) / values.size();
}

A program that uses this function in order to calculate and print movie average ratings may look like the following:

struct movie
{
int id;
std::string title;
std::vector<int> ratings;
};

void print_movie_ratings(std::vector<movie> const & movies)
{
for (auto const & m : movies)
{
std::cout << m.title << " : "
<< std::fixed << std::setprecision(1)
<< truncated_mean(m.ratings, 0.05) << std::endl;
}
}

int main()
{
std::vector<movie> movies
{
{ 101, "The Matrix", {10, 9, 10, 9, 9, 8, 7, 10, 5, 9, 9, 8} },
{ 102, "Gladiator", {10, 5, 7, 8, 9, 8, 9, 10, 10, 5, 9, 8, 10} },
{ 103, "Interstellar", {10, 10, 10, 9, 3, 8, 8, 9, 6, 4, 7, 10} }
};

print_movie_ratings(movies);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset