Skip to content

Instantly share code, notes, and snippets.

@qtip
Created December 21, 2017 22:44
Show Gist options
  • Save qtip/7e5f6ee6f7ee2a68e34cdcde2bda113e to your computer and use it in GitHub Desktop.
Save qtip/7e5f6ee6f7ee2a68e34cdcde2bda113e to your computer and use it in GitHub Desktop.
template<class UIntType>
VanDerCorputEngine<UIntType>::VanDerCorputEngine(unsigned int base) :
i(1),
base(base) {
}
template<class UIntType>
UIntType VanDerCorputEngine<UIntType>::index() const {
return i;
}
template<class UIntType>
UIntType VanDerCorputEngine<UIntType>::operator()() {
return van_der_corput(i++, base);
}
template<class UIntType>
void VanDerCorputEngine<UIntType>::discard(unsigned long long z) {
i += z;
}
template<class UIntType>
bool VanDerCorputEngine<UIntType>::operator==(const VanDerCorputEngine& rhs) {
return i == rhs.i;
}
template<class UIntType>
bool VanDerCorputEngine<UIntType>::operator!=(const VanDerCorputEngine& rhs) {
return !(*this == rhs);
}
template<class UIntType>
UIntType VanDerCorputEngine<UIntType>::van_der_corput(UIntType i, unsigned int base) {
UIntType exponent = std::numeric_limits<UIntType>::max() / base + 1;
UIntType out(0);
UIntType n(i);
while (n > 0) {
out += UIntType(n % base * exponent);
exponent /= base;
n = n / base;
}
return out;
}
// Implementations
template class VanDerCorputEngine<unsigned char>;
template class VanDerCorputEngine<unsigned short>;
template class VanDerCorputEngine<unsigned int>;
template class VanDerCorputEngine<unsigned long>;
template class VanDerCorputEngine<unsigned long long>;
template<class UIntType>
class VanDerCorputEngine {
static_assert(std::numeric_limits<UIntType>::is_integer, "UIntType must be integral type");
static_assert(!std::numeric_limits<UIntType>::is_signed, "UIntType must be unsigned type");
public:
typedef UIntType result_type;
VanDerCorputEngine(unsigned int base = 2);
UIntType index() const;
UIntType operator()();
void discard(unsigned long long);
static constexpr UIntType min();
static constexpr UIntType max();
bool operator==(const VanDerCorputEngine& rhs);
bool operator!=(const VanDerCorputEngine& rhs);
// TODO: stream (de)serializer
private:
UIntType i;
unsigned int base;
static UIntType van_der_corput(UIntType i, unsigned int base);
};
template<class UIntType>
constexpr UIntType VanDerCorputEngine<UIntType>::min() {
return std::numeric_limits<UIntType>::min();
}
template<class UIntType>
constexpr UIntType VanDerCorputEngine<UIntType>::max() {
return std::numeric_limits<UIntType>::max();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment