NumCpp  2.16.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
Loading...
Searching...
No Matches
mode.hpp
Go to the documentation of this file.
1
28#pragma once
29
30#include <algorithm>
31#include <complex>
32#include <unordered_map>
33#include <utility>
34
38#include "NumCpp/Core/Types.hpp"
39#include "NumCpp/NdArray.hpp"
40
41namespace nc
42{
43 //===========================================================================
44 // Method Description:
54 template<typename dtype, typename HashFunction = std::hash<dtype>>
56 {
57 const auto modeFunction =
59 {
60 std::unordered_map<dtype, int, HashFunction> counts{};
61 auto greatestCount = int{ 0 };
62 dtype mode{};
63 for (auto iter = iterBegin; iter != iterEnd; ++iter)
64 {
65 const auto& value = *iter;
66
67 if (counts.count(value) > 0)
68 {
69 auto& count = counts[value];
70 ++count;
71 if (count > greatestCount)
72 {
73 greatestCount = count;
74 mode = value;
75 }
76 }
77 else
78 {
79 counts.insert({ value, 1 });
80 }
81 }
82
83 return mode;
84 };
85
86 switch (inAxis)
87 {
88 case Axis::NONE:
89 {
91 return returnArray;
92 }
93 case Axis::COL:
94 {
96 for (uint32 row = 0; row < inArray.numRows(); ++row)
97 {
98 returnArray(0, row) = modeFunction(inArray.cbegin(row), inArray.cend(row));
99 }
100
101 return returnArray;
102 }
103 case Axis::ROW:
104 {
105 return mode(inArray.transpose(), Axis::COL);
106 }
107 default:
108 {
109 THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type.");
110 return {};
111 }
112 }
113 }
114
115 //============================================================================
116 // Method Description:
126 template<typename dtype>
133} // namespace nc
#define THROW_INVALID_ARGUMENT_ERROR(msg)
Definition Error.hpp:37
#define STATIC_ASSERT_ARITHMETIC(dtype)
Definition StaticAsserts.hpp:39
Custom const_iterator for NdArray.
Definition NdArrayIterators.hpp:41
Holds 1D and 2D arrays, the main work horse of the NumCpp library.
Definition NdArrayCore.hpp:139
Definition Cartesian.hpp:40
NdArray< dtype > mode(const NdArray< dtype > &inArray, Axis inAxis=Axis::NONE)
Definition mode.hpp:55
Axis
Enum To describe an axis.
Definition Enums.hpp:36
NdArray< dtype > arange(dtype inStart, dtype inStop, dtype inStep=1)
Definition arange.hpp:59
std::uint32_t uint32
Definition Types.hpp:40
Definition StdComplexOperators.hpp:125