NumCpp  2.7.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
choice.hpp
Go to the documentation of this file.
1 #pragma once
29 
31 #include "NumCpp/Core/Shape.hpp"
32 #include "NumCpp/Core/Types.hpp"
33 #include "NumCpp/NdArray.hpp"
36 
37 #include <algorithm>
38 
39 namespace nc
40 {
41  namespace random
42  {
43  //============================================================================
44  // Method Description:
50  template<typename dtype>
51  dtype choice(const NdArray<dtype>& inArray)
52  {
53  uint32 randIdx = random::randInt<uint32>(0, inArray.size());
54  return inArray[randIdx];
55  }
56 
57  //============================================================================
58  // Method Description:
66  template<typename dtype>
67  NdArray<dtype> choice(const NdArray<dtype>& inArray, uint32 inNum, bool replace = true)
68  {
69  if (!replace && inNum > inArray.size())
70  {
71  THROW_INVALID_ARGUMENT_ERROR("when 'replace' == false 'inNum' must be <= inArray.size()");
72  }
73 
74  if (replace)
75  {
76  NdArray<dtype> outArray(1, inNum);
77  std::for_each(outArray.begin(), outArray.end(),
78  [&inArray](dtype& value) -> void
79  {
80  value = choice(inArray);
81  });
82 
83  return outArray;
84  }
85 
86  return permutation(inArray)[Slice(inNum)];
87  }
88  } // namespace random
89 } // namespace nc
#define THROW_INVALID_ARGUMENT_ERROR(msg)
Definition: Error.hpp:36
Holds 1D and 2D arrays, the main work horse of the NumCpp library.
Definition: NdArrayCore.hpp:72
size_type size() const noexcept
Definition: NdArrayCore.hpp:4296
iterator end() noexcept
Definition: NdArrayCore.hpp:1474
iterator begin() noexcept
Definition: NdArrayCore.hpp:1166
A Class for slicing into NdArrays.
Definition: Slice.hpp:44
NdArray< dtype > permutation(dtype inValue)
Definition: permutation.hpp:50
dtype choice(const NdArray< dtype > &inArray)
Definition: choice.hpp:51
void for_each(InputIt first, InputIt last, UnaryFunction f)
Definition: StlAlgorithms.hpp:213
Definition: Coordinate.hpp:45
NdArray< dtype > replace(const NdArray< dtype > &inArray, dtype oldValue, dtype newValue)
Definition: replace.hpp:45
std::uint32_t uint32
Definition: Types.hpp:40