Smartcar Shield
Utilities.hpp
Go to the documentation of this file.
1 
5 #pragma once
6 
7 namespace smartcarlib
8 {
9 namespace utils
10 {
23 template <typename AnyNumber>
24 constexpr AnyNumber getAbsolute(AnyNumber number)
25 {
26  return number < 0 ? -number : number;
27 }
28 
45 template <typename AnyNumber>
46 constexpr AnyNumber getConstrain(AnyNumber number, AnyNumber min, AnyNumber max)
47 {
48  return number < min ? min : (number > max ? max : number);
49 }
50 
65 template <typename AnyNumber>
66 AnyNumber getMedian(AnyNumber unsortedNumbers[], const unsigned int& arraySize)
67 {
68  // Sort the array using bubble sort
69  for (unsigned int i = 0; i < arraySize - 1; i++)
70  {
71  for (unsigned int j = 0; j < arraySize - 1 - i; j++)
72  {
73  if (unsortedNumbers[j] > unsortedNumbers[j + 1])
74  {
75  auto swappedValue = unsortedNumbers[j];
76  unsortedNumbers[j] = unsortedNumbers[j + 1];
77  unsortedNumbers[j + 1] = swappedValue;
78  }
79  }
80  }
81  // Return the Median value now that the array is sorted
82  return unsortedNumbers[arraySize / 2];
83 }
84 
103 template <typename AnyNumber>
104 constexpr AnyNumber getMap(
105  AnyNumber valueToMap, AnyNumber fromLow, AnyNumber fromHigh, AnyNumber toLow, AnyNumber toHigh)
106 {
107  return fromHigh == fromLow
108  ? toLow
109  : (valueToMap - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow;
110 }
111 
124 constexpr bool areAlmostEqual(float a, float b)
125 {
126  // C++11 does not allow us to declare the delta as a variable within the function body
127  // NOLINTNEXTLINE(readability-magic-numbers)
128  return getAbsolute(getAbsolute(a) - getAbsolute(b)) <= 0.001F;
129 }
130 } // namespace utils
131 } // namespace smartcarlib
smartcarlib
Definition: DistanceCar.hpp:11
smartcarlib::utils::getMedian
AnyNumber getMedian(AnyNumber unsortedNumbers[], const unsigned int &arraySize)
Gets the median value out of the supplied number array.
Definition: Utilities.hpp:66
smartcarlib::utils::getMap
constexpr AnyNumber getMap(AnyNumber valueToMap, AnyNumber fromLow, AnyNumber fromHigh, AnyNumber toLow, AnyNumber toHigh)
Maps a value from a range to another.
Definition: Utilities.hpp:104
smartcarlib::utils::getAbsolute
constexpr AnyNumber getAbsolute(AnyNumber number)
Gets the absolute of the supplied number.
Definition: Utilities.hpp:24
smartcarlib::utils::areAlmostEqual
constexpr bool areAlmostEqual(float a, float b)
Compares two floating point numbers.
Definition: Utilities.hpp:124
smartcarlib::utils::getConstrain
constexpr AnyNumber getConstrain(AnyNumber number, AnyNumber min, AnyNumber max)
Limit the number between a range.
Definition: Utilities.hpp:46