1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
#include <iostream>
#include <algorithm> // std::minmax_element
#include <cmath> // NAN
#include <numeric> // std::accumulate
// replace one smallest and one largest element of the sequence with zeroes
void zero_minmax_elements( int array[], int sz ) {
if( array == nullptr || sz < 1 ) return ;
// https://en.cppreference.com/w/cpp/algorithm/minmax_element
const auto [ psmallest, plargest ] = std::minmax_element( array, array+sz ) ;
*psmallest = 0 ;
*plargest = 0 ;
}
// return the average after setting one smallest element and
// one largest element of the array to zeroes
double zero_minmax_and_average( int array[], int sz ) {
if( array == nullptr || sz < 1 ) return double(NAN) ;
zero_minmax_elements( array, sz ) ;
// https://en.cppreference.com/w/cpp/algorithm/accumulate
return std::accumulate( array, array+sz, 0.0 ) / sz ;
}
void zero_minmax_elements_home_grown( int array[], int sz ) {
if( array == nullptr || sz < 1 ) return ;
int pos_min = 0 ;
int pos_max = 0 ;
for( int i = 1 ; i < sz ; ++i ) {
if( array[i] < array[pos_min] ) pos_min = i ;
if( array[pos_max] < array[i] ) pos_max = i ;
}
array[pos_min] = 0 ;
array[pos_max] = 0 ;
}
double zero_minmax_and_average_home_grown( int array[], int sz ) {
if( array == nullptr || sz < 1 ) return double(NAN) ;
zero_minmax_elements_home_grown( array, sz ) ;
double sum = 0 ;
for( int i = 0 ; i < sz ; ++i ) sum += array[i] ;
return sum / sz ;
}
int main() {
const int N = 10 ;
{
int input[N] = { 85, 38, 77, 20, 28, 6, 70, 88, 12, 27 };
std::cout << zero_minmax_and_average( input, N ) << '\n' ; // 35.7
}
{
int input[N] = { 85, 38, 77, 20, 28, 6, 70, 88, 12, 27 };
std::cout << zero_minmax_and_average_home_grown( input, N ) << '\n' ; // 35.7
}
}
|