NumCpp  2.8.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
discrete.hpp
Go to the documentation of this file.
1 #pragma once
29 
30 #include <algorithm>
31 #include <random>
32 
35 #include "NumCpp/Core/Shape.hpp"
36 #include "NumCpp/NdArray.hpp"
38 
39 namespace nc
40 {
41  namespace random
42  {
43  namespace detail
44  {
45  //============================================================================
46  // Method Description:
56  template<typename dtype, typename GeneratorType = std::mt19937>
57  dtype discrete(GeneratorType& generator, const NdArray<double>& inWeights)
58  {
59  STATIC_ASSERT_INTEGER(dtype);
60 
61  std::discrete_distribution<dtype> dist(inWeights.cbegin(), inWeights.cend());
62  return dist(generator);
63  }
64 
65  //============================================================================
66  // Method Description:
78  template<typename dtype, typename GeneratorType = std::mt19937>
79  NdArray<dtype> discrete(GeneratorType& generator, const Shape& inShape, const NdArray<double>& inWeights)
80  {
81  STATIC_ASSERT_INTEGER(dtype);
82 
83  NdArray<dtype> returnArray(inShape);
84 
85  std::discrete_distribution<dtype> dist(inWeights.cbegin(), inWeights.cend());
86 
87  std::for_each(returnArray.begin(),
88  returnArray.end(),
89  [&generator, &dist](dtype& value) -> void { value = dist(generator); });
90 
91  return returnArray;
92  }
93  } // namespace detail
94 
95  //============================================================================
96  // Method Description:
105  template<typename dtype>
106  dtype discrete(const NdArray<double>& inWeights)
107  {
108  return detail::discrete<dtype>(generator_, inWeights);
109  }
110 
111  //============================================================================
112  // Method Description:
123  template<typename dtype>
124  NdArray<dtype> discrete(const Shape& inShape, const NdArray<double>& inWeights)
125  {
126  return detail::discrete<dtype>(generator_, inShape, inWeights);
127  }
128  } // namespace random
129 } // namespace nc
#define STATIC_ASSERT_INTEGER(dtype)
Definition: StaticAsserts.hpp:40
const_iterator cbegin() const noexcept
Definition: NdArrayCore.hpp:1221
iterator end() noexcept
Definition: NdArrayCore.hpp:1479
const_iterator cend() const noexcept
Definition: NdArrayCore.hpp:1529
iterator begin() noexcept
Definition: NdArrayCore.hpp:1171
A Shape Class for NdArrays.
Definition: Core/Shape.hpp:41
dtype discrete(GeneratorType &generator, const NdArray< double > &inWeights)
Definition: discrete.hpp:57
dtype discrete(const NdArray< double > &inWeights)
Definition: discrete.hpp:106
static std::mt19937_64 generator_
generator function
Definition: generator.hpp:37
void for_each(InputIt first, InputIt last, UnaryFunction f)
Definition: StlAlgorithms.hpp:227
Definition: Coordinate.hpp:45