UNPKG

oimp

Version:

A CLI tool for generating OI problem and packages

1,466 lines (1,260 loc) 204 kB
export const testlibHeader = ` /* * It is strictly recommended to include "testlib.h" before any other include * in your code. In this case testlib overrides compiler specific "random()". * * If you can't compile your code and compiler outputs something about * ambiguous call of "random_shuffle", "rand" or "srand" it means that * you shouldn't use them. Use "shuffle", and "rnd.next()" instead of them * because these calls produce stable result for any C++ compiler. Read * sample generator sources for clarification. * * Please read the documentation for class "random_t" and use "rnd" instance in * generators. Probably, these sample calls will be useful for you: * rnd.next(); rnd.next(100); rnd.next(1, 2); * rnd.next(3.14); rnd.next("[a-z]{1,100}"). * * Also read about wnext() to generate off-center random distribution. * * See https://github.com/MikeMirzayanov/testlib/ to get latest version or bug tracker. */ #ifndef _TESTLIB_H_ #define _TESTLIB_H_ /* * Copyright (c) 2005-2024 */ #define VERSION "0.9.42-SNAPSHOT" /* * Mike Mirzayanov * * This material is provided "as is", with absolutely no warranty expressed * or implied. Any use is at your own risk. * * Permission to use or copy this software for any purpose is hereby granted * without fee, provided the above notices are retained on all copies. * Permission to modify the code and to distribute modified code is granted, * provided the above notices are retained, and a notice that the code was * modified is included with the above copyright notice. * */ /* NOTE: This file contains testlib library for C++. * * Check, using testlib running format: * check.exe <Input_File> <Output_File> <Answer_File> [<Result_File> [-appes]], * If result file is specified it will contain results. * * Validator, using testlib running format: * validator.exe < input.txt, * It will return non-zero exit code and writes message to standard output. * * Generator, using testlib running format: * gen.exe [parameter-1] [parameter-2] [... paramerter-n] * You can write generated test(s) into standard output or into the file(s). * * Interactor, using testlib running format: * interactor.exe <Input_File> <Output_File> [<Answer_File> [<Result_File> [-appes]]], * Reads test from inf (mapped to args[1]), writes result to tout (mapped to argv[2], * can be judged by checker later), reads program output from ouf (mapped to stdin), * writes output to program via stdout (use cout, printf, etc). */ const char *latestFeatures[] = { "Added ConstantBoundsLog, VariablesLog to validator testOverviewLogFile", "Use setAppesModeEncoding to change xml encoding from windows-1251 to other", "rnd.any/wany use distance/advance instead of -/+: now they support sets/multisets", "Use syntax int t = inf.readInt(1, 3, \"~t\"); to skip the lower bound check. Tildes can be used on either side or both: ~t, t~, ~t~", "Supported EJUDGE support in registerTestlibCmd", "Supported '--testMarkupFileName fn' and '--testCase tc/--testCaseFileName fn' for validators", "Added opt defaults via opt<T>(key/index, default_val); check unused opts when using has_opt or default opt (turn off this check with suppressEnsureNoUnusedOpt()).", "For checker added --group and --testset command line params (like for validator), use checker.group() or checker.testset() to get values", "Added quitpi(points_info, message) function to return with _points exit code 7 and given points_info", "rnd.partition(size, sum[, min_part=1]) returns random (unsorted) partition which is a representation of the given 'sum' as a sum of 'size' positive integers (or >=min_part if specified)", "rnd.distinct(size, n) and rnd.distinct(size, from, to)", "opt<bool>(\"some_missing_key\") returns false now", "has_opt(key)", "Abort validator on validator.testset()/validator.group() if registered without using command line", "Print integer range violations in a human readable way like 'violates the range [1, 10^9]'", "Opts supported: use them like n = opt<int>(\"n\"), in a command line you can use an exponential notation", "Reformatted", "Use setTestCase(i) or unsetTestCase() to support test cases (you can use it in any type of program: generator, interactor, validator or checker)", "Fixed issue #87: readStrictDouble accepts \"-0.00\"", "Fixed issue #83: added InStream::quitif(condition, ...)", "Fixed issue #79: fixed missed guard against repeated header include", "Fixed issue #80: fixed UB in case of huge quitf message", "Fixed issue #84: added readXs(size, indexBase = 1)", "Fixed stringstream repeated usage issue", "Fixed compilation in g++ (for std=c++03)", "Batch of println functions (support collections, iterator ranges)", "Introduced rnd.perm(size, first = 0) to generate a 'first'-indexed permutation", "Allow any whitespace in readInts-like functions for non-validators", "Ignore 4+ command line arguments ifdef EJUDGE", "Speed up of vtos", "Show line number in validators in case of incorrect format", "Truncate huge checker/validator/interactor message", "Fixed issue with readTokenTo of very long tokens, now aborts with _pe/_fail depending of a stream type", "Introduced InStream::ensure/ensuref checking a condition, returns wa/fail depending of a stream type", "Fixed compilation in VS 2015+", "Introduced space-separated read functions: readWords/readTokens, multilines read functions: readStrings/readLines", "Introduced space-separated read functions: readInts/readIntegers/readLongs/readUnsignedLongs/readDoubles/readReals/readStrictDoubles/readStrictReals", "Introduced split/tokenize functions to separate string by given char", "Introduced InStream::readUnsignedLong and InStream::readLong with unsigned long long parameters", "Supported --testOverviewLogFileName for validator: bounds hits + features", "Fixed UB (sequence points) in random_t", "POINTS_EXIT_CODE returned back to 7 (instead of 0)", "Removed disable buffers for interactive problems, because it works unexpectedly in wine", "InStream over string: constructor of InStream from base InStream to inherit policies and std::string", "Added expectedButFound quit function, examples: expectedButFound(_wa, 10, 20), expectedButFound(_fail, ja, pa, \"[n=%d,m=%d]\", n, m)", "Fixed incorrect interval parsing in patterns", "Use registerGen(argc, argv, 1) to develop new generator, use registerGen(argc, argv, 0) to compile old generators (originally created for testlib under 0.8.7)", "Introduced disableFinalizeGuard() to switch off finalization checkings", "Use join() functions to format a range of items as a single string (separated by spaces or other separators)", "Use -DENABLE_UNEXPECTED_EOF to enable special exit code (by default, 8) in case of unexpected eof. It is good idea to use it in interactors", "Use -DUSE_RND_AS_BEFORE_087 to compile in compatibility mode with random behavior of versions before 0.8.7", "Fixed bug with nan in stringToDouble", "Fixed issue around overloads for size_t on x64", "Added attribute 'points' to the XML output in case of result=_points", "Exit codes can be customized via macros, e.g. -DPE_EXIT_CODE=14", "Introduced InStream function readWordTo/readTokenTo/readStringTo/readLineTo for faster reading", "Introduced global functions: format(), englishEnding(), upperCase(), lowerCase(), compress()", "Manual buffer in InStreams, some IO speed improvements", "Introduced quitif(bool, const char* pattern, ...) which delegates to quitf() in case of first argument is true", "Introduced guard against missed quitf() in checker or readEof() in validators", "Supported readStrictReal/readStrictDouble - to use in validators to check strictly float numbers", "Supported registerInteraction(argc, argv)", "Print checker message to the stderr instead of stdout", "Supported TResult _points to output calculated score, use quitp(...) functions", "Fixed to be compilable on Mac", "PC_BASE_EXIT_CODE=50 in case of defined TESTSYS", "Fixed issues 19-21, added __attribute__ format printf", "Some bug fixes", "ouf.readInt(1, 100) and similar calls return WA", "Modified random_t to avoid integer overflow", "Truncated checker output [patch by Stepan Gatilov]", "Renamed class random -> class random_t", "Supported name parameter for read-and-validation methods, like readInt(1, 2, \"n\")", "Fixed bug in readDouble()", "Improved ensuref(), fixed nextLine to work in case of EOF, added startTest()", "Supported \"partially correct\", example: quitf(_pc(13), \"result=%d\", result)", "Added shuffle(begin, end), use it instead of random_shuffle(begin, end)", "Added readLine(const string& ptrn), fixed the logic of readLine() in the validation mode", "Package extended with samples of generators and validators", "Written the documentation for classes and public methods in testlib.h", "Implemented random routine to support generators, use registerGen() to switch it on", "Implemented strict mode to validate tests, use registerValidation() to switch it on", "Now ncmp.cpp and wcmp.cpp are return WA if answer is suffix or prefix of the output", "Added InStream::readLong() and removed InStream::readLongint()", "Now no footer added to each report by default (use directive FOOTER to switch on)", "Now every checker has a name, use setName(const char* format, ...) to set it", "Now it is compatible with TTS (by Kittens Computing)", "Added \'ensure(condition, message = \"\")\' feature, it works like assert()", "Fixed compatibility with MS C++ 7.1", "Added footer with exit code information", "Added compatibility with EJUDGE (compile with EJUDGE directive)", "Added compatibility with Contester (compile with CONTESTER directive)" }; #ifdef _MSC_VER #define _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_NO_WARNINGS #define _CRT_NO_VA_START_VALIDATION #endif /* Overrides random() for Borland C++. */ #define random __random_deprecated #include <stdlib.h> #include <cstdlib> #include <climits> #include <algorithm> #undef random #include <cstdio> #include <cctype> #include <string> #include <vector> #include <map> #include <set> #include <cmath> #include <iterator> #include <iostream> #include <sstream> #include <fstream> #include <cstring> #include <limits> #include <stdarg.h> #include <fcntl.h> #include <functional> #include <cstdint> #ifdef TESTLIB_THROW_EXIT_EXCEPTION_INSTEAD_OF_EXIT # include <exception> #endif #if (_WIN32 || __WIN32__ || __WIN32 || _WIN64 || __WIN64__ || __WIN64 || WINNT || __WINNT || __WINNT__ || __CYGWIN__) # if !defined(_MSC_VER) || _MSC_VER > 1400 # define NOMINMAX 1 # include <windows.h> # else # define WORD unsigned short # include <unistd.h> # endif # include <io.h> # define ON_WINDOWS # if defined(_MSC_VER) && _MSC_VER > 1400 # pragma warning( disable : 4127 ) # pragma warning( disable : 4146 ) # pragma warning( disable : 4458 ) # endif #else # define WORD unsigned short # include <unistd.h> #endif #if defined(FOR_WINDOWS) && defined(FOR_LINUX) #error Only one target system is allowed #endif #ifndef LLONG_MIN #define LLONG_MIN (-9223372036854775807LL - 1) #endif #ifndef ULLONG_MAX #define ULLONG_MAX (18446744073709551615) #endif #define LF ((char)10) #define CR ((char)13) #define TAB ((char)9) #define SPACE ((char)' ') #define EOFC (255) #ifndef OK_EXIT_CODE # ifdef CONTESTER # define OK_EXIT_CODE 0xAC # else # define OK_EXIT_CODE 0 # endif #endif #ifndef WA_EXIT_CODE # ifdef EJUDGE # define WA_EXIT_CODE 5 # elif defined(CONTESTER) # define WA_EXIT_CODE 0xAB # else # define WA_EXIT_CODE 1 # endif #endif #ifndef PE_EXIT_CODE # ifdef EJUDGE # define PE_EXIT_CODE 4 # elif defined(CONTESTER) # define PE_EXIT_CODE 0xAA # else # define PE_EXIT_CODE 2 # endif #endif #ifndef FAIL_EXIT_CODE # ifdef EJUDGE # define FAIL_EXIT_CODE 6 # elif defined(CONTESTER) # define FAIL_EXIT_CODE 0xA3 # else # define FAIL_EXIT_CODE 3 # endif #endif #ifndef DIRT_EXIT_CODE # ifdef EJUDGE # define DIRT_EXIT_CODE 6 # else # define DIRT_EXIT_CODE 4 # endif #endif #ifndef POINTS_EXIT_CODE # define POINTS_EXIT_CODE 7 #endif #ifndef UNEXPECTED_EOF_EXIT_CODE # define UNEXPECTED_EOF_EXIT_CODE 8 #endif #ifndef PC_BASE_EXIT_CODE # ifdef TESTSYS # define PC_BASE_EXIT_CODE 50 # else # define PC_BASE_EXIT_CODE 0 # endif #endif #ifdef __GNUC__ # define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[(condition) ? 1 : -1] __attribute__((unused)) #else # define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[(condition) ? 1 : -1] #endif #ifdef ON_WINDOWS #define I64 "%I64d" #define U64 "%I64u" #else #define I64 "%lld" #define U64 "%llu" #endif #ifdef _MSC_VER # define NORETURN __declspec(noreturn) #elif defined __GNUC__ # define NORETURN __attribute__ ((noreturn)) #else # define NORETURN #endif static char __testlib_format_buffer[16777216]; static int __testlib_format_buffer_usage_count = 0; #define FMT_TO_RESULT(fmt, cstr, result) std::string result; \ if (__testlib_format_buffer_usage_count != 0) \ __testlib_fail("FMT_TO_RESULT::__testlib_format_buffer_usage_count != 0"); \ __testlib_format_buffer_usage_count++; \ va_list ap; \ va_start(ap, fmt); \ vsnprintf(__testlib_format_buffer, sizeof(__testlib_format_buffer), cstr, ap); \ va_end(ap); \ __testlib_format_buffer[sizeof(__testlib_format_buffer) - 1] = 0; \ result = std::string(__testlib_format_buffer); \ __testlib_format_buffer_usage_count--; \ const long long __TESTLIB_LONGLONG_MAX = 9223372036854775807LL; const int __TESTLIB_MAX_TEST_CASE = 1073741823; int __testlib_exitCode; bool __testlib_hasTestCase; int __testlib_testCase = -1; void setTestCase(int testCase); void unsetTestCase() { __testlib_hasTestCase = false; __testlib_testCase = -1; } NORETURN static void __testlib_fail(const std::string &message); template<typename T> #ifdef __GNUC__ __attribute__((const)) #endif static inline T __testlib_abs(const T &x) { return x > 0 ? x : -x; } template<typename T> #ifdef __GNUC__ __attribute__((const)) #endif static inline T __testlib_min(const T &a, const T &b) { return a < b ? a : b; } template<typename T> #ifdef __GNUC__ __attribute__((const)) #endif static inline T __testlib_max(const T &a, const T &b) { return a > b ? a : b; } template<typename T> #ifdef __GNUC__ __attribute__((const)) #endif static inline T __testlib_crop(T value, T a, T b) { return __testlib_min(__testlib_max(value, a), --b); } #ifdef __GNUC__ __attribute__((const)) #endif static inline double __testlib_crop(double value, double a, double b) { value = __testlib_min(__testlib_max(value, a), b); if (value >= b) value = std::nexttoward(b, a); return value; } static bool __testlib_prelimIsNaN(double r) { volatile double ra = r; #ifndef __BORLANDC__ return ((ra != ra) == true) && ((ra == ra) == false) && ((1.0 > ra) == false) && ((1.0 < ra) == false); #else return std::_isnan(ra); #endif } #ifdef __GNUC__ __attribute__((const)) #endif static std::string removeDoubleTrailingZeroes(std::string value) { while (!value.empty() && value[value.length() - 1] == '0' && value.find('.') != std::string::npos) value = value.substr(0, value.length() - 1); if (!value.empty() && value[value.length() - 1] == '.') return value + '0'; else return value; } #ifdef __GNUC__ __attribute__((const)) #endif inline std::string upperCase(std::string s) { for (size_t i = 0; i < s.length(); i++) if ('a' <= s[i] && s[i] <= 'z') s[i] = char(s[i] - 'a' + 'A'); return s; } #ifdef __GNUC__ __attribute__((const)) #endif inline std::string lowerCase(std::string s) { for (size_t i = 0; i < s.length(); i++) if ('A' <= s[i] && s[i] <= 'Z') s[i] = char(s[i] - 'A' + 'a'); return s; } #ifdef __GNUC__ __attribute__ ((format (printf, 1, 2))) #endif std::string format(const char *fmt, ...) { FMT_TO_RESULT(fmt, fmt, result); return result; } std::string format(const std::string fmt, ...) { FMT_TO_RESULT(fmt, fmt.c_str(), result); return result; } #ifdef __GNUC__ __attribute__((const)) #endif static std::string __testlib_part(const std::string &s); static bool __testlib_isNaN(double r) { __TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long)); volatile double ra = r; long long llr1, llr2; std::memcpy((void *) &llr1, (void *) &ra, sizeof(double)); ra = -ra; std::memcpy((void *) &llr2, (void *) &ra, sizeof(double)); long long llnan = 0xFFF8000000000000LL; return __testlib_prelimIsNaN(r) || llnan == llr1 || llnan == llr2; } static double __testlib_nan() { __TESTLIB_STATIC_ASSERT(sizeof(double) == sizeof(long long)); #ifndef NAN long long llnan = 0xFFF8000000000000LL; double nan; std::memcpy(&nan, &llnan, sizeof(double)); return nan; #else return NAN; #endif } static bool __testlib_isInfinite(double r) { volatile double ra = r; return (ra > 1E300 || ra < -1E300); } #ifdef __GNUC__ __attribute__((const)) #endif inline bool doubleCompare(double expected, double result, double MAX_DOUBLE_ERROR) { MAX_DOUBLE_ERROR += 1E-15; if (__testlib_isNaN(expected)) { return __testlib_isNaN(result); } else if (__testlib_isInfinite(expected)) { if (expected > 0) { return result > 0 && __testlib_isInfinite(result); } else { return result < 0 && __testlib_isInfinite(result); } } else if (__testlib_isNaN(result) || __testlib_isInfinite(result)) { return false; } else if (__testlib_abs(result - expected) <= MAX_DOUBLE_ERROR) { return true; } else { double minv = __testlib_min(expected * (1.0 - MAX_DOUBLE_ERROR), expected * (1.0 + MAX_DOUBLE_ERROR)); double maxv = __testlib_max(expected * (1.0 - MAX_DOUBLE_ERROR), expected * (1.0 + MAX_DOUBLE_ERROR)); return result >= minv && result <= maxv; } } #ifdef __GNUC__ __attribute__((const)) #endif inline double doubleDelta(double expected, double result) { double absolute = __testlib_abs(result - expected); if (__testlib_abs(expected) > 1E-9) { double relative = __testlib_abs(absolute / expected); return __testlib_min(absolute, relative); } else return absolute; } /** It does nothing on non-windows and files differ from stdin/stdout/stderr. */ static void __testlib_set_binary(std::FILE *file) { if (NULL != file) { #ifdef ON_WINDOWS # ifdef _O_BINARY if (stdin == file) # ifdef STDIN_FILENO return void(_setmode(STDIN_FILENO, _O_BINARY)); # else return void(_setmode(_fileno(stdin), _O_BINARY)); # endif if (stdout == file) # ifdef STDOUT_FILENO return void(_setmode(STDOUT_FILENO, _O_BINARY)); # else return void(_setmode(_fileno(stdout), _O_BINARY)); # endif if (stderr == file) # ifdef STDERR_FILENO return void(_setmode(STDERR_FILENO, _O_BINARY)); # else return void(_setmode(_fileno(stderr), _O_BINARY)); # endif # elif O_BINARY if (stdin == file) # ifdef STDIN_FILENO return void(setmode(STDIN_FILENO, O_BINARY)); # else return void(setmode(fileno(stdin), O_BINARY)); # endif if (stdout == file) # ifdef STDOUT_FILENO return void(setmode(STDOUT_FILENO, O_BINARY)); # else return void(setmode(fileno(stdout), O_BINARY)); # endif if (stderr == file) # ifdef STDERR_FILENO return void(setmode(STDERR_FILENO, O_BINARY)); # else return void(setmode(fileno(stderr), O_BINARY)); # endif # endif #endif } } #if __cplusplus > 199711L || defined(_MSC_VER) template<typename T> #ifdef __GNUC__ __attribute__((const)) #endif static std::string vtos(const T &t, std::true_type) { if (t == 0) return "0"; else { T n(t); bool negative = n < 0; std::string s; while (n != 0) { T digit = n % 10; if (digit < 0) digit = -digit; s += char('0' + digit); n /= 10; } std::reverse(s.begin(), s.end()); return negative ? "-" + s : s; } } template<typename T> static std::string vtos(const T &t, std::false_type) { std::string s; static std::stringstream ss; ss.str(std::string()); ss.clear(); ss << t; ss >> s; return s; } template<typename T> static std::string vtos(const T &t) { return vtos(t, std::is_integral<T>()); } /* signed case. */ template<typename T> static std::string toHumanReadableString(const T &n, std::false_type) { if (n == 0) return vtos(n); int trailingZeroCount = 0; T n_ = n; while (n_ % 10 == 0) n_ /= 10, trailingZeroCount++; if (trailingZeroCount >= 7) { if (n_ == 1) return "10^" + vtos(trailingZeroCount); else if (n_ == -1) return "-10^" + vtos(trailingZeroCount); else return vtos(n_) + "*10^" + vtos(trailingZeroCount); } else return vtos(n); } /* unsigned case. */ template<typename T> static std::string toHumanReadableString(const T &n, std::true_type) { if (n == 0) return vtos(n); int trailingZeroCount = 0; T n_ = n; while (n_ % 10 == 0) n_ /= 10, trailingZeroCount++; if (trailingZeroCount >= 7) { if (n_ == 1) return "10^" + vtos(trailingZeroCount); else return vtos(n_) + "*10^" + vtos(trailingZeroCount); } else return vtos(n); } template<typename T> static std::string toHumanReadableString(const T &n) { return toHumanReadableString(n, std::is_unsigned<T>()); } #else template<typename T> static std::string vtos(const T& t) { std::string s; static std::stringstream ss; ss.str(std::string()); ss.clear(); ss << t; ss >> s; return s; } template<typename T> static std::string toHumanReadableString(const T &n) { return vtos(n); } #endif template<typename T> static std::string toString(const T &t) { return vtos(t); } #if __cplusplus > 199711L || defined(_MSC_VER) /* opts */ void prepareOpts(int argc, char* argv[]); #endif /* * Very simple regex-like pattern. * It used for two purposes: validation and generation. * * For example, pattern("[a-z]{1,5}").next(rnd) will return * random string from lowercase latin letters with length * from 1 to 5. It is easier to call rnd.next("[a-z]{1,5}") * for the same effect. * * Another samples: * "mike|john" will generate (match) "mike" or "john"; * "-?[1-9][0-9]{0,3}" will generate (match) non-zero integers from -9999 to 9999; * "id-([ac]|b{2})" will generate (match) "id-a", "id-bb", "id-c"; * "[^0-9]*" will match sequences (empty or non-empty) without digits, you can't * use it for generations. * * You can't use pattern for generation if it contains meta-symbol '*'. Also it * is not recommended to use it for char-sets with meta-symbol '^' like [^a-z]. * * For matching very simple greedy algorithm is used. For example, pattern * "[0-9]?1" will not match "1", because of greedy nature of matching. * Alternations (meta-symbols "|") are processed with brute-force algorithm, so * do not use many alternations in one expression. * * If you want to use one expression many times it is better to compile it into * a single pattern like "pattern p("[a-z]+")". Later you can use * "p.matches(std::string s)" or "p.next(random_t& rd)" to check matching or generate * new string by pattern. * * Simpler way to read token and check it for pattern matching is "inf.readToken("[a-z]+")". * * All spaces are ignored in regex, unless escaped with \. For example, ouf.readLine("NO SOLUTION") * will expect "NOSOLUTION", the correct call should be ouf.readLine("NO\\ SOLUTION") or * ouf.readLine(R"(NO\ SOLUTION)") if you prefer raw string literals from C++11. */ class random_t; class pattern { public: /* Create pattern instance by string. */ pattern(std::string s); /* Generate new string by pattern and given random_t. */ std::string next(random_t &rnd) const; /* Checks if given string match the pattern. */ bool matches(const std::string &s) const; /* Returns source string of the pattern. */ std::string src() const; private: bool matches(const std::string &s, size_t pos) const; std::string s; std::vector<pattern> children; std::vector<char> chars; int from; int to; }; /* * Use random_t instances to generate random values. It is preferred * way to use randoms instead of rand() function or self-written * randoms. * * Testlib defines global variable "rnd" of random_t class. * Use registerGen(argc, argv, 1) to setup random_t seed be command * line (to use latest random generator version). * * Random generates uniformly distributed values if another strategy is * not specified explicitly. */ class random_t { private: unsigned long long seed; static const unsigned long long multiplier; static const unsigned long long addend; static const unsigned long long mask; static const int lim; long long nextBits(int bits) { if (bits <= 48) { seed = (seed * multiplier + addend) & mask; return (long long) (seed >> (48 - bits)); } else { if (bits > 63) __testlib_fail("random_t::nextBits(int bits): n must be less than 64"); int lowerBitCount = (random_t::version == 0 ? 31 : 32); long long left = (nextBits(31) << 32); long long right = nextBits(lowerBitCount); return left ^ right; } } public: static int version; /* New random_t with fixed seed. */ random_t() : seed(3905348978240129619LL) { } /* Sets seed by command line. */ void setSeed(int argc, char *argv[]) { random_t p; seed = 3905348978240129619LL; for (int i = 1; i < argc; i++) { std::size_t le = std::strlen(argv[i]); for (std::size_t j = 0; j < le; j++) seed = seed * multiplier + (unsigned int) (argv[i][j]) + addend; seed += multiplier / addend; } seed = seed & mask; } /* Sets seed by given value. */ void setSeed(long long _seed) { seed = (unsigned long long) _seed; seed = (seed ^ multiplier) & mask; } #ifndef __BORLANDC__ /* Random string value by given pattern (see pattern documentation). */ std::string next(const std::string &ptrn) { pattern p(ptrn); return p.next(*this); } #else /* Random string value by given pattern (see pattern documentation). */ std::string next(std::string ptrn) { pattern p(ptrn); return p.next(*this); } #endif /* Random value in range [0, n-1]. */ int next(int n) { if (n <= 0) __testlib_fail("random_t::next(int n): n must be positive"); if ((n & -n) == n) // n is a power of 2 return (int) ((n * (long long) nextBits(31)) >> 31); const long long limit = INT_MAX / n * n; long long bits; do { bits = nextBits(31); } while (bits >= limit); return int(bits % n); } /* Random value in range [0, n-1]. */ unsigned int next(unsigned int n) { if (n >= INT_MAX) __testlib_fail("random_t::next(unsigned int n): n must be less INT_MAX"); return (unsigned int) next(int(n)); } /* Random value in range [0, n-1]. */ long long next(long long n) { if (n <= 0) __testlib_fail("random_t::next(long long n): n must be positive"); const long long limit = __TESTLIB_LONGLONG_MAX / n * n; long long bits; do { bits = nextBits(63); } while (bits >= limit); return bits % n; } /* Random value in range [0, n-1]. */ unsigned long long next(unsigned long long n) { if (n >= (unsigned long long) (__TESTLIB_LONGLONG_MAX)) __testlib_fail("random_t::next(unsigned long long n): n must be less LONGLONG_MAX"); return (unsigned long long) next((long long) (n)); } /* Random value in range [0, n-1]. */ long next(long n) { return (long) next((long long) (n)); } /* Random value in range [0, n-1]. */ unsigned long next(unsigned long n) { if (n >= (unsigned long) (LONG_MAX)) __testlib_fail("random_t::next(unsigned long n): n must be less LONG_MAX"); return (unsigned long) next((unsigned long long) (n)); } /* Returns random value in range [from,to]. */ int next(int from, int to) { return int(next((long long) to - from + 1) + from); } /* Returns random value in range [from,to]. */ unsigned int next(unsigned int from, unsigned int to) { return (unsigned int) (next((long long) to - from + 1) + from); } /* Returns random value in range [from,to]. */ long long next(long long from, long long to) { return next(to - from + 1) + from; } /* Returns random value in range [from,to]. */ unsigned long long next(unsigned long long from, unsigned long long to) { if (from > to) __testlib_fail("random_t::next(unsigned long long from, unsigned long long to): from can't not exceed to"); return next(to - from + 1) + from; } /* Returns random value in range [from,to]. */ long next(long from, long to) { return next(to - from + 1) + from; } /* Returns random value in range [from,to]. */ unsigned long next(unsigned long from, unsigned long to) { if (from > to) __testlib_fail("random_t::next(unsigned long from, unsigned long to): from can't not exceed to"); return next(to - from + 1) + from; } /* Random double value in range [0, 1). */ double next() { long long left = ((long long) (nextBits(26)) << 27); long long right = nextBits(27); return __testlib_crop((double) (left + right) / (double) (1LL << 53), 0.0, 1.0); } /* Random double value in range [0, n). */ double next(double n) { if (n <= 0.0) __testlib_fail("random_t::next(double): n should be positive"); return __testlib_crop(n * next(), 0.0, n); } /* Random double value in range [from, to). */ double next(double from, double to) { if (from >= to) __testlib_fail("random_t::next(double from, double to): from should be strictly less than to"); return next(to - from) + from; } /* Returns random element from container. */ template<typename Container> typename Container::value_type any(const Container &c) { int size = int(c.size()); if (size <= 0) __testlib_fail("random_t::any(const Container& c): c.size() must be positive"); typename Container::const_iterator it = c.begin(); std::advance(it, next(size)); return *it; } /* Returns random element from iterator range. */ template<typename Iter> typename Iter::value_type any(const Iter &begin, const Iter &end) { int size = static_cast<int>(std::distance(begin, end)); if (size <= 0) __testlib_fail("random_t::any(const Iter& begin, const Iter& end): range must have positive length"); Iter it = begin; std::advance(it, next(size)); return *it; } /* Random string value by given pattern (see pattern documentation). */ #ifdef __GNUC__ __attribute__ ((format (printf, 2, 3))) #endif std::string next(const char *format, ...) { FMT_TO_RESULT(format, format, ptrn); return next(ptrn); } /* * Weighted next. If type == 0 than it is usual "next()". * * If type = 1, than it returns "max(next(), next())" * (the number of "max" functions equals to "type"). * * If type < 0, than "max" function replaces with "min". */ int wnext(int n, int type) { if (n <= 0) __testlib_fail("random_t::wnext(int n, int type): n must be positive"); if (abs(type) < random_t::lim) { int result = next(n); for (int i = 0; i < +type; i++) result = __testlib_max(result, next(n)); for (int i = 0; i < -type; i++) result = __testlib_min(result, next(n)); return result; } else { double p; if (type > 0) p = std::pow(next() + 0.0, 1.0 / (type + 1)); else p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1)); return __testlib_crop((int) (double(n) * p), 0, n); } } /* See wnext(int, int). It uses the same algorithms. */ long long wnext(long long n, int type) { if (n <= 0) __testlib_fail("random_t::wnext(long long n, int type): n must be positive"); if (abs(type) < random_t::lim) { long long result = next(n); for (int i = 0; i < +type; i++) result = __testlib_max(result, next(n)); for (int i = 0; i < -type; i++) result = __testlib_min(result, next(n)); return result; } else { double p; if (type > 0) p = std::pow(next() + 0.0, 1.0 / (type + 1)); else p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1)); return __testlib_crop((long long) (double(n) * p), 0LL, n); } } /* Returns value in [0, n). See wnext(int, int). It uses the same algorithms. */ double wnext(double n, int type) { if (n <= 0) __testlib_fail("random_t::wnext(double n, int type): n must be positive"); if (abs(type) < random_t::lim) { double result = next(); for (int i = 0; i < +type; i++) result = __testlib_max(result, next()); for (int i = 0; i < -type; i++) result = __testlib_min(result, next()); return n * result; } else { double p; if (type > 0) p = std::pow(next() + 0.0, 1.0 / (type + 1)); else p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1)); return __testlib_crop(n * p, 0.0, n); } } /* Returns value in [0, 1). See wnext(int, int). It uses the same algorithms. */ double wnext(int type) { return wnext(1.0, type); } /* See wnext(int, int). It uses the same algorithms. */ unsigned int wnext(unsigned int n, int type) { if (n >= INT_MAX) __testlib_fail("random_t::wnext(unsigned int n, int type): n must be less INT_MAX"); return (unsigned int) wnext(int(n), type); } /* See wnext(int, int). It uses the same algorithms. */ unsigned long long wnext(unsigned long long n, int type) { if (n >= (unsigned long long) (__TESTLIB_LONGLONG_MAX)) __testlib_fail("random_t::wnext(unsigned long long n, int type): n must be less LONGLONG_MAX"); return (unsigned long long) wnext((long long) (n), type); } /* See wnext(int, int). It uses the same algorithms. */ long wnext(long n, int type) { return (long) wnext((long long) (n), type); } /* See wnext(int, int). It uses the same algorithms. */ unsigned long wnext(unsigned long n, int type) { if (n >= (unsigned long) (LONG_MAX)) __testlib_fail("random_t::wnext(unsigned long n, int type): n must be less LONG_MAX"); return (unsigned long) wnext((unsigned long long) (n), type); } /* Returns weighted random value in range [from, to]. */ int wnext(int from, int to, int type) { if (from > to) __testlib_fail("random_t::wnext(int from, int to, int type): from can't not exceed to"); return wnext(to - from + 1, type) + from; } /* Returns weighted random value in range [from, to]. */ int wnext(unsigned int from, unsigned int to, int type) { if (from > to) __testlib_fail("random_t::wnext(unsigned int from, unsigned int to, int type): from can't not exceed to"); return int(wnext(to - from + 1, type) + from); } /* Returns weighted random value in range [from, to]. */ long long wnext(long long from, long long to, int type) { if (from > to) __testlib_fail("random_t::wnext(long long from, long long to, int type): from can't not exceed to"); return wnext(to - from + 1, type) + from; } /* Returns weighted random value in range [from, to]. */ unsigned long long wnext(unsigned long long from, unsigned long long to, int type) { if (from > to) __testlib_fail( "random_t::wnext(unsigned long long from, unsigned long long to, int type): from can't not exceed to"); return wnext(to - from + 1, type) + from; } /* Returns weighted random value in range [from, to]. */ long wnext(long from, long to, int type) { if (from > to) __testlib_fail("random_t::wnext(long from, long to, int type): from can't not exceed to"); return wnext(to - from + 1, type) + from; } /* Returns weighted random value in range [from, to]. */ unsigned long wnext(unsigned long from, unsigned long to, int type) { if (from > to) __testlib_fail("random_t::wnext(unsigned long from, unsigned long to, int type): from can't not exceed to"); return wnext(to - from + 1, type) + from; } /* Returns weighted random double value in range [from, to). */ double wnext(double from, double to, int type) { if (from >= to) __testlib_fail("random_t::wnext(double from, double to, int type): from should be strictly less than to"); return wnext(to - from, type) + from; } /* Returns weighted random element from container. */ template<typename Container> typename Container::value_type wany(const Container &c, int type) { int size = int(c.size()); if (size <= 0) __testlib_fail("random_t::wany(const Container& c, int type): c.size() must be positive"); typename Container::const_iterator it = c.begin(); std::advance(it, wnext(size, type)); return *it; } /* Returns weighted random element from iterator range. */ template<typename Iter> typename Iter::value_type wany(const Iter &begin, const Iter &end, int type) { int size = static_cast<int>(std::distance(begin, end)); if (size <= 0) __testlib_fail( "random_t::any(const Iter& begin, const Iter& end, int type): range must have positive length"); Iter it = begin; std::advance(it, wnext(size, type)); return *it; } /* Returns random permutation of the given size (values are between 'first' and 'first'+size-1)*/ template<typename T, typename E> std::vector<E> perm(T size, E first) { if (size < 0) __testlib_fail("random_t::perm(T size, E first = 0): size must non-negative"); else if (size == 0) return std::vector<E>(); std::vector<E> p(size); E current = first; for (T i = 0; i < size; i++) p[i] = current++; if (size > 1) for (T i = 1; i < size; i++) std::swap(p[i], p[next(i + 1)]); return p; } /* Returns random permutation of the given size (values are between 0 and size-1)*/ template<typename T> std::vector<T> perm(T size) { return perm(size, T(0)); } /* Returns 'size' unordered (unsorted) distinct numbers between 'from' and 'to'. */ template<typename T> std::vector<T> distinct(int size, T from, T to) { std::vector<T> result; if (size == 0) return result; if (from > to) __testlib_fail("random_t::distinct expected from <= to"); if (size < 0) __testlib_fail("random_t::distinct expected size >= 0"); uint64_t n = to - from + 1; if (uint64_t(size) > n) __testlib_fail("random_t::distinct expected size <= to - from + 1"); double expected = 0.0; for (int i = 1; i <= size; i++) expected += double(n) / double(n - i + 1); if (expected < double(n)) { std::set<T> vals; while (int(vals.size()) < size) { T x = T(next(from, to)); if (vals.insert(x).second) result.push_back(x); } } else { if (n > 1000000000) __testlib_fail("random_t::distinct here expected to - from + 1 <= 1000000000"); std::vector<T> p(perm(int(n), from)); result.insert(result.end(), p.begin(), p.begin() + size); } return result; } /* Returns 'size' unordered (unsorted) distinct numbers between '0' and 'upper'-1. */ template<typename T> std::vector<T> distinct(int size, T upper) { if (size < 0) __testlib_fail("random_t::distinct expected size >= 0"); if (size == 0) return std::vector<T>(); if (upper <= 0) __testlib_fail("random_t::distinct expected upper > 0"); if (size > upper) __testlib_fail("random_t::distinct expected size <= upper"); return distinct(size, T(0), upper - 1); } /* Returns random (unsorted) partition which is a representation of sum as a sum of integers not less than min_part. */ template<typename T> std::vector<T> partition(int size, T sum, T min_part) { if (size < 0) __testlib_fail("random_t::partition: size < 0"); if (size == 0 && sum != 0) __testlib_fail("random_t::partition: size == 0 && sum != 0"); if (min_part * size > sum) __testlib_fail("random_t::partition: min_part * size > sum"); if (size == 0 && sum == 0) return std::vector<T>(); T sum_ = sum; sum -= min_part * size; std::vector<T> septums(size); std::vector<T> d = distinct(size - 1, T(1), T(sum + size - 1)); for (int i = 0; i + 1 < size; i++) septums[i + 1] = d[i]; sort(septums.begin(), septums.end()); std::vector<T> result(size); for (int i = 0; i + 1 < size; i++) result[i] = septums[i + 1] - septums[i] - 1; result[size - 1] = sum + size - 1 - septums.back(); for (std::size_t i = 0; i < result.size(); i++) result[i] += min_part; T result_sum = 0; for (std::size_t i = 0; i < result.size(); i++) result_sum += result[i]; if (result_sum != sum_) __testlib_fail("random_t::partition: partition sum is expected to be the given sum"); if (*std::min_element(result.begin(), result.end()) < min_part) __testlib_fail("random_t::partition: partition min is expected to be no less than the given min_part"); if (int(result.size()) != size || result.size() != (size_t) size) __testlib_fail("random_t::partition: partition size is expected to be equal to the given size"); return result; } /* Returns random (unsorted) partition which is a representation of sum as a sum of positive integers. */ template<typename T> std::vector<T> partition(int size, T sum) { return partition(size, sum, T(1)); } }; const int random_t::lim = 25; const unsigned long long random_t::multiplier = 0x5DEECE66DLL; const unsigned long long random_t::addend = 0xBLL; const unsigned long long random_t::mask = (1LL << 48) - 1; int random_t::version = -1; /* Pattern implementation */ bool pattern::matches(const std::string &s) const { return matches(s, 0); } static bool __pattern_isSlash(const std::string &s, size_t pos) { return s[pos] == '\\'; } #ifdef __GNUC__ __attribute__((pure)) #endif static bool __pattern_isCommandChar(const std::string &s, size_t pos, char value) { if (pos >= s.length()) return false; int slashes = 0; int before = int(pos) - 1; while (before >= 0 && s[before] == '\\') before--, slashes++; return slashes % 2 == 0 && s[pos] == value; } static char __pattern_getChar(const std::string &s, size_t &pos) { if (__pattern_isSlash(s, pos)) pos += 2; else pos++; return s[pos - 1]; } #ifdef __GNUC__ __attribute__((pure)) #endif static int __pattern_greedyMatch(const std::string &s, size_t pos, const std::vector<char> chars) { int result = 0; while (pos < s.length()) { char c = s[pos++]; if (!std::binary_search(chars.begin(), chars.end(), c)) break; else result++; } return result; } std::string pattern::src() const { return s; } bool pattern::matches(const std::string &s, size_t pos) const { std::string result; if (to > 0) { int size = __pattern_greedyMatch(s, pos, chars); if (size < from) return false; if (size > to) size = to; pos += size; } if (children.size() > 0) { for (size_t child = 0; child < children.size(); child++) if (children[child].matches(s, pos)) return true; return false; } else return pos == s.length(); } std::string pattern::next(random_t &rnd) const { std::string result; result.reserve(20); if (to == INT_MAX) __testlib_fail("pattern::next(random_t& rnd): can't process character '*' for generation"); if (to > 0) { int count = rnd.next(to - from + 1) + from; for (int i = 0; i < count; i++) result += chars[rnd.next(int(chars.size()))]; } if (children.size() > 0) { int child = rnd.next(int(children.size())); result += children[child].next(rnd); } return result; } static void __pattern_scanCounts(const std::string &s, size_t &pos, int &from, int &to) { if (pos >= s.length()) { from = to = 1; return; } if (__pattern_isCommandChar(s, pos, '{')) { std::vector<std::string> parts; std::string part; pos++; while (pos < s.length() && !__pattern_isCommandChar(s, pos, '}')) { if (__pattern_isCommandChar(s, pos, ',')) parts.push_back(part), part = "", pos++; else part += __pattern_getChar(s, pos); } if (part != "") parts.push_back(part); if (!__pattern_isCommandChar(s, pos, '}')) __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\""); pos++; if (parts.size() < 1 || parts.size() > 2) __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\""); std::vector<int> numbers; for (size_t i = 0; i < parts.size(); i++) { if (parts[i].length() == 0) __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\""); int number; if (std::sscanf(parts[i].c_str(), "%d", &number) != 1) __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\""); numbers.push_back(number); } if (numbers.size() == 1) from = to = numbers[0]; else from = numbers[0], to = numbers[1]; if (from > to) __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\""); } else { if (__pattern_isCommandChar(s, pos, '?')) { from = 0, to = 1, pos++; return; } if (__pattern_isCommandChar(s, pos, '*')) { from = 0, to = INT_MAX, pos++; return; } if (__pattern_isCommandChar(s, pos, '+')) { from = 1, to = INT_MAX, pos++; return; } from = to = 1; } } static std::vector<char> __pattern_scanCharSet(const std::string &s, size_t &pos) { if (pos >= s.length()) __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\""); std::vector<char> result; if (__patt