compro_library

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub siro53/compro_library

:heavy_check_mark: テスト生成用の乱数 (Random)
(random/gen/random.hpp)

このライブラリでできること

Random は、ランダムテストの入力生成器 (generator) のための乱数クラスです。seed を指定でき、同じ seed からは常に同じ乱数列が得られます。そのため、ランダムテストで見つけた反例を seed だけから再現できます。

コンストラクタ Random(argc, argv) はコマンドライン引数の argv[1] を seed として読みます。scripts/randtest.py が生成器を gen <seed> の形で呼ぶので、この規約に合わせて書くだけで反例の保存と再現ができます。

整数乱数の区間は、既存の random/rng.hpp と同じく右端を含まない半開区間 $[l,r)$ です。randint(1, 7) は $1$ 以上 $6$ 以下の整数を返します。偶数だけ・奇数だけが欲しい場合は、even(l, r) と odd(l, r) が $[l,r)$ に含まれる偶数・奇数から一様に選びます。

rng.hpp との違いは次のとおりです。

木やグラフなどの生成関数は、このクラスを引数に取る別ヘッダにまとめています。一覧は 生成器ライブラリ一式 を参照してください。

使い方

生成器では main の引数を Random に渡し、問題の制約を半開区間で書き写して乱数を引きます。size は小さい値ほど出やすい長さを返すので、反例が見つかったときに手で追える小さな入力が得やすくなります。

#include "template/template.cpp"
#include "random/gen/random.hpp"

int main(int argc, char **argv) {
    Random rng(argc, argv);           // ./gen 42 なら seed = 42
    int n = rng.size(1, 9);           // 1 以上 8 以下。小さい値に偏る
    assert(1 <= n && n <= 8);
    long long x = rng.randint(0, 1000000000000LL);  // long long になる
    assert(0 <= x && x < 1000000000000LL);
    int e = rng.even(1, 11);          // 2, 4, 6, 8, 10 のいずれか
    int o = rng.odd(-3, 4);           // -3, -1, 1, 3 のいずれか
    assert(e % 2 == 0 && 2 <= e && e <= 10);
    assert(o % 2 != 0 && -3 <= o && o <= 3);
    vector<int> p{1, 2, 3};
    rng.shuffle(p);
    int c = rng.choice(p);
    assert(1 <= c && c <= 3);

    // 同じ seed なら同じ列になる
    Random a(7), b(7);
    for(int i = 0; i < 5; i++) assert(a.randint(100) == b.randint(100));
    print(n, x);
}

例を実行すると、n と x が1行に出力されます。値は seed によって決まり、引数なしで実行したときは seed が $0$ になります。

API・計算量

以下では、選ぶ範囲の幅を $w=r-l$、数列の長さを $n$ とします。乱数エンジンの状態は固定サイズで、クラス全体の空間計算量は $O(1)$ です。

API 動作・返り値 時間計算量
Random(uint64_t seed = 0) seed でエンジンを初期化する。 $O(1)$
Random(int argc, char **argv) argv[1] を10進の非負整数として読み、seed にする。argc < 2 なら seed は $0$。 $O(\lvert \mathtt{argv[1]} \rvert)$
uniform(uint64_t n) $[0,n)$ の一様な整数を返す。$n>0$。 期待 $O(1)$
randint(l, r) $[l,r)$ の一様な整数を返す。型は l, r, int の共通型。 期待 $O(1)$
randint(r) randint(0, r) と同じ。 期待 $O(1)$
even(l, r) $[l,r)$ に含まれる偶数から一様に1つ選ぶ。型は randint と同じ。 期待 $O(1)$
even(r) even(0, r) と同じ。 期待 $O(1)$
odd(l, r) $[l,r)$ に含まれる奇数から一様に1つ選ぶ。型は randint と同じ。 期待 $O(1)$
odd(r) odd(0, r) と同じ。 期待 $O(1)$
real(l, r) $[l,r)$ の double を返す。 $O(1)$
real() real(0.0, 1.0) と同じ。 $O(1)$
coin(p = 0.5) 確率 $p$ で true を返す。 $O(1)$
size(l, r) 小さい値に偏らせた $[l,r)$ の整数を返す。分布は後述。 期待 $O(1)$
choice(v) 空でない vector の要素を一様に1つ選び、参照を返す。 期待 $O(1)$
shuffle(v) vector を一様ランダムな順に並べ替える。 期待 $O(n)$
engine() 内部の std::mt19937_64 への参照。標準の分布と組み合わせる場合に使う。 $O(1)$

