shogo-library

競技プログラミング用の C++ ライブラリ

View the Project on GitHub shogo314/shogo-library

:heavy_check_mark: test/unittest/base/functions.test.cpp

Depends on

Code

#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"

// functions.hpp と binary-search.hpp の関数を愚直な実装とランダムに比較する
// 問題の入力は使わず、すべて一致したら Hello World を出力する

#include "../../../src/base/functions.hpp"

#include <algorithm>
#include <array>
#include <cmath>
#include <cstdint>
#include <forward_list>
#include <iostream>
#include <limits>
#include <list>
#include <random>
#include <set>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>
#include <vector>

#include "../../../src/utility/binary-search.hpp"

bool ok = true;

void check(bool cond, const char* what) {
    if (!cond) {
        if (ok) std::cerr << "failed: " << what << std::endl;
        ok = false;
    }
}

// midpoint の答え: (a + b) / 2 を a の側に丸める。__int128 で計算する
template <typename T>
T naive_midpoint(T a, T b) {
    __int128 s = static_cast<__int128>(a) + static_cast<__int128>(b);
    return static_cast<T>(a <= b ? floordiv(s, 2) : ceildiv(s, 2));
}
template <typename T>
void check_midpoint(std::mt19937_64& rng) {
    std::vector<T> xs = {std::numeric_limits<T>::min(), std::numeric_limits<T>::max(), 0, 1, static_cast<T>(std::numeric_limits<T>::max() - 1), static_cast<T>(std::numeric_limits<T>::min() + 1)};
    if (std::is_signed_v<T>) xs.push_back(static_cast<T>(-1));
    for (int i = 0; i < 30; i++) xs.push_back(static_cast<T>(rng())), xs.push_back(static_cast<T>(static_cast<T>(rng()) >> (rng() % (8 * sizeof(T)))));
    for (T a : xs)
        for (T b : xs) check(midpoint(a, b) == naive_midpoint(a, b), "midpoint 整数");
    static_assert(std::is_same_v<decltype(midpoint(T(), T())), T>);
}

// len は要素数の分からないもの (forward_list や整数) を渡すと候補から外れる
template <typename C, typename = void>
struct has_len : std::false_type {};
template <typename C>
struct has_len<C, std::void_t<decltype(len(std::declval<C&>()))>> : std::true_type {};
static_assert(has_len<std::vector<int>>::value && has_len<int[3]>::value && has_len<std::list<int>>::value);
static_assert(!has_len<std::forward_list<int>>::value && !has_len<int>::value);
// size() だけを持つ自作の型 (begin() と end() はない) にも、C++17 と C++20 のどちらでも使える
struct OnlySize {
    int size() const { return 5; }
};
static_assert(has_len<OnlySize>::value && has_len<const OnlySize>::value);

