Skip to content

Commit 24dc076

Browse files
committed
WIF - Combinators - Introduce majority combinator
1 parent 80a5ec6 commit 24dc076

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* @file
3+
* @author Richard Plny <[email protected]>
4+
* @brief Majority combinator interface
5+
*
6+
* SPDX-License-Identifier: BSD-3-Clause
7+
*/
8+
9+
#pragma once
10+
11+
#include "combinator.hpp"
12+
13+
#include <algorithm>
14+
15+
namespace WIF {
16+
17+
/**
18+
* @brief MajorityCombinator class
19+
*
20+
* Perform majority vote by finding the prevalent element
21+
*/
22+
class MajorityCombinator : public Combinator {
23+
public:
24+
/**
25+
* @brief Combine multiple values into one by using majority
26+
* The result is the first prevailing element.
27+
*
28+
* @throw std::runtime_error if an empty vector is passed
29+
* @param valuesToCombine vector of doubles to combine
30+
* @return double majority value in the provided vector
31+
*/
32+
double combine(const std::vector<double>& valuesToCombine) override;
33+
};
34+
35+
} // namespace WIF

src/wif/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ set(LIBWIF_SOURCES
55
classifiers/scikitMlClassifier.cpp
66
combinators/averageCombinator.cpp
77
combinators/binaryDSTCombinator.cpp
8+
combinators/majorityCombinator.cpp
89
combinators/sumCombinator.cpp
910
filesystem/fileModificationChecker.cpp
1011
ml/scikitMlWrapper.cpp
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* @file
3+
* @author Richard Plny <[email protected]>
4+
* @brief Majority combinator implementation
5+
*
6+
* SPDX-License-Identifier: BSD-3-Clause
7+
*/
8+
9+
#include "wif/combinators/majorityCombinator.hpp"
10+
11+
#include <numeric>
12+
#include <stdexcept>
13+
14+
namespace WIF {
15+
16+
static double findPrevalentElement(std::vector<double> values)
17+
{
18+
std::sort(values.begin(), values.end());
19+
20+
unsigned maxCount = 1;
21+
unsigned currentCount = 1;
22+
double candidate = values[0];
23+
24+
for (unsigned index = 1; index < values.size(); ++index) {
25+
if (values[index] == values[index - 1]) {
26+
++currentCount;
27+
} else {
28+
currentCount = 1;
29+
}
30+
31+
if (currentCount > maxCount) {
32+
maxCount = currentCount;
33+
candidate = values[index - 1];
34+
}
35+
}
36+
37+
return candidate;
38+
}
39+
40+
double MajorityCombinator::combine(const std::vector<double>& valuesToCombine)
41+
{
42+
if (valuesToCombine.empty()) {
43+
throw std::runtime_error("Nothing to combine! The supplied vector is empty.");
44+
}
45+
46+
return findPrevalentElement(valuesToCombine);
47+
}
48+
49+
} // namespace WIF

0 commit comments

Comments
 (0)