uniform は剰余の偏りを除くため、$2^{64} \bmod n$ 個の値を引いた場合に引き直します。1回で受理される確率は $1/2$ より大きいので、引き直しの回数の期待値は定数です。

利用条件と実装上の注意

Required by

Verified with

Code

#pragma once

#include <algorithm>
#include <cassert>
#include <cerrno>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <random>
#include <type_traits>
#include <utility>
#include <vector>

// seed を指定できる、ランダムテストの入力生成用の乱数
class Random {
  public:
    explicit Random(std::uint64_t seed = 0) : mt(seed) {}
    // argv[1] を seed として読む。引数がなければ seed = 0
    Random(int argc, char **argv) : mt(parse_seed(argc, argv)) {}

    // [0, n) の一様な整数 (n > 0)
    std::uint64_t uniform(std::uint64_t n) {
        assert(n > 0);
        // 2^64 mod n 個の値を棄却して剰余の偏りをなくす
        const std::uint64_t threshold = (0 - n) % n;
        std::uint64_t x = mt();
        while(x < threshold) x = mt();
        return x % n;
    }

    // [l, r) の一様な整数
    template <class T, class U>
    std::common_type_t<T, U, int> randint(T l, U r) {
        using C = std::common_type_t<T, U, int>;
        static_assert(std::is_integral<C>::value, "randint requires integers");
        const C lo = C(l), hi = C(r);
        assert(lo < hi);
        using UC = std::make_unsigned_t<C>;
        const std::uint64_t width = std::uint64_t(UC(hi) - UC(lo));
        return C(UC(lo) + UC(uniform(width)));
    }
    // [0, r) の一様な整数
    template <class T> std::common_type_t<T, int> randint(T r) {
        return randint(T(0), r);
    }

    // [l, r) に含まれる偶数から一様に選ぶ (偶数が 1 つ以上あること)
    template <class T, class U>
    std::common_type_t<T, U, int> even(T l, U r) {
        return with_parity(l, r, 0);
    }
    // [0, r) に含まれる偶数から一様に選ぶ
    template <class T> std::common_type_t<T, int> even(T r) {
        return even(T(0), r);
    }

    // [l, r) に含まれる奇数から一様に選ぶ (奇数が 1 つ以上あること)
    template <class T, class U>
    std::common_type_t<T, U, int> odd(T l, U r) {
        return with_parity(l, r, 1);
    }
    // [0, r) に含まれる奇数から一様に選ぶ
    template <class T> std::common_type_t<T, int> odd(T r) {
        return odd(T(0), r);
    }

    // [l, r) の実数 (53 bit の分解能)
    double real(double l, double r) {
        assert(l < r);
        const double u = double(mt() >> 11) / double(std::uint64_t(1) << 53);
        const double x = l + (r - l) * u;
        return x < r ? x : std::nextafter(r, l);
    }
    double real() { return real(0.0, 1.0); }

    // 確率 p で true
    bool coin(double p = 0.5) { return real() < p; }

    // 小さい値に偏らせた [l, r) の整数
    // 2 冪のスケール 1, 2, 4, ... を等確率で選び、その範囲で一様に選ぶ
    template <class T, class U>
    std::common_type_t<T, U, int> size(T l, U r) {
        using C = std::common_type_t<T, U, int>;
        const C lo = C(l), hi = C(r);
        assert(lo < hi);
        using UC = std::make_unsigned_t<C>;
        const std::uint64_t width = std::uint64_t(UC(hi) - UC(lo));
        int scales = 0;
        while(scales < 64 && (std::uint64_t(1) << scales) < width) scales++;
        const int k = int(uniform(std::uint64_t(scales + 1)));
        const std::uint64_t w = k >= 64 ? width : std::min(width, std::uint64_t(1) << k);
        return C(UC(lo) + UC(uniform(w)));
    }

