NumCpp  2.4.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:
51  template<typename dtype>
52  dtype choice(const NdArray<dtype>& inArray)
53  {
54  uint32 randIdx = random::randInt<uint32>(0, inArray.size());
55  return inArray[randIdx];
56  }
57 
58  //============================================================================
59  // Method Description:
68  template<typename dtype>
69  NdArray<dtype> choice(const NdArray<dtype>& inArray, uint32 inNum, bool replace = true)
70  {
71  if (!replace && inNum > inArray.size())
72  {
73  THROW_INVALID_ARGUMENT_ERROR("when 'replace' == false 'inNum' must be <= inArray.size()");
74  }
75 
76  if (replace)
77  {
78  NdArray<dtype> outArray(1, inNum);
79  std::for_each(outArray.begin(), outArray.end(),
80  [&inArray](dtype& value) -> void
81  {
82  value = choice(inArray);
83  });
84 
85  return outArray;
86  }
87 
88  return permutation(inArray)[Slice(inNum)];
89  }
90  } // namespace random
91 } // namespace nc
nc::random::permutation
NdArray< dtype > permutation(dtype inValue)
Definition: permutation.hpp:52
Error.hpp
nc::replace
NdArray< dtype > replace(const NdArray< dtype > &inArray, dtype oldValue, dtype newValue)
Definition: replace.hpp:45
randInt.hpp
nc::NdArray< dtype >
nc::stl_algorithms::for_each
void for_each(InputIt first, InputIt last, UnaryFunction f)
Definition: StlAlgorithms.hpp:213
nc::uint32
std::uint32_t uint32
Definition: Types.hpp:40
NdArray.hpp
nc::NdArray::end
iterator end() noexcept
Definition: NdArrayCore.hpp:1431
nc::NdArray::size
size_type size() const noexcept
Definition: NdArrayCore.hpp:4370
nc::random::choice
dtype choice(const NdArray< dtype > &inArray)
Definition: choice.hpp:52
Shape.hpp
nc
Definition: Coordinate.hpp:44
THROW_INVALID_ARGUMENT_ERROR
#define THROW_INVALID_ARGUMENT_ERROR(msg)
Definition: Error.hpp:36
Types.hpp
nc::NdArray::begin
iterator begin() noexcept
Definition: NdArrayCore.hpp:1087
nc::Slice
A Class for slicing into NdArrays.
Definition: Slice.hpp:43
permutation.hpp