#include "Numeric_array_2.hpp" #include #include #include #include #include ///////////////// // Constructor // ///////////////// // Construct an empty array with an initial // capacity of CAPACITY_INCREMENT (10). // An empty array is considered sorted. Numeric_array_2::Numeric_array_2(): capacity_ { CAPACITY_INCREMENT }, array_ { new double[CAPACITY_INCREMENT] }, size_ { 0 }, sum_ { 0.0 }, sum_of_squares_ { 0.0 }, min_idx_ {}, // Not defined until one entry max_idx_ {}, // is added to the array is_sorted_ { true } { // All member variables are initialized in the initializer list. } //////////////////////////////////////////////////////// // Destructor, copy constructor, move constructor, // // assignment operator, and move assignment operator // //////////////////////////////////////////////////////// // Free the dynamically allocated memory. // The destructor is called when the object is destroyed. Numeric_array_2::~Numeric_array_2() { delete[] array_; capacity_ = 0; array_ = nullptr; size_ = 0; sum_ = 0; sum_of_squares_ = 0; min_idx_ = 0; max_idx_ = 0; is_sorted_ = true; } // Construct a deep copy of another array: // Allocate new memory and copy all the existing entries. Numeric_array_2::Numeric_array_2( Numeric_array_2 const &other ): capacity_ { other.capacity() }, array_ { new double[other.capacity()] }, size_ { other.size() }, sum_ { other.sum_ }, sum_of_squares_ { other.sum_of_squares_ }, min_idx_ { other.min_idx_ }, max_idx_ { other.max_idx_ }, is_sorted_ { other.is_sorted() } { for ( std::size_t k{ 0 }; k < size(); ++k ) { array_[k] = other.array_[k]; } } // Move the contents of another array into this array: // Take ownership of its memory and leave the other array empty. Numeric_array_2::Numeric_array_2( Numeric_array_2 &&other ) noexcept: capacity_ { other.capacity() }, array_ { other.array_ }, size_ { other.size() }, sum_ { other.sum_ }, sum_of_squares_ { other.sum_of_squares_ }, min_idx_ { other.min_idx_ }, max_idx_ { other.max_idx_ }, is_sorted_ { other.is_sorted() } { other.capacity_ = 0; other.array_ = nullptr; other.size_ = 0; other.sum_ = 0.0; other.sum_of_squares_ = 0.0; other.min_idx_ = 0; other.max_idx_ = 0; other.is_sorted_ = true; } // Replace this array with a deep copy of another array. // - Reuse the allocated memory if the capacities are equal. Numeric_array_2 &Numeric_array_2::operator=( Numeric_array_2 const &other ) { if ( this == &other ) { return *this; } if ( capacity_ != other.capacity_ ) { double *new_array{ new double[other.capacity_] }; for ( std::size_t k{ 0 }; k < other.size_; ++k ) { new_array[k] = other.array_[k]; } delete[] array_; array_ = new_array; capacity_ = other.capacity_; } else { for ( std::size_t k{ 0 }; k < other.size_; ++k ) { array_[k] = other.array_[k]; } } size_ = other.size_; sum_ = other.sum_; sum_of_squares_ = other.sum_of_squares_; min_idx_ = other.min_idx_; max_idx_ = other.max_idx_; is_sorted_ = other.is_sorted_; return *this; } // Replace this array by moving another array: // Release the old memory and take ownership of the other's memory. Numeric_array_2 &Numeric_array_2::operator=( Numeric_array_2 &&other ) noexcept { if ( this == &other ) { return *this; } delete[] array_; capacity_ = other.capacity(); array_ = other.array_; size_ = other.size(); sum_ = other.sum_; sum_of_squares_ = other.sum_of_squares_; min_idx_ = other.min_idx_; max_idx_ = other.max_idx_; is_sorted_ = other.is_sorted(); other.capacity_ = 0; other.array_ = nullptr; other.size_ = 0; other.sum_ = 0.0; other.sum_of_squares_ = 0.0; other.min_idx_ = 0; other.max_idx_ = 0; other.is_sorted_ = true; return *this; } /////////////////////////////////////////////////////// // Accessors (observers or queries): // // Member functions that return information about // // an object without modifing that object. // /////////////////////////////////////////////////////// // Return the number of elements currently stored in the array. // - This may be less than the allocated capacity. std::size_t Numeric_array_2::size() const noexcept { return size_; } // Return the number of elements that can be stored // without allocating additional memory. std::size_t Numeric_array_2::capacity() const noexcept { return capacity_; } // Return true if the elements are in nondecreasing order. // - An empty array or an array with one element is sorted. bool Numeric_array_2::is_sorted() const noexcept { return is_sorted_; } // Return the value stored at the given index. // - Throw an exception if the index is out of range. double Numeric_array_2::operator[](std::size_t n) const { if ( n >= size() ) { throw std::out_of_range{ "Numeric_array_2 index out of range" }; } return array_[n]; } // Return the index of the first occurrence of the minimum. // - If sorted, the minimum is at index zero. std::size_t Numeric_array_2::min() const { if ( size() == 0 ) { throw std::domain_error{ "You cannot find the minimum of an empty array" }; } return min_idx_; } // Return the index of the last occurrence of the maximum. // - If sorted, the maximum is at the final index. std::size_t Numeric_array_2::max() const { if ( size_ == 0 ) { throw std::domain_error{ "You cannot find the maximum of an empty array" }; } return max_idx_; } // Calculate the arithmetic mean of the entries. // - Throw an exception if the array is empty. double Numeric_array_2::mean() const { if ( size() == 0 ) { throw std::domain_error{ "You cannot calculate the mean (the average value) of an empty array" }; } return sum_/static_cast( size() ); } // Calculate the population standard deviation of the entries. // - Divide the sum of squared deviations from the mean // by the number of entries. // - Throw an exception if the array is empty. double Numeric_array_2::std_dev() const { if ( size() == 0 ) { throw std::domain_error{ "You cannot calculate the standard deviation of empty array" }; } return std::sqrt( sum_of_squares_/size() - mean()*mean() ); } // Calculate the median without modifying the original array. // - If unsorted, make a copy, sort it, and calculate its median. // - Throw an exception if the array is empty. double Numeric_array_2::median() const { if ( size() == 0 ) { throw std::domain_error{ "You cannot determine the median of empty array" }; } // If this array is not sorted, // make a copy, sort it, and find the median of that array if ( !is_sorted() ) { Numeric_array_2 sorted_copy{ *this }; sorted_copy.sort(); return sorted_copy.median(); } std::size_t middle{ size()/2 }; if ( size()%2 == 1 ) { return array_[middle]; } else { // Halving before addition avoids overflow of the sum in some cases. return array_[middle - 1]/2.0 + array_[middle]/2.0; } } // Search for a value using linear or binary search, // depending on whether the array is sorted. // - Return a matching index, or size() if not found. std::size_t Numeric_array_2::find( double x ) const { check_for_inf_or_NaN( x ); // If the array is not sorted, // perform a linear search if ( !is_sorted() ) { for ( std::size_t k{ 0 }; k < size(); ++k ) { if ( array_[k] == x ) { return k; } } return size(); } assert( is_sorted() ); // Perform a binary search on a sorted array std::size_t low{ 0 }; std::size_t high{ size() }; while ( low < high ) { std::size_t middle{ low + (high - low)/2 }; if ( array_[middle] == x ) { return middle; } else if ( array_[middle] < x ) { low = middle + 1; } else { high = middle; } } return size(); } /////////////////////////////////////////////// // Mutators (modifiers): // // - Member functions that will modify or // // change the contents of the object. // /////////////////////////////////////////////// // Append a value to the end of the array: // Update the sorted status and return the index of the new entry. std::size_t Numeric_array_2::append( double x ) { check_for_inf_or_NaN( x ); if ( size() == capacity() ) { increase_capacity(); } // If the appended value is less than the entry at // the end of the array, the array is no longer sorted if ( size() == 0) { sum_ = x; sum_of_squares_ = x*x; min_idx_ = 0; max_idx_ = 0; } else { if ( x < array_[size() - 1] ) { is_sorted_ = false; } sum_ += x; sum_of_squares_ += x*x; if ( x < array_[min_idx_] ) { min_idx_ = size(); } else if ( x >= array_[max_idx_] ) { max_idx_ = size(); } } array_[size()] = x; return size_++; } // Insert a value as though the array were sorted. // - Shift larger preceding entries and return the insertion index. std::size_t Numeric_array_2::insert( double x ) { // If the array is empty, just call append // - It will initialize all the member variables appropriately if ( size() == 0 ) { return append( x ); } check_for_inf_or_NaN( x ); if ( size() == capacity() ) { increase_capacity(); } std::size_t k{ size() }; while ( (k > 0) && (array_[k - 1] > x) ) { array_[k] = array_[k - 1]; --k; } sum_ += x; sum_of_squares_ += x*x; if ( k <= min_idx_ ) { ++min_idx_; } if ( x < array_[min_idx_] ) { min_idx_ = k; } if ( k <= max_idx_ ) { ++max_idx_; } if ( x >= array_[max_idx_] ) { max_idx_ = k; } array_[k] = x; ++size_; // The previous sorted status remains correct. return k; } // Sort the array into non-decreasing order using insertion sort. // - Return the number of inversions removed during sorting. std::size_t Numeric_array_2::sort() noexcept { if ( is_sorted() ) { return 0; } // Count and return the number of inversions: // - A sorted array has zero inversions. // n(n - 1) // - A strictly decreasing array has -------- inversions. // 2 std::size_t inversion_count{ 0 }; for ( std::size_t k{ 1 }; k < size(); ++k ) { double value{ array_[k] }; std::size_t j{ k }; while ( (j > 0) && (array_[j - 1] > value) ) { array_[j] = array_[j - 1]; ++inversion_count; // Each move removes one inversion --j; } array_[j] = value; } is_sorted_ = true; max_idx_ = size() - 1; min_idx_ = 0; return inversion_count; } ////////////////////////////// // Private helper functions // ////////////////////////////// // Increase the capacity by CAPACITY_INCREMENT (currently 10). // Allocate new memory, copy the entries, and release the old memory. void Numeric_array_2::increase_capacity() { std::size_t new_capacity{ capacity_ + CAPACITY_INCREMENT }; double *new_array{ new double[new_capacity] }; for ( std::size_t k{ 0 }; k < size_; ++k ) { new_array[k] = array_[k]; } delete[] array_; array_ = new_array; capacity_ = new_capacity; } // Check that the given value is finite. // Throw an exception if it is infinity or NaN. void Numeric_array_2::check_for_inf_or_NaN( double x ) { if ( !std::isfinite( x ) ) { throw std::invalid_argument{ "Values must be finite (not +inf, -inf, or NaN)" }; } } //////////////////////////////////// // Global functions and operators // //////////////////////////////////// // Insert the array into an output stream. // - Display the entries in braces, separated by commas. std::ostream &operator<<( std::ostream &out, Numeric_array_2 const &array ) { if ( array.size() == 0 ) { out << "{}"; return out; } out << "{" << array[0]; for ( std::size_t k{ 1 }; k < array.size(); ++k ) { out << ", " << array[k]; } out << "}"; return out; }