    // v の要素を一様に 1 つ選ぶ (v は空でない)
    template <class T> const T &choice(const std::vector<T> &v) {
        assert(!v.empty());
        return v[uniform(v.size())];
    }

    // Fisher-Yates で v を一様にシャッフルする
    template <class T> void shuffle(std::vector<T> &v) {
        for(std::size_t i = v.size(); i > 1; i--) {
            std::swap(v[i - 1], v[uniform(i)]);
        }
    }

    // 標準の分布と組み合わせる場合のエンジン
    std::mt19937_64 &engine() { return mt; }

  private:
    std::mt19937_64 mt;

    // [l, r) のうち 2 で割った余りが parity (負の数も含めて数学的な偶奇) の値から一様に選ぶ
    template <class T, class U>
    std::common_type_t<T, U, int> with_parity(T l, U r, unsigned parity) {
        using C = std::common_type_t<T, U, int>;
        static_assert(std::is_integral<C>::value, "even/odd requires integers");
        using UC = std::make_unsigned_t<C>;
        const C lo = C(l), hi = C(r);
        assert(lo < hi);
        const std::uint64_t width = std::uint64_t(UC(hi) - UC(lo));
        // 2 の補数表現では UC への変換で偶奇が保たれる
        const std::uint64_t first = (std::uint64_t(UC(lo)) & 1) == parity ? 0 : 1;
        assert(first < width && "no integer of the requested parity in [l, r)");
        // first, first + 2, ... < width の個数 (width - first + 1 のあふれを避ける)
        const std::uint64_t count = (width - first - 1) / 2 + 1;
        return C(UC(lo) + UC(first + 2 * uniform(count)));
    }

    static std::uint64_t parse_seed(int argc, char **argv) {
        if(argc < 2) return 0;
        const char *s = argv[1];
        char *end = nullptr;
        errno = 0;
        const unsigned long long seed = std::strtoull(s, &end, 10);
        if(*s == '\0' || *s == '-' || *end != '\0' || errno == ERANGE) {
            std::cerr << "Random: invalid seed '" << s << "'\n";
            std::exit(2);
        }
        return seed;
    }
};
#line 2 "random/gen/random.hpp"

#include <algorithm>
#include <cassert>
#include <cerrno>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <random>
#include <type_traits>
#include <utility>
#include <vector>

// seed を指定できる、ランダムテストの入力生成用の乱数
class Random {
  public:
    explicit Random(std::uint64_t seed = 0) : mt(seed) {}
    // argv[1] を seed として読む。引数がなければ seed = 0
    Random(int argc, char **argv) : mt(parse_seed(argc, argv)) {}

    // [0, n) の一様な整数 (n > 0)
    std::uint64_t uniform(std::uint64_t n) {
        assert(n > 0);
        // 2^64 mod n 個の値を棄却して剰余の偏りをなくす
        const std::uint64_t threshold = (0 - n) % n;
        std::uint64_t x = mt();
        while(x < threshold) x = mt();
        return x % n;
    }

    // [l, r) の一様な整数
    template <class T, class U>
    std::common_type_t<T, U, int> randint(T l, U r) {
        using C = std::common_type_t<T, U, int>;
        static_assert(std::is_integral<C>::value, "randint requires integers");
        const C lo = C(l), hi = C(r);
        assert(lo < hi);
        using UC = std::make_unsigned_t<C>;
        const std::uint64_t width = std::uint64_t(UC(hi) - UC(lo));
        return C(UC(lo) + UC(uniform(width)));
    }
    // [0, r) の一様な整数
    template <class T> std::common_type_t<T, int> randint(T r) {
        return randint(T(0), r);
    }

    // [l, r) に含まれる偶数から一様に選ぶ (偶数が 1 つ以上あること)
    template <class T, class U>
    std::common_type_t<T, U, int> even(T l, U r) {
        return with_parity(l, r, 0);
    }
    // [0, r) に含まれる偶数から一様に選ぶ
    template <class T> std::common_type_t<T, int> even(T r) {
        return even(T(0), r);
    }

    // [l, r) に含まれる奇数から一様に選ぶ (奇数が 1 つ以上あること)
    template <class T, class U>
    std::common_type_t<T, U, int> odd(T l, U r) {
        return with_parity(l, r, 1);
    }
    // [0, r) に含まれる奇数から一様に選ぶ
    template <class T> std::common_type_t<T, int> odd(T r) {
        return odd(T(0), r);
    }

    // [l, r) の実数 (53 bit の分解能)
    double real(double l, double r) {
        assert(l < r);
        const double u = double(mt() >> 11) / double(std::uint64_t(1) << 53);
        const double x = l + (r - l) * u;
        return x < r ? x : std::nextafter(r, l);
    }
    double real() { return real(0.0, 1.0); }

    // 確率 p で true
    bool coin(double p = 0.5) { return real() < p; }

    // 小さい値に偏らせた [l, r) の整数
    // 2 冪のスケール 1, 2, 4, ... を等確率で選び、その範囲で一様に選ぶ
    template <class T, class U>
    std::common_type_t<T, U, int> size(T l, U r) {
        using C = std::common_type_t<T, U, int>;
        const C lo = C(l), hi = C(r);
        assert(lo < hi);
        using UC = std::make_unsigned_t<C>;
        const std::uint64_t width = std::uint64_t(UC(hi) - UC(lo));
        int scales = 0;
        while(scales < 64 && (std::uint64_t(1) << scales) < width) scales++;
        const int k = int(uniform(std::uint64_t(scales + 1)));
        const std::uint64_t w = k >= 64 ? width : std::min(width, std::uint64_t(1) << k);
        return C(UC(lo) + UC(uniform(w)));
    }

    // v の要素を一様に 1 つ選ぶ (v は空でない)
    template <class T> const T &choice(const std::vector<T> &v) {
        assert(!v.empty());
        return v[uniform(v.size())];
    }

    // Fisher-Yates で v を一様にシャッフルする
    template <class T> void shuffle(std::vector<T> &v) {
        for(std::size_t i = v.size(); i > 1; i--) {
            std::swap(v[i - 1], v[uniform(i)]);
        }
    }

    // 標準の分布と組み合わせる場合のエンジン
    std::mt19937_64 &engine() { return mt; }

  private:
    std::mt19937_64 mt;

    // [l, r) のうち 2 で割った余りが parity (負の数も含めて数学的な偶奇) の値から一様に選ぶ
    template <class T, class U>
    std::common_type_t<T, U, int> with_parity(T l, U r, unsigned parity) {
        using C = std::common_type_t<T, U, int>;
        static_assert(std::is_integral<C>::value, "even/odd requires integers");
        using UC = std::make_unsigned_t<C>;
        const C lo = C(l), hi = C(r);
        assert(lo < hi);
        const std::uint64_t width = std::uint64_t(UC(hi) - UC(lo));
        // 2 の補数表現では UC への変換で偶奇が保たれる
        const std::uint64_t first = (std::uint64_t(UC(lo)) & 1) == parity ? 0 : 1;
        assert(first < width && "no integer of the requested parity in [l, r)");
        // first, first + 2, ... < width の個数 (width - first + 1 のあふれを避ける)
        const std::uint64_t count = (width - first - 1) / 2 + 1;
        return C(UC(lo) + UC(first + 2 * uniform(count)));
    }

    static std::uint64_t parse_seed(int argc, char **argv) {
        if(argc < 2) return 0;
        const char *s = argv[1];
        char *end = nullptr;
        errno = 0;
        const unsigned long long seed = std::strtoull(s, &end, 10);
        if(*s == '\0' || *s == '-' || *end != '\0' || errno == ERANGE) {
            std::cerr << "Random: invalid seed '" << s << "'\n";
            std::exit(2);
        }
        return seed;
    }
};
Back to top page