int main() {
    std::mt19937_64 rng(314);

    for (int rep = 0; rep < 20000 && ok; rep++) {
        long long a = static_cast<long long>(rng() % 21) - 10, b = static_cast<long long>(rng() % 21) - 10;

        // chmin / chmax: 更新したかを返す
        {
            long long x = a;
            bool changed = chmin(x, b);
            check(x == std::min(a, b) && changed == (b < a), "chmin");
            x = a;
            changed = chmax(x, b);
            check(x == std::max(a, b) && changed == (b > a), "chmax");
            double d = a;
            check(chmin(d, b + 0.5) == (b + 0.5 < a) && d == std::min<double>(a, b + 0.5), "chmin (型が異なる)");
        }

        // long long 同士の max / min
        check(max(a, b) == std::max(a, b) && min(a, b) == std::min(a, b), "max/min(long long, long long)");
        check(max(a, 3) == std::max(a, 3LL) && min(2, b) == std::min(2LL, b), "max/min (int と long long の混在)");

        // floordiv / ceildiv: 実数の floor / ceil と比べる
        if (b != 0) {
            check(floordiv(a, b) == static_cast<long long>(std::floor(static_cast<double>(a) / b)), "floordiv");
            check(ceildiv(a, b) == static_cast<long long>(std::ceil(static_cast<double>(a) / b)), "ceildiv");
            auto [q, r] = divmod(a, b);
            check(q == floordiv(a, b) && q * b + r == a, "divmod");
            check(r == 0 || (r < 0) == (b < 0), "divmod 余りの符号");
            check(std::abs(r) < std::abs(b), "divmod 余りの大きさ");
        }

        // inrange / inrect
        {
            long long x = static_cast<long long>(rng() % 15) - 5;
            check(inrange(x, a) == (0 <= x && x < a), "inrange(x, a)");
            check(inrange(x, a, b) == (a <= x && x < b), "inrange(x, a, b)");
            long long y = static_cast<long long>(rng() % 15) - 5;
            check(inrect(x, y, a, b) == (0 <= x && x < a && 0 <= y && y < b), "inrect");
        }

        // 整数の二分探索: f(ok) が真、f(ng) が偽で単調なとき、境界の ok 側を返す
        {
            long long t = static_cast<long long>(rng() % 2001) - 1000;
            long long lo = t - static_cast<long long>(rng() % 1000) - 1, hi = t + static_cast<long long>(rng() % 1000) + 1;
            // f(x) = x <= t (ok = lo, ng = hi) -> t
            check(binary_search(lo, hi, [&](long long x) { return x <= t; }) == t, "binary_search 整数 (ok < ng)");
            // f(x) = x >= t (ok = hi, ng = lo) -> t
            check(binary_search(hi, lo, [&](long long x) { return x >= t; }) == t, "binary_search 整数 (ok > ng)");
            // 隣り合う ok, ng なら ok をそのまま返す
            check(binary_search(t, t + 1, [&](long long) { return true; }) == t, "binary_search 整数 隣接");
        }

        // 実数の二分探索 (100 回)
        {
            double t = static_cast<double>(rng() % 2000001) / 1000.0;  // [0, 2000]
            double r = binary_search(0.0, 3000.0, [&](double x) { return x * x <= t; });
            check(std::abs(r - std::sqrt(t)) < 1e-9, "binary_search 実数 sqrt");
            double r2 = binary_search(3000.0, 0.0, [&](double x) { return x * x >= t; });
            check(std::abs(r2 - std::sqrt(t)) < 1e-9, "binary_search 実数 (ok > ng)");
        }
    }

    // 決まった値
    check(binary_search(0, 1000000000, [](int x) { return static_cast<long long>(x) * x <= 1000000000; }) == 31622, "binary_search sqrt(1e9)");
    check(!inrange(0, 0) && inrange(0, 1) && !inrange(-1, 1), "inrange 境界");
    check(inrange(5, 5, 6) && !inrange(6, 5, 6), "inrange(x, a, b) 境界");
    check(floordiv(7, 2) == 3 && floordiv(-7, 2) == -4 && floordiv(7, -2) == -4 && floordiv(-7, -2) == 3, "floordiv 決まった値");
    check(ceildiv(7, 2) == 4 && ceildiv(-7, 2) == -3 && ceildiv(7, -2) == -3 && ceildiv(-7, -2) == 4, "ceildiv 決まった値");
    check(floordiv(-6, 3) == -2 && ceildiv(-6, 3) == -2, "割り切れる場合");
    {
        long long n = -7;
        check(floordiv(n, 2) == -4 && ceildiv(n, 2) == -3, "long long と int の混在");
    }
    check(divmod(7, 3) == std::pair(2, 1) && divmod(-7, 3) == std::pair(-3, 2), "divmod 決まった値");
    check(divmod(7, -3) == std::pair(-3, -2) && divmod(-7, -3) == std::pair(2, -1), "divmod 決まった値 (b < 0)");
    static_assert(floordiv(-1LL, 1000000000000LL) == -1 && ceildiv(1LL, 1000000000000LL) == 1);
    static_assert(divmod(-1LL, 1000000000000LL) == std::pair(-1LL, 999999999999LL));

    // midpoint: 整数は 8 ビットの型を全組、他は境界付近とランダム。浮動小数点数とポインタは決まった値
    for (int a = -128; a < 128; a++)
        for (int b = -128; b < 128; b++) check(midpoint(static_cast<std::int8_t>(a), static_cast<std::int8_t>(b)) == naive_midpoint(static_cast<std::int8_t>(a), static_cast<std::int8_t>(b)), "midpoint int8");
    for (int a = 0; a < 256; a++)
        for (int b = 0; b < 256; b++) check(midpoint(static_cast<std::uint8_t>(a), static_cast<std::uint8_t>(b)) == naive_midpoint(static_cast<std::uint8_t>(a), static_cast<std::uint8_t>(b)), "midpoint uint8");
    check_midpoint<short>(rng);
    check_midpoint<int>(rng);
    check_midpoint<unsigned>(rng);
    check_midpoint<long long>(rng);
    check_midpoint<unsigned long long>(rng);
    {
        constexpr double M = std::numeric_limits<double>::max(), D = std::numeric_limits<double>::denorm_min();
        check(midpoint(1.0, 4.0) == 2.5 && midpoint(-3.0, 1.0) == -1.0, "midpoint double");
        check(midpoint(M, M) == M && midpoint(-M, M) == 0.0 && midpoint(M, M / 2) == M * 0.75, "midpoint double あふれない");
        check(midpoint(D, 4.0) == 2.0 && midpoint(4.0, D) == 2.0 && midpoint(D, D) == D, "midpoint double 非正規化数");
        check(midpoint(1.0f, 2.0f) == 1.5f && std::is_same_v<decltype(midpoint(1.0f, 2.0f)), float>, "midpoint float");
        for (int rep = 0; rep < 1000; rep++) {
            double a = static_cast<double>(static_cast<long long>(rng() % 2000001 - 1000000)) / 1024, b = static_cast<double>(static_cast<long long>(rng() % 2000001 - 1000000)) / 1024;
            check(midpoint(a, b) == (a + b) / 2, "midpoint double ランダム");
        }
        static int arr[10];
        check(midpoint(arr, arr + 9) == arr + 4 && midpoint(arr + 9, arr) == arr + 5 && midpoint(arr + 3, arr + 3) == arr + 3, "midpoint ポインタ");
    }
    static_assert(midpoint(1, 4) == 2 && midpoint(4, 1) == 3 && midpoint(-3, 0) == -2);
    static_assert(midpoint(std::numeric_limits<long long>::max(), std::numeric_limits<long long>::max() - 2) == std::numeric_limits<long long>::max() - 1);
    static_assert(midpoint(0u, 4294967295u) == 2147483647u && midpoint(4294967295u, 0u) == 2147483648u);
    static_assert(midpoint(1.0, 2.0) == 1.5);

    // len: 要素数を long long で返す
    {
        std::vector<int> v(5);
        const std::string str = "abcd";
        std::set<int> st = {3, 1, 4, 1, 5};
        int carr[7] = {};
        check(len(v) == 5 && len(str) == 4 && len(st) == 4 && len(carr) == 7, "len");
        check(len(std::vector<int>()) == 0 && len(std::string_view("xy")) == 2 && len("abc") == 4, "len 空・一時オブジェクト・文字列リテラル");
        check(len(v) - 6 == -1, "len は符号付き");
        static_assert(std::is_same_v<decltype(len(v)), long long>);
        OnlySize os;
        check(len(os) == 5 && len(OnlySize{}) == 5, "len size() だけを持つ型");
        static_assert(std::is_same_v<decltype(len(os)), long long>);
        static_assert(len(std::array<int, 3>{}) == 3);
#if __cplusplus >= 202002L
        check(len(std::views::iota(2, 9)) == 7, "len views::iota");
#endif
    }

    if (ok) std::cout << "Hello World" << std::endl;
}
#line 1 "test/unittest/base/functions.test.cpp"
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"

// functions.hpp と binary-search.hpp の関数を愚直な実装とランダムに比較する
// 問題の入力は使わず、すべて一致したら Hello World を出力する

#line 2 "src/base/functions.hpp"

/**
 * @file functions.hpp
 * @brief 汎用関数 (chmin, chmax など)
 */

#include <algorithm>
#include <cmath>
#include <iterator>
#include <limits>
#include <numeric>
#if __cplusplus >= 202002L
#include <ranges>
#endif
#include <type_traits>
#include <utility>

template <typename T1, typename T2>
inline constexpr bool chmin(T1& a, T2 b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}

template <typename T1, typename T2>
inline constexpr bool chmax(T1& a, T2 b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}

inline constexpr long long max(const long long& t1, const long long& t2) {
    return std::max<long long>(t1, t2);
}

inline constexpr long long min(const long long& t1, const long long& t2) {
    return std::min<long long>(t1, t2);
}

using std::abs;
using std::gcd;
using std::lcm;
using std::size;

#if __cplusplus >= 202002L
using std::midpoint;
#else
// C++20 の std::midpoint と同じ (整数は a の側に丸め、あふれない)
template <typename T>
inline constexpr std::enable_if_t<std::is_integral_v<T> && !std::is_same_v<T, bool>, T> midpoint(T a, T b) noexcept {
    using U = std::make_unsigned_t<T>;
    if (a <= b) return static_cast<T>(a + static_cast<T>(static_cast<U>(static_cast<U>(b) - static_cast<U>(a)) >> 1));
    return static_cast<T>(a - static_cast<T>(static_cast<U>(static_cast<U>(a) - static_cast<U>(b)) >> 1));
}
template <typename T>
inline constexpr std::enable_if_t<std::is_floating_point_v<T>, T> midpoint(T a, T b) noexcept {
    constexpr T lo = std::numeric_limits<T>::min() * 2;
    constexpr T hi = std::numeric_limits<T>::max() / 2;
    const T abs_a = a < 0 ? -a : a, abs_b = b < 0 ? -b : b;
    if (abs_a <= hi && abs_b <= hi) return (a + b) / 2;
    if (abs_a < lo) return a + b / 2;
    if (abs_b < lo) return a / 2 + b;
    return a / 2 + b / 2;
}
template <typename T>
inline constexpr std::enable_if_t<std::is_object_v<T>, T*> midpoint(T* a, T* b) noexcept {
    return a + (b - a) / 2;
}
#endif

/**
 * 要素数を long long で返す (std::ssize の long long 版)
 * size() を持つ型なら、begin() と end() を持たない自作の型にも使える
 */
#if __cplusplus >= 202002L
template <typename R>
    requires requires(R& r) { std::ranges::size(r); }
inline constexpr long long len(R&& r) {
    return static_cast<long long>(std::ranges::size(r));
}
#else
template <typename C>
inline constexpr auto len(const C& c) -> decltype(static_cast<long long>(std::size(c))) {
    return static_cast<long long>(std::size(c));
}
#endif

template <typename T>
constexpr T extgcd(const T& a, const T& b, T& x, T& y) {
    T d = a;
    if (b != 0) {
        d = extgcd(b, a % b, y, x);
        y -= (a / b) * x;
    } else {
        x = 1;
        y = 0;
    }
    return d;
}

/**
 * floor(a / b) (b != 0、負の数も可)
 */
template <typename T1, typename T2>
inline constexpr std::common_type_t<T1, T2> floordiv(T1 a, T2 b) {
    return a / b - (a % b != 0 && (a < 0) != (b < 0));
}
/**
 * ceil(a / b) (b != 0、負の数も可)
 */
template <typename T1, typename T2>
inline constexpr std::common_type_t<T1, T2> ceildiv(T1 a, T2 b) {
    return a / b + (a % b != 0 && (a < 0) == (b < 0));
}
/**
 * {floor(a / b), a - b * floor(a / b)} (b != 0、負の数も可)
 * 余りは 0 または b と同じ符号になる
 */
template <typename T1, typename T2>
inline constexpr std::pair<std::common_type_t<T1, T2>, std::common_type_t<T1, T2>> divmod(T1 a, T2 b) {
    std::common_type_t<T1, T2> q = floordiv(a, b);
    return {q, a - q * b};
}

/**
 * 0 <= x < a
 */
inline constexpr bool inrange(long long x, long long a) {
    return 0 <= x && x < a;
}
/**
 * a <= x < b
 */
inline constexpr bool inrange(long long x, long long a, long long b) {
    return a <= x && x < b;
}
/**
 * 0 <= x < a and 0 <= y < b
 */
inline constexpr bool inrect(long long x, long long y, long long a, long long b) {
    return 0 <= x && x < a && 0 <= y && y < b;
}
#line 7 "test/unittest/base/functions.test.cpp"

#line 9 "test/unittest/base/functions.test.cpp"
#include <array>
#line 11 "test/unittest/base/functions.test.cpp"
#include <cstdint>
#include <forward_list>
#include <iostream>
#line 15 "test/unittest/base/functions.test.cpp"
#include <list>
#include <random>
#include <set>
#include <string>
#include <string_view>
#line 22 "test/unittest/base/functions.test.cpp"
#include <vector>

#line 2 "src/utility/binary-search.hpp"

/**
 * @file binary-search.hpp
 * @brief 二分探索
 */

#line 10 "src/utility/binary-search.hpp"

#line 2 "src/utility/traits.hpp"

/**
 * @file traits.hpp
 * @brief 型特性
 */

#include <cstddef>
#include <functional>
#line 14 "src/utility/traits.hpp"

#if __cplusplus >= 202002L
#include <concepts>
#include <ranges>
#endif

namespace internal_traits {
using std::begin, std::end;

#if __cplusplus >= 202002L
template <class T>
    struct is_range_impl : std::bool_constant < requires(T& t) {
    begin(t);
    end(t);
}>{};
#else
template <class T, class = void>
struct is_range_impl : std::false_type {};
template <class T>
struct is_range_impl<T, std::void_t<decltype(begin(std::declval<T&>()), end(std::declval<T&>()))>> : std::true_type {};
#endif

// サイズ付き範囲から要素を直接構築するコンストラクタで共有する。
#if __cplusplus >= 202002L
template <class R, class S>
concept sized_constructible_range = std::ranges::input_range<R> && std::ranges::sized_range<R> &&
                                    std::is_constructible_v<S, std::ranges::range_reference_t<R>>;

template <class R>
auto range_size(R& r) {
    return std::ranges::size(r);
}
template <class R>
auto range_begin(R& r) {
    return std::ranges::begin(r);
}
template <class R>
using range_value_t = std::ranges::range_value_t<R>;
#else
using std::size;
template <class R>
auto range_size(R& r) -> decltype(size(r)) {
    return size(r);
}
template <class R>
auto range_begin(R& r) -> decltype(begin(r)) {
    return begin(r);
}
template <class R>
using range_value_t = typename std::iterator_traits<decltype(range_begin(std::declval<R&>()))>::value_type;

template <class R, class S, class = void>
struct is_sized_constructible_range : std::false_type {};
template <class R, class S>
struct is_sized_constructible_range<R, S, std::void_t<decltype(range_size(std::declval<R&>())), decltype(++std::declval<decltype(begin(std::declval<R&>()))&>()), decltype(begin(std::declval<R&>()) != end(std::declval<R&>())), decltype(*begin(std::declval<R&>()))>>
    : std::is_constructible<S, decltype(*begin(std::declval<R&>()))> {};
#endif
}  // namespace internal_traits

template <class T>
struct is_range : internal_traits::is_range_impl<T>::type {};
template <class T>
inline constexpr bool is_range_v = is_range<T>::value;

#if __cplusplus >= 202002L
#define HAS_METHOD(func_name)                                                                   \
    namespace internal_traits {                                                                 \
    template <class T>                                                                          \
    concept has_##func_name##_impl = requires { std::declval<T>().func_name(); };               \
    }                                                                                           \
    template <class T>                                                                          \
    struct has_##func_name : std::bool_constant<internal_traits::has_##func_name##_impl<T>> {}; \
    template <class T>                                                                          \
    inline constexpr bool has_##func_name##_v = has_##func_name<T>::value;

#define HAS_METHOD_ARG(func_name)                                                                  \
    namespace internal_traits {                                                                    \
    template <class T, class U>                                                                    \
    concept has_##func_name##_impl = requires { std::declval<T>().func_name(std::declval<U>()); }; \
    }                                                                                              \
    template <class T, class U>                                                                    \
    struct has_##func_name : std::bool_constant<internal_traits::has_##func_name##_impl<T, U>> {}; \
    template <class T, class U>                                                                    \
    inline constexpr bool has_##func_name##_v = has_##func_name<T, U>::value;
#else
#define HAS_METHOD(func_name)                                                              \
    namespace internal_traits {                                                            \
    template <class T, class = void>                                                       \
    struct has_##func_name##_impl : std::false_type {};                                    \
    template <class T>                                                                     \
    struct has_##func_name##_impl<T, std::void_t<decltype(std::declval<T>().func_name())>> \
        : std::true_type {};                                                               \
    }                                                                                      \
    template <class T>                                                                     \
    struct has_##func_name : internal_traits::has_##func_name##_impl<T>::type {};          \
    template <class T>                                                                     \
    inline constexpr bool has_##func_name##_v = has_##func_name<T>::value;

#define HAS_METHOD_ARG(func_name)                                                                              \
    namespace internal_traits {                                                                                \
    template <class T, typename U, class = void>                                                               \
    struct has_##func_name##_impl : std::false_type {};                                                        \
    template <class T, typename U>                                                                             \
    struct has_##func_name##_impl<T, U, std::void_t<decltype(std::declval<T>().func_name(std::declval<U>()))>> \
        : std::true_type {};                                                                                   \
    }                                                                                                          \
    template <class T, typename U>                                                                             \
    struct has_##func_name : internal_traits::has_##func_name##_impl<T, U>::type {};                           \
    template <class T, typename U>                                                                             \
    inline constexpr bool has_##func_name##_v = has_##func_name<T, U>::value;
#endif

HAS_METHOD(repr)
HAS_METHOD(type_str)
HAS_METHOD(initializer_str)
HAS_METHOD(max)
HAS_METHOD(min)
HAS_METHOD(reversed)
HAS_METHOD(sorted)
HAS_METHOD(sum)
HAS_METHOD(product)
HAS_METHOD(product_xor)
HAS_METHOD_ARG(count)
HAS_METHOD_ARG(find)
HAS_METHOD_ARG(lower_bound)
HAS_METHOD_ARG(upper_bound)

#define ENABLE_IF_T_IMPL(expr) std::enable_if_t<expr, std::nullptr_t> = nullptr
#define ENABLE_IF_T(...) ENABLE_IF_T_IMPL((__VA_ARGS__))

namespace internal_traits {
// 射影 (proj) の既定値
#if __cplusplus >= 202002L
using identity = std::identity;
#else
struct identity {
    using is_transparent = void;
    template <class T>
    constexpr T&& operator()(T&& x) const noexcept {
        return std::forward<T>(x);
    }
};
#endif
}  // namespace internal_traits

template <class C>
using mem_value_type = typename C::value_type;
template <class C>
using mem_difference_type = typename C::difference_type;

namespace internal_traits {
template <class T, class = void>
struct is_sorted_container_impl : std::false_type {};
template <class T>
struct is_sorted_container_impl<std::set<T>> : std::true_type {};
template <class T>
struct is_sorted_container_impl<std::multiset<T>> : std::true_type {};
}  // namespace internal_traits
template <class T>
struct is_sorted_container : internal_traits::is_sorted_container_impl<T>::type {};
template <class T>
inline constexpr bool is_sorted_container_v = is_sorted_container<T>::value;
#line 13 "src/utility/binary-search.hpp"

/**
 * f(ok) が真、f(ng) が偽として、境界で f が真になる側の値を返す
 * 整数なら ok と ng の差が 1 になるまで、浮動小数点数なら 100 回二分する
 */
template <typename M, typename N, class F, ENABLE_IF_T(std::is_integral_v<std::common_type_t<M, N>>and std::is_invocable_r_v<bool, F, std::common_type_t<M, N>>)>
inline constexpr std::common_type_t<M, N> binary_search(const M& ok, const N& ng, F f) {
    using T = std::common_type_t<M, N>;
    using U = std::make_unsigned_t<T>;
    T _ok = ok, _ng = ng;
    // 差は符号なしで求めるとあふれない (LLONG_MIN と LLONG_MAX の差も U に収まる)
    // 中点は midpoint で求める (あふれず、ok の側に丸める)
    while ((_ok < _ng ? static_cast<U>(static_cast<U>(_ng) - static_cast<U>(_ok)) : static_cast<U>(static_cast<U>(_ok) - static_cast<U>(_ng))) > 1) {
        T mid = midpoint(_ok, _ng);
        if (f(mid)) {
            _ok = mid;
        } else {
            _ng = mid;
        }
    }
    return _ok;
}

template <typename M, typename N, class F, ENABLE_IF_T(!std::is_integral_v<std::common_type_t<M, N>> && std::is_invocable_r_v<bool, F, std::common_type_t<M, N>>)>
inline constexpr std::common_type_t<M, N> binary_search(const M& ok, const N& ng, F f) {
    std::common_type_t<M, N> _ok = ok, _ng = ng;
    for (int i = 0; i < 100; i++) {
        std::common_type_t<M, N> mid = (_ok + _ng) / 2;
        if (f(mid)) {
            _ok = mid;
        } else {
            _ng = mid;
        }
    }
    return _ok;
}
#line 25 "test/unittest/base/functions.test.cpp"

bool ok = true;

void check(bool cond, const char* what) {
    if (!cond) {
        if (ok) std::cerr << "failed: " << what << std::endl;
        ok = false;
    }
}

// midpoint の答え: (a + b) / 2 を a の側に丸める。__int128 で計算する
template <typename T>
T naive_midpoint(T a, T b) {
    __int128 s = static_cast<__int128>(a) + static_cast<__int128>(b);
    return static_cast<T>(a <= b ? floordiv(s, 2) : ceildiv(s, 2));
}
template <typename T>
void check_midpoint(std::mt19937_64& rng) {
    std::vector<T> xs = {std::numeric_limits<T>::min(), std::numeric_limits<T>::max(), 0, 1, static_cast<T>(std::numeric_limits<T>::max() - 1), static_cast<T>(std::numeric_limits<T>::min() + 1)};
    if (std::is_signed_v<T>) xs.push_back(static_cast<T>(-1));
    for (int i = 0; i < 30; i++) xs.push_back(static_cast<T>(rng())), xs.push_back(static_cast<T>(static_cast<T>(rng()) >> (rng() % (8 * sizeof(T)))));
    for (T a : xs)
        for (T b : xs) check(midpoint(a, b) == naive_midpoint(a, b), "midpoint 整数");
    static_assert(std::is_same_v<decltype(midpoint(T(), T())), T>);
}

// len は要素数の分からないもの (forward_list や整数) を渡すと候補から外れる
template <typename C, typename = void>
struct has_len : std::false_type {};
template <typename C>
struct has_len<C, std::void_t<decltype(len(std::declval<C&>()))>> : std::true_type {};
static_assert(has_len<std::vector<int>>::value && has_len<int[3]>::value && has_len<std::list<int>>::value);
static_assert(!has_len<std::forward_list<int>>::value && !has_len<int>::value);
// size() だけを持つ自作の型 (begin() と end() はない) にも、C++17 と C++20 のどちらでも使える
struct OnlySize {
    int size() const { return 5; }
};
static_assert(has_len<OnlySize>::value && has_len<const OnlySize>::value);

int main() {
    std::mt19937_64 rng(314);

    for (int rep = 0; rep < 20000 && ok; rep++) {
        long long a = static_cast<long long>(rng() % 21) - 10, b = static_cast<long long>(rng() % 21) - 10;

        // chmin / chmax: 更新したかを返す
        {
            long long x = a;
            bool changed = chmin(x, b);
            check(x == std::min(a, b) && changed == (b < a), "chmin");
            x = a;
            changed = chmax(x, b);
            check(x == std::max(a, b) && changed == (b > a), "chmax");
            double d = a;
            check(chmin(d, b + 0.5) == (b + 0.5 < a) && d == std::min<double>(a, b + 0.5), "chmin (型が異なる)");
        }

        // long long 同士の max / min
        check(max(a, b) == std::max(a, b) && min(a, b) == std::min(a, b), "max/min(long long, long long)");
        check(max(a, 3) == std::max(a, 3LL) && min(2, b) == std::min(2LL, b), "max/min (int と long long の混在)");

        // floordiv / ceildiv: 実数の floor / ceil と比べる
        if (b != 0) {
            check(floordiv(a, b) == static_cast<long long>(std::floor(static_cast<double>(a) / b)), "floordiv");
            check(ceildiv(a, b) == static_cast<long long>(std::ceil(static_cast<double>(a) / b)), "ceildiv");
            auto [q, r] = divmod(a, b);
            check(q == floordiv(a, b) && q * b + r == a, "divmod");
            check(r == 0 || (r < 0) == (b < 0), "divmod 余りの符号");
            check(std::abs(r) < std::abs(b), "divmod 余りの大きさ");
        }

        // inrange / inrect
        {
            long long x = static_cast<long long>(rng() % 15) - 5;
            check(inrange(x, a) == (0 <= x && x < a), "inrange(x, a)");
            check(inrange(x, a, b) == (a <= x && x < b), "inrange(x, a, b)");
            long long y = static_cast<long long>(rng() % 15) - 5;
            check(inrect(x, y, a, b) == (0 <= x && x < a && 0 <= y && y < b), "inrect");
        }

        // 整数の二分探索: f(ok) が真、f(ng) が偽で単調なとき、境界の ok 側を返す
        {
            long long t = static_cast<long long>(rng() % 2001) - 1000;
            long long lo = t - static_cast<long long>(rng() % 1000) - 1, hi = t + static_cast<long long>(rng() % 1000) + 1;
            // f(x) = x <= t (ok = lo, ng = hi) -> t
            check(binary_search(lo, hi, [&](long long x) { return x <= t; }) == t, "binary_search 整数 (ok < ng)");
            // f(x) = x >= t (ok = hi, ng = lo) -> t
            check(binary_search(hi, lo, [&](long long x) { return x >= t; }) == t, "binary_search 整数 (ok > ng)");
            // 隣り合う ok, ng なら ok をそのまま返す
            check(binary_search(t, t + 1, [&](long long) { return true; }) == t, "binary_search 整数 隣接");
        }

        // 実数の二分探索 (100 回)
        {
            double t = static_cast<double>(rng() % 2000001) / 1000.0;  // [0, 2000]
            double r = binary_search(0.0, 3000.0, [&](double x) { return x * x <= t; });
            check(std::abs(r - std::sqrt(t)) < 1e-9, "binary_search 実数 sqrt");
            double r2 = binary_search(3000.0, 0.0, [&](double x) { return x * x >= t; });
            check(std::abs(r2 - std::sqrt(t)) < 1e-9, "binary_search 実数 (ok > ng)");
        }
    }

    // 決まった値
    check(binary_search(0, 1000000000, [](int x) { return static_cast<long long>(x) * x <= 1000000000; }) == 31622, "binary_search sqrt(1e9)");
    check(!inrange(0, 0) && inrange(0, 1) && !inrange(-1, 1), "inrange 境界");
    check(inrange(5, 5, 6) && !inrange(6, 5, 6), "inrange(x, a, b) 境界");
    check(floordiv(7, 2) == 3 && floordiv(-7, 2) == -4 && floordiv(7, -2) == -4 && floordiv(-7, -2) == 3, "floordiv 決まった値");
    check(ceildiv(7, 2) == 4 && ceildiv(-7, 2) == -3 && ceildiv(7, -2) == -3 && ceildiv(-7, -2) == 4, "ceildiv 決まった値");
    check(floordiv(-6, 3) == -2 && ceildiv(-6, 3) == -2, "割り切れる場合");
    {
        long long n = -7;
        check(floordiv(n, 2) == -4 && ceildiv(n, 2) == -3, "long long と int の混在");
    }
    check(divmod(7, 3) == std::pair(2, 1) && divmod(-7, 3) == std::pair(-3, 2), "divmod 決まった値");
    check(divmod(7, -3) == std::pair(-3, -2) && divmod(-7, -3) == std::pair(2, -1), "divmod 決まった値 (b < 0)");
    static_assert(floordiv(-1LL, 1000000000000LL) == -1 && ceildiv(1LL, 1000000000000LL) == 1);
    static_assert(divmod(-1LL, 1000000000000LL) == std::pair(-1LL, 999999999999LL));

    // midpoint: 整数は 8 ビットの型を全組、他は境界付近とランダム。浮動小数点数とポインタは決まった値
    for (int a = -128; a < 128; a++)
        for (int b = -128; b < 128; b++) check(midpoint(static_cast<std::int8_t>(a), static_cast<std::int8_t>(b)) == naive_midpoint(static_cast<std::int8_t>(a), static_cast<std::int8_t>(b)), "midpoint int8");
    for (int a = 0; a < 256; a++)
        for (int b = 0; b < 256; b++) check(midpoint(static_cast<std::uint8_t>(a), static_cast<std::uint8_t>(b)) == naive_midpoint(static_cast<std::uint8_t>(a), static_cast<std::uint8_t>(b)), "midpoint uint8");
    check_midpoint<short>(rng);
    check_midpoint<int>(rng);
    check_midpoint<unsigned>(rng);
    check_midpoint<long long>(rng);
    check_midpoint<unsigned long long>(rng);
    {
        constexpr double M = std::numeric_limits<double>::max(), D = std::numeric_limits<double>::denorm_min();
        check(midpoint(1.0, 4.0) == 2.5 && midpoint(-3.0, 1.0) == -1.0, "midpoint double");
        check(midpoint(M, M) == M && midpoint(-M, M) == 0.0 && midpoint(M, M / 2) == M * 0.75, "midpoint double あふれない");
        check(midpoint(D, 4.0) == 2.0 && midpoint(4.0, D) == 2.0 && midpoint(D, D) == D, "midpoint double 非正規化数");
        check(midpoint(1.0f, 2.0f) == 1.5f && std::is_same_v<decltype(midpoint(1.0f, 2.0f)), float>, "midpoint float");
        for (int rep = 0; rep < 1000; rep++) {
            double a = static_cast<double>(static_cast<long long>(rng() % 2000001 - 1000000)) / 1024, b = static_cast<double>(static_cast<long long>(rng() % 2000001 - 1000000)) / 1024;
            check(midpoint(a, b) == (a + b) / 2, "midpoint double ランダム");
        }
        static int arr[10];
        check(midpoint(arr, arr + 9) == arr + 4 && midpoint(arr + 9, arr) == arr + 5 && midpoint(arr + 3, arr + 3) == arr + 3, "midpoint ポインタ");
    }
    static_assert(midpoint(1, 4) == 2 && midpoint(4, 1) == 3 && midpoint(-3, 0) == -2);
    static_assert(midpoint(std::numeric_limits<long long>::max(), std::numeric_limits<long long>::max() - 2) == std::numeric_limits<long long>::max() - 1);
    static_assert(midpoint(0u, 4294967295u) == 2147483647u && midpoint(4294967295u, 0u) == 2147483648u);
    static_assert(midpoint(1.0, 2.0) == 1.5);

    // len: 要素数を long long で返す
    {
        std::vector<int> v(5);
        const std::string str = "abcd";
        std::set<int> st = {3, 1, 4, 1, 5};
        int carr[7] = {};
        check(len(v) == 5 && len(str) == 4 && len(st) == 4 && len(carr) == 7, "len");
        check(len(std::vector<int>()) == 0 && len(std::string_view("xy")) == 2 && len("abc") == 4, "len 空・一時オブジェクト・文字列リテラル");
        check(len(v) - 6 == -1, "len は符号付き");
        static_assert(std::is_same_v<decltype(len(v)), long long>);
        OnlySize os;
        check(len(os) == 5 && len(OnlySize{}) == 5, "len size() だけを持つ型");
        static_assert(std::is_same_v<decltype(len(os)), long long>);
        static_assert(len(std::array<int, 3>{}) == 3);
#if __cplusplus >= 202002L
        check(len(std::views::iota(2, 9)) == 7, "len views::iota");
#endif
    }

    if (ok) std::cout << "Hello World" << std::endl;
}
Back to top page