testlib.h 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559
  1. /*
  2. * It is strictly recommended to include "testlib.h" before any other include
  3. * in your code. In this case testlib overrides compiler specific "random()".
  4. *
  5. * If you can't compile your code and compiler outputs something about
  6. * ambiguous call of "random_shuffle", "rand" or "srand" it means that
  7. * you shouldn't use them. Use "shuffle", and "rnd.next()" instead of them
  8. * because these calls produce stable result for any C++ compiler. Read
  9. * sample generator sources for clarification.
  10. *
  11. * Please read the documentation for class "random_t" and use "rnd" instance in
  12. * generators. Probably, these sample calls will be usefull for you:
  13. * rnd.next(); rnd.next(100); rnd.next(1, 2);
  14. * rnd.next(3.14); rnd.next("[a-z]{1,100}").
  15. *
  16. * Also read about wnext() to generate off-center random distribution.
  17. *
  18. * See http://code.google.com/p/testlib/ to get latest version or bug tracker.
  19. */
  20. #ifndef _TESTLIB_H_
  21. #define _TESTLIB_H_
  22. /*
  23. * Copyright (c) 2005-2012
  24. */
  25. #define VERSION "0.8.2-SNAPSHOT"
  26. /*
  27. * Mike Mirzayanov
  28. *
  29. * This material is provided "as is", with absolutely no warranty expressed
  30. * or implied. Any use is at your own risk.
  31. *
  32. * Permission to use or copy this software for any purpose is hereby granted
  33. * without fee, provided the above notices are retained on all copies.
  34. * Permission to modify the code and to distribute modified code is granted,
  35. * provided the above notices are retained, and a notice that the code was
  36. * modified is included with the above copyright notice.
  37. *
  38. */
  39. /* NOTE: This file contains testlib library for C++.
  40. *
  41. * Check, using testlib running format:
  42. * check.exe <Input_File> <Output_File> <Answer_File> [<Result_File> [-appes]],
  43. * If result file is specified it will contain results.
  44. *
  45. * Validator, using testlib running format:
  46. * validator.exe < input.txt,
  47. * It will return non-zero exit code and writes message to standard output.
  48. *
  49. * Generator, using testlib running format:
  50. * gen.exe [parameter-1] [parameter-2] [... paramerter-n]
  51. * You can write generated test(s) into standard output or into the file(s).
  52. *
  53. * Interactor, using testlib running format:
  54. * interactor.exe <Input_File> <Output_File> [<Answer_File> [<Result_File> [-appes]]],
  55. * Reads test from inf (mapped to args[1]), writes result to tout (mapped to argv[2],
  56. * can be judged by checker later), reads program output from ouf (mapped to stdin),
  57. * writes output to program via stdout (use cout, printf, etc).
  58. */
  59. const char* latestFeatures[] = {
  60. "Introduced quitif(bool, const char* pattern, ...) which delegates to quitf() in case of first argument is true",
  61. "Introduced guard against missed quitf() in checker or readEof() in validators",
  62. "Supported readStrictReal/readStrictDouble - to use in validators to check strictly float numbers",
  63. "Supported registerInteraction(argc, argv)",
  64. "Print checker message to the stderr instead of stdout",
  65. "Supported TResult _points to output calculated score, use quitp(...) functions",
  66. "Fixed to be compilable on Mac",
  67. "PC_BASE_EXIT_CODE=50 in case of defined TESTSYS",
  68. "Fixed issues 19-21, added __attribute__ format printf",
  69. "Some bug fixes",
  70. "ouf.readInt(1, 100) and similar calls return WA",
  71. "Modified random_t to avoid integer overflow",
  72. "Truncated checker output [patch by Stepan Gatilov]",
  73. "Renamed class random -> class random_t",
  74. "Supported name parameter for read-and-validation methods, like readInt(1, 2, \"n\")",
  75. "Fixed bug in readDouble()",
  76. "Improved ensuref(), fixed nextLine to work in case of EOF, added startTest()",
  77. "Supported \"partially correct\", example: quitf(_pc(13), \"result=%d\", result)",
  78. "Added shuffle(begin, end), use it instead of random_shuffle(begin, end)",
  79. "Added readLine(const string& ptrn), fixed the logic of readLine() in the validation mode",
  80. "Package extended with samples of generators and validators",
  81. "Written the documentation for classes and public methods in testlib.h",
  82. "Implemented random routine to support generators, use registerGen() to switch it on",
  83. "Implemented strict mode to validate tests, use registerValidation() to switch it on",
  84. "Now ncmp.cpp and wcmp.cpp are return WA if answer is suffix or prefix of the output",
  85. "Added InStream::readLong() and removed InStream::readLongint()",
  86. "Now no footer added to each report by default (use directive FOOTER to switch on)",
  87. "Now every checker has a name, use setName(const char* format, ...) to set it",
  88. "Now it is compatible with TTS (by Kittens Computing)",
  89. "Added \'ensure(condition, message = \"\")\' feature, it works like assert()",
  90. "Fixed compatibility with MS C++ 7.1",
  91. "Added footer with exit code information",
  92. "Added compatibility with EJUDGE (compile with EJUDGE directive)"
  93. };
  94. #ifdef _MSC_VER
  95. #define _CRT_SECURE_NO_DEPRECATE
  96. #define _CRT_SECURE_NO_WARNINGS
  97. #endif
  98. /* Overrides random() for Borland C++. */
  99. #define random __random_deprecated
  100. #include <stdlib.h>
  101. #include <cstdlib>
  102. #include <climits>
  103. #include <algorithm>
  104. #undef random
  105. #include <cstdio>
  106. #include <cctype>
  107. #include <string>
  108. #include <vector>
  109. #include <cmath>
  110. #include <sstream>
  111. #include <fstream>
  112. #include <cstring>
  113. #include <stdarg.h>
  114. #include <fcntl.h>
  115. #if ( _WIN32 || __WIN32__ || _WIN64 || __WIN64__ )
  116. #include <windows.h>
  117. #include <io.h>
  118. #define ON_WINDOWS
  119. #else
  120. #define WORD unsigned short
  121. #endif
  122. #ifndef LLONG_MIN
  123. #define LLONG_MIN (-9223372036854775807LL - 1)
  124. #endif
  125. #define MAX_FORMAT_BUFFER_SIZE (8388608)
  126. #define LF ((char)10)
  127. #define CR ((char)13)
  128. #define TAB ((char)9)
  129. #define SPACE ((char)' ')
  130. #define EOFC ((char)26)
  131. #ifndef EJUDGE
  132. #define OK_EXIT_CODE 0
  133. #define WA_EXIT_CODE 1
  134. #define PE_EXIT_CODE 2
  135. #define FAIL_EXIT_CODE 3
  136. #define DIRT_EXIT_CODE 4
  137. #define POINTS_EXIT_CODE 7
  138. #define PC_BASE_EXIT_CODE 0
  139. #else
  140. #define OK_EXIT_CODE 0
  141. #define WA_EXIT_CODE 5
  142. #define PE_EXIT_CODE 4
  143. #define FAIL_EXIT_CODE 6
  144. #define DIRT_EXIT_CODE 6
  145. #define POINTS_EXIT_CODE 7
  146. #define PC_BASE_EXIT_CODE 0
  147. #endif
  148. #ifdef TESTSYS
  149. #undef PC_BASE_EXIT_CODE
  150. #define PC_BASE_EXIT_CODE 50
  151. #endif
  152. #define __TESTLIB_STATIC_ASSERT(condition) typedef void* __testlib_static_assert_type[((condition) != 0) * 2 - 1];
  153. #ifdef ON_WINDOWS
  154. #define I64 "%I64d"
  155. #else
  156. #define I64 "%lld"
  157. #endif
  158. const long long __TESTLIB_LONGLONG_MAX = 9223372036854775807LL;
  159. template<typename T>
  160. static inline T __testlib_abs(const T& x)
  161. {
  162. return x > 0 ? x : -x;
  163. }
  164. template<typename T>
  165. static inline T __testlib_min(const T& a, const T& b)
  166. {
  167. return a < b ? a : b;
  168. }
  169. template<typename T>
  170. static inline T __testlib_max(const T& a, const T& b)
  171. {
  172. return a > b ? a : b;
  173. }
  174. static void __testlib_fail(const std::string& message);
  175. static void __testlib_set_binary(FILE* file)
  176. {
  177. #if !defined(unix) && !defined(__APPLE__)
  178. if (NULL != file)
  179. {
  180. #ifdef _MSC_VER
  181. _setmode(_fileno(file), O_BINARY);
  182. #else
  183. #ifdef fileno
  184. setmode(fileno(file), O_BINARY);
  185. #endif
  186. #endif
  187. }
  188. #endif
  189. }
  190. /*
  191. * Very simple regex-like pattern.
  192. * It used for two purposes: validation and generation.
  193. *
  194. * For example, pattern("[a-z]{1,5}").next(rnd) will return
  195. * random string from lowercase latin letters with length
  196. * from 1 to 5. It is easier to call rnd.next("[a-z]{1,5}")
  197. * for the same effect.
  198. *
  199. * Another samples:
  200. * "mike|john" will generate (match) "mike" or "john";
  201. * "-?[1-9][0-9]{0,3}" will generate (match) non-zero integers from -9999 to 9999;
  202. * "id-([ac]|b{2})" will generate (match) "id-a", "id-bb", "id-c";
  203. * "[^0-9]*" will match sequences (empty or non-empty) without digits, you can't
  204. * use it for generations.
  205. *
  206. * You can't use pattern for generation if it contains meta-symbol '*'. Also it
  207. * is not recommended to use it for char-sets with meta-symbol '^' like [^a-z].
  208. *
  209. * For matching very simple greedy algorithm is used. For example, pattern
  210. * "[0-9]?1" will not match "1", because of greedy nature of matching.
  211. * Alternations (meta-symbols "|") are processed with brute-force algorithm, so
  212. * do not use many alternations in one expression.
  213. *
  214. * If you want to use one expression many times it is better to compile it into
  215. * a single pattern like "pattern p("[a-z]+")". Later you can use
  216. * "p.matches(std::string s)" or "p.next(random_t& rd)" to check matching or generate
  217. * new string by pattern.
  218. *
  219. * Simpler way to read token and check it for pattern matching is "inf.readToken("[a-z]+")".
  220. */
  221. class random_t;
  222. class pattern
  223. {
  224. public:
  225. /* Create pattern instance by string. */
  226. pattern(std::string s);
  227. /* Generate new string by pattern and given random_t. */
  228. std::string next(random_t& rnd) const;
  229. /* Checks if given string match the pattern. */
  230. bool matches(const std::string& s) const;
  231. private:
  232. bool matches(const std::string& s, size_t pos) const;
  233. std::vector<pattern> children;
  234. std::vector<char> chars;
  235. int from;
  236. int to;
  237. };
  238. /*
  239. * Use random_t instances to generate random values. It is preffered
  240. * way to use randoms instead of rand() function or self-written
  241. * randoms.
  242. *
  243. * Testlib defines global variable "rnd" of random_t class.
  244. * Use registerGen(argc, argv) to setup random_t seed be command
  245. * line.
  246. *
  247. * Random generates uniformly distributed values if another strategy is
  248. * not specified explicitly.
  249. */
  250. class random_t
  251. {
  252. private:
  253. long long seed;
  254. static const long long multiplier;
  255. static const long long addend;
  256. static const long long mask;
  257. static const int lim;
  258. long long nextBits(int bits)
  259. {
  260. if (bits <= 48)
  261. {
  262. seed = (seed * multiplier + addend) & mask;
  263. return (long long)(seed >> (48 - bits));
  264. }
  265. else
  266. {
  267. if (bits > 63)
  268. __testlib_fail("random_t::nextBits(int bits): n must be less than 64");
  269. return ((nextBits(31) << 32) ^ nextBits(31));
  270. }
  271. }
  272. public:
  273. /* New random_t with fixed seed. */
  274. random_t()
  275. : seed(3905348978240129619LL)
  276. {
  277. }
  278. /* Sets seed by command line. */
  279. void setSeed(int argc, char* argv[])
  280. {
  281. random_t p;
  282. seed = 3905348978240129619LL;
  283. for (int i = 1; i < argc; i++)
  284. {
  285. std::size_t le = std::strlen(argv[i]);
  286. for (std::size_t j = 0; j < le; j++)
  287. seed = seed * multiplier + (unsigned int)(argv[i][j]) + addend;
  288. seed += multiplier / addend;
  289. }
  290. seed = seed & mask;
  291. }
  292. /* Sets seed by given value. */
  293. void setSeed(long long _seed)
  294. {
  295. _seed = (_seed ^ multiplier) & mask;
  296. seed = _seed;
  297. }
  298. /* Random value in range [0, n-1]. */
  299. int next(int n)
  300. {
  301. if (n <= 0)
  302. __testlib_fail("random_t::next(int n): n must be positive");
  303. if ((n & -n) == n) // n is a power of 2
  304. return (int)((n * (long long)nextBits(31)) >> 31);
  305. const long long limit = INT_MAX / n * n;
  306. long long bits;
  307. do {
  308. bits = nextBits(31);
  309. } while (bits >= limit);
  310. return int(bits % n);
  311. }
  312. /* Random value in range [0, n-1]. */
  313. int next(unsigned int n)
  314. {
  315. if (n >= INT_MAX)
  316. __testlib_fail("random_t::next(unsigned int n): n must be less INT_MAX");
  317. return next(int(n));
  318. }
  319. /* Random value in range [0, n-1]. */
  320. long long next(long long n)
  321. {
  322. if (n <= 0)
  323. __testlib_fail("random_t::next(long long n): n must be positive");
  324. const long long limit = __TESTLIB_LONGLONG_MAX / n * n;
  325. long long bits;
  326. do {
  327. bits = nextBits(63);
  328. } while (bits >= limit);
  329. return bits % n;
  330. }
  331. /* Random value in range [0, n-1]. */
  332. unsigned long long next(unsigned long long n)
  333. {
  334. if (n >= (unsigned long long)(__TESTLIB_LONGLONG_MAX))
  335. __testlib_fail("random_t::next(unsigned long long n): n must be less LONGLONG_MAX");
  336. return (unsigned long long)next((long long)(n));
  337. }
  338. /* Returns random value in range [from,to]. */
  339. int next(int from, int to)
  340. {
  341. return int(next((long long)to - from + 1) + from);
  342. }
  343. /* Returns random value in range [from,to]. */
  344. unsigned int next(unsigned int from, unsigned int to)
  345. {
  346. return (unsigned int)(next((long long)to - from + 1) + from);
  347. }
  348. /* Returns random value in range [from,to]. */
  349. long long next(long long from, long long to)
  350. {
  351. return next(to - from + 1) + from;
  352. }
  353. /* Random double value in range [0, 1). */
  354. double next()
  355. {
  356. return (((long long)(nextBits(26)) << 27) + nextBits(27)) / (double)(1LL << 53);
  357. }
  358. /* Random double value in range [0, n). */
  359. double next(double n)
  360. {
  361. return n * next();
  362. }
  363. /* Random double value in range [from, to). */
  364. double next(double from, double to)
  365. {
  366. return next(to - from) + from;
  367. }
  368. /* Random string value by given pattern (see pattern documentation). */
  369. std::string next(const std::string& ptrn)
  370. {
  371. pattern p(ptrn);
  372. return p.next(*this);
  373. }
  374. /* Returns random element from container. */
  375. template <typename Container>
  376. typename Container::value_type any(const Container& c)
  377. {
  378. size_t size = c.size();
  379. if (size <= 0)
  380. __testlib_fail("random_t::any(const Container& c): c.size() must be positive");
  381. return *(c.begin() + next(size));
  382. }
  383. /* Returns random element from iterator range. */
  384. template <typename Iter>
  385. typename Iter::value_type any(const Iter& begin, const Iter& end)
  386. {
  387. int size = int(end - begin);
  388. if (size <= 0)
  389. __testlib_fail("random_t::any(const Iter& begin, const Iter& end): range must have positive length");
  390. return *(begin + next(size));
  391. }
  392. /* Random string value by given pattern (see pattern documentation). */
  393. #ifdef __GNUC__
  394. __attribute__ ((format (printf, 2, 3)))
  395. #endif
  396. std::string next(const char* format, ...)
  397. {
  398. char* buffer = new char [MAX_FORMAT_BUFFER_SIZE];
  399. va_list ap;
  400. va_start(ap, format);
  401. std::vsprintf(buffer, format, ap);
  402. va_end(ap);
  403. std::string ptrn(buffer);
  404. delete[] buffer;
  405. return next(ptrn);
  406. }
  407. /*
  408. * Weighted next. If type == 0 than it is usual "next()".
  409. *
  410. * If type = 1, than it returns "max(next(), next())"
  411. * (the number of "max" functions equals to "type").
  412. *
  413. * If type < 0, than "max" function replaces with "min".
  414. */
  415. int wnext(int n, int type)
  416. {
  417. if (n <= 0)
  418. __testlib_fail("random_t::wnext(int n, int type): n must be positive");
  419. if (abs(type) < random_t::lim)
  420. {
  421. int result = next(n);
  422. for (int i = 0; i < +type; i++)
  423. result = __testlib_max(result, next(n));
  424. for (int i = 0; i < -type; i++)
  425. result = __testlib_min(result, next(n));
  426. return result;
  427. }
  428. else
  429. {
  430. double p;
  431. if (type > 0)
  432. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  433. else
  434. p = 1 - std::pow(next() + 0.0, 1.0 / (-type + 1));
  435. return int(n * p);
  436. }
  437. }
  438. /* See wnext(int, int). It uses the same algorithms. */
  439. int wnext(unsigned int n, int type)
  440. {
  441. if (n >= INT_MAX)
  442. __testlib_fail("random_t::wnext(unsigned int n, int type): n must be less INT_MAX");
  443. return wnext(int(n), type);
  444. }
  445. /* See wnext(int, int). It uses the same algorithms. */
  446. long long wnext(long long n, int type)
  447. {
  448. if (n <= 0)
  449. __testlib_fail("random_t::wnext(long long n, int type): n must be positive");
  450. if (abs(type) < random_t::lim)
  451. {
  452. long long result = next(n);
  453. for (int i = 0; i < +type; i++)
  454. result = __testlib_max(result, next(n));
  455. for (int i = 0; i < -type; i++)
  456. result = __testlib_min(result, next(n));
  457. return result;
  458. }
  459. else
  460. {
  461. double p;
  462. if (type > 0)
  463. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  464. else
  465. p = std::pow(next() + 0.0, - type + 1);
  466. return (long long)(n * p);
  467. }
  468. }
  469. /* See wnext(int, int). It uses the same algorithms. */
  470. double wnext(int type)
  471. {
  472. if (abs(type) < random_t::lim)
  473. {
  474. double result = next();
  475. for (int i = 0; i < +type; i++)
  476. result = __testlib_max(result, next());
  477. for (int i = 0; i < -type; i++)
  478. result = __testlib_min(result, next());
  479. return result;
  480. }
  481. else
  482. {
  483. double p;
  484. if (type > 0)
  485. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  486. else
  487. p = std::pow(next() + 0.0, - type + 1);
  488. return p;
  489. }
  490. }
  491. /* See wnext(int, int). It uses the same algorithms. */
  492. double wnext(double n, int type)
  493. {
  494. if (n <= 0)
  495. __testlib_fail("random_t::wnext(double n, int type): n must be positive");
  496. if (abs(type) < random_t::lim)
  497. {
  498. double result = next();
  499. for (int i = 0; i < +type; i++)
  500. result = __testlib_max(result, next());
  501. for (int i = 0; i < -type; i++)
  502. result = __testlib_min(result, next());
  503. return n * result;
  504. }
  505. else
  506. {
  507. double p;
  508. if (type > 0)
  509. p = std::pow(next() + 0.0, 1.0 / (type + 1));
  510. else
  511. p = std::pow(next() + 0.0, - type + 1);
  512. return n * p;
  513. }
  514. }
  515. /* Returns weighted random value in range [from, to]. */
  516. int wnext(int from, int to, int type)
  517. {
  518. return wnext(to - from + 1, type) + from;
  519. }
  520. /* Returns weighted random value in range [from, to]. */
  521. int wnext(unsigned int from, unsigned int to, int type)
  522. {
  523. return wnext(to - from + 1, type) + from;
  524. }
  525. /* Returns weighted random value in range [from, to]. */
  526. long long wnext(long long from, long long to, int type)
  527. {
  528. return wnext(to - from + 1, type) + from;
  529. }
  530. /* Returns weighted random double value in range [from, to). */
  531. double wnext(double from, double to, int type)
  532. {
  533. return wnext(to - from, type) + from;
  534. }
  535. /* Returns weighted random element from container. */
  536. template <typename Container>
  537. typename Container::value_type wany(const Container& c, int type)
  538. {
  539. size_t size = c.size();
  540. if (size <= 0)
  541. __testlib_fail("random_t::wany(const Container& c, int type): c.size() must be positive");
  542. return *(c.begin() + wnext(size, type));
  543. }
  544. /* Returns weighted random element from iterator range. */
  545. template <typename Iter>
  546. typename Iter::value_type wany(const Iter& begin, const Iter& end, int type)
  547. {
  548. int size = int(end - begin);
  549. if (size <= 0)
  550. __testlib_fail("random_t::any(const Iter& begin, const Iter& end, int type): range must have positive length");
  551. return *(begin + wnext(size, type));
  552. }
  553. };
  554. const int random_t::lim = 25;
  555. const long long random_t::multiplier = 0x5DEECE66DLL;
  556. const long long random_t::addend = 0xBLL;
  557. const long long random_t::mask = (1LL << 48) - 1;
  558. /* Pattern implementation */
  559. bool pattern::matches(const std::string& s) const
  560. {
  561. return matches(s, 0);
  562. }
  563. static bool __pattern_isSlash(const std::string& s, size_t pos)
  564. {
  565. return s[pos] == '\\';
  566. }
  567. static bool __pattern_isCommandChar(const std::string& s, size_t pos, char value)
  568. {
  569. if (pos >= s.length())
  570. return false;
  571. int slashes = 0;
  572. int before = pos - 1;
  573. while (before >= 0 && s[before] == '\\')
  574. before--, slashes++;
  575. return slashes % 2 == 0 && s[pos] == value;
  576. }
  577. static char __pattern_getChar(const std::string& s, size_t& pos)
  578. {
  579. if (__pattern_isSlash(s, pos))
  580. pos += 2;
  581. else
  582. pos++;
  583. return s[pos - 1];
  584. }
  585. static int __pattern_greedyMatch(const std::string& s, size_t pos, const std::vector<char> chars)
  586. {
  587. int result = 0;
  588. while (pos < s.length())
  589. {
  590. char c = s[pos++];
  591. if (!std::binary_search(chars.begin(), chars.end(), c))
  592. break;
  593. else
  594. result++;
  595. }
  596. return result;
  597. }
  598. bool pattern::matches(const std::string& s, size_t pos) const
  599. {
  600. std::string result;
  601. if (to > 0)
  602. {
  603. int size = __pattern_greedyMatch(s, pos, chars);
  604. if (size < from)
  605. return false;
  606. if (size > to)
  607. size = to;
  608. pos += size;
  609. }
  610. if (children.size() > 0)
  611. {
  612. for (size_t child = 0; child < children.size(); child++)
  613. if (children[child].matches(s, pos))
  614. return true;
  615. return false;
  616. }
  617. else
  618. return pos == s.length();
  619. }
  620. std::string pattern::next(random_t& rnd) const
  621. {
  622. std::string result;
  623. if (to == INT_MAX)
  624. __testlib_fail("pattern::next(random_t& rnd): can't process character '*' for generation");
  625. if (to > 0)
  626. {
  627. int count = rnd.next(to - from + 1) + from;
  628. for (int i = 0; i < count; i++)
  629. result += chars[rnd.next(int(chars.size()))];
  630. }
  631. if (children.size() > 0)
  632. {
  633. int child = rnd.next(int(children.size()));
  634. result += children[child].next(rnd);
  635. }
  636. return result;
  637. }
  638. static void __pattern_scanCounts(const std::string& s, size_t& pos, int& from, int& to)
  639. {
  640. if (pos >= s.length())
  641. {
  642. from = to = 1;
  643. return;
  644. }
  645. if (__pattern_isCommandChar(s, pos, '{'))
  646. {
  647. std::vector<std::string> parts;
  648. std::string part;
  649. pos++;
  650. while (pos < s.length() && !__pattern_isCommandChar(s, pos, '}'))
  651. {
  652. if (__pattern_isCommandChar(s, pos, ','))
  653. parts.push_back(part), part = "", pos++;
  654. else
  655. part += __pattern_getChar(s, pos);
  656. }
  657. if (part != "")
  658. parts.push_back(part);
  659. if (!__pattern_isCommandChar(s, pos, '}'))
  660. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  661. pos++;
  662. if (parts.size() < 1 || parts.size() > 2)
  663. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  664. std::vector<int> numbers;
  665. for (size_t i = 0; i < parts.size(); i++)
  666. {
  667. if (parts[i].length() == 0)
  668. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  669. int number;
  670. if (std::sscanf(parts[i].c_str(), "%d", &number) != 1)
  671. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  672. numbers.push_back(number);
  673. }
  674. if (numbers.size() == 1)
  675. from = to = numbers[0];
  676. else
  677. from = numbers[0], to = numbers[1];
  678. if (from > to)
  679. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  680. }
  681. else
  682. {
  683. if (__pattern_isCommandChar(s, pos, '?'))
  684. {
  685. from = 0, to = 1, pos++;
  686. return;
  687. }
  688. if (__pattern_isCommandChar(s, pos, '*'))
  689. {
  690. from = 0, to = INT_MAX, pos++;
  691. return;
  692. }
  693. if (__pattern_isCommandChar(s, pos, '+'))
  694. {
  695. from = 1, to = INT_MAX, pos++;
  696. return;
  697. }
  698. from = to = 1;
  699. }
  700. }
  701. static std::vector<char> __pattern_scanCharSet(const std::string& s, size_t& pos)
  702. {
  703. if (pos >= s.length())
  704. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  705. std::vector<char> result;
  706. if (__pattern_isCommandChar(s, pos, '['))
  707. {
  708. pos++;
  709. bool negative = __pattern_isCommandChar(s, pos, '^');
  710. char prev = 0;
  711. while (pos < s.length() && !__pattern_isCommandChar(s, pos, ']'))
  712. {
  713. if (__pattern_isCommandChar(s, pos, '-') && prev != 0)
  714. {
  715. pos++;
  716. if (pos + 1 == s.length())
  717. {
  718. result.push_back(prev);
  719. prev = '-';
  720. continue;
  721. }
  722. char next = __pattern_getChar(s, pos);
  723. if (prev > next)
  724. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  725. for (char c = prev; c != next; c++)
  726. result.push_back(c);
  727. result.push_back(next);
  728. prev = 0;
  729. }
  730. else
  731. {
  732. if (prev != 0)
  733. result.push_back(prev);
  734. prev = __pattern_getChar(s, pos);
  735. }
  736. }
  737. if (prev != 0)
  738. result.push_back(prev);
  739. if (!__pattern_isCommandChar(s, pos, ']'))
  740. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  741. pos++;
  742. if (negative)
  743. {
  744. std::sort(result.begin(), result.end());
  745. std::vector<char> actuals;
  746. for (int code = 0; code < 255; code++)
  747. {
  748. char c = char(code);
  749. if (!std::binary_search(result.begin(), result.end(), c))
  750. actuals.push_back(c);
  751. }
  752. result = actuals;
  753. }
  754. std::sort(result.begin(), result.end());
  755. }
  756. else
  757. result.push_back(__pattern_getChar(s, pos));
  758. return result;
  759. }
  760. pattern::pattern(std::string s): from(0), to(0)
  761. {
  762. std::string t;
  763. for (size_t i = 0; i < s.length(); i++)
  764. if (!__pattern_isCommandChar(s, i, ' '))
  765. t += s[i];
  766. s = t;
  767. int opened = 0;
  768. int firstClose = -1;
  769. std::vector<int> seps;
  770. for (size_t i = 0; i < s.length(); i++)
  771. {
  772. if (__pattern_isCommandChar(s, i, '('))
  773. {
  774. opened++;
  775. continue;
  776. }
  777. if (__pattern_isCommandChar(s, i, ')'))
  778. {
  779. opened--;
  780. if (opened == 0 && firstClose == -1)
  781. firstClose = i;
  782. continue;
  783. }
  784. if (opened < 0)
  785. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  786. if (__pattern_isCommandChar(s, i, '|') && opened == 0)
  787. seps.push_back(i);
  788. }
  789. if (opened != 0)
  790. __testlib_fail("pattern: Illegal pattern (or part) \"" + s + "\"");
  791. if (seps.size() == 0 && firstClose + 1 == (int)s.length()
  792. && __pattern_isCommandChar(s, 0, '(') && __pattern_isCommandChar(s, s.length() - 1, ')'))
  793. {
  794. children.push_back(pattern(s.substr(1, s.length() - 2)));
  795. }
  796. else
  797. {
  798. if (seps.size() > 0)
  799. {
  800. seps.push_back(s.length());
  801. int last = 0;
  802. for (size_t i = 0; i < seps.size(); i++)
  803. {
  804. children.push_back(pattern(s.substr(last, seps[i] - last)));
  805. last = seps[i] + 1;
  806. }
  807. }
  808. else
  809. {
  810. size_t pos = 0;
  811. chars = __pattern_scanCharSet(s, pos);
  812. __pattern_scanCounts(s, pos, from, to);
  813. if (pos < s.length())
  814. children.push_back(pattern(s.substr(pos)));
  815. }
  816. }
  817. }
  818. /* End of pattern implementation */
  819. inline bool isEof(char c)
  820. {
  821. return (c == EOF || c == EOFC);
  822. }
  823. inline bool isEoln(char c)
  824. {
  825. return (c == LF || c == CR);
  826. }
  827. inline bool isBlanks(char c)
  828. {
  829. return (c == LF || c == CR || c == SPACE || c == TAB);
  830. }
  831. enum TMode
  832. {
  833. _input, _output, _answer
  834. };
  835. enum TResult
  836. {
  837. _ok, _wa, _pe, _fail, _dirt, _partially, _points
  838. };
  839. enum TTestlibMode
  840. {
  841. _unknown, _checker, _validator, _generator, _interactor
  842. };
  843. #define _pc(exitCode) (TResult(_partially + (exitCode)))
  844. const std::string outcomes[] =
  845. {"accepted", "wrong-answer", "presentation-error", "fail", "fail", "partially-correct", "points"};
  846. /*
  847. * Streams to be used for reading data in checkers or validators.
  848. * Each read*() method moves pointer to the next character after the
  849. * read value.
  850. */
  851. struct InStream
  852. {
  853. /* Do not use it. */
  854. InStream();
  855. std::FILE * file;
  856. std::string name;
  857. TMode mode;
  858. bool opened;
  859. bool stdfile;
  860. bool strict;
  861. void init(std::string fileName, TMode mode);
  862. void init(std::FILE* f, TMode mode);
  863. /* Moves stream pointer to the first non-white-space character or EOF. */
  864. void skipBlanks();
  865. /* Returns current character in the stream. Doesn't remove it from stream. */
  866. char curChar();
  867. /* Moves stream pointer one character forward. */
  868. void skipChar();
  869. /* Returns current character and moves pointer one character forward. */
  870. char nextChar();
  871. /* Returns current character and moves pointer one character forward. */
  872. char readChar();
  873. /* As "readChar()" but ensures that the result is equal to given parameter. */
  874. char readChar(char c);
  875. /* As "readChar()" but ensures that the result is equal to the space (code=32). */
  876. char readSpace();
  877. /* Puts back the character into the stream. */
  878. void unreadChar(char c);
  879. /* Reopens stream, you should not use it. */
  880. void reset();
  881. /* Checks that current position is EOF. If not it doesn't move stream pointer. */
  882. bool eof();
  883. /* Moves pointer to the first non-white-space character and calls "eof()". */
  884. bool seekEof();
  885. /*
  886. * Checks that current position contains EOLN.
  887. * If not it doesn't move stream pointer.
  888. * In strict mode expects "#13#10" for windows or "#10" for other platforms.
  889. */
  890. bool eoln();
  891. /* Moves pointer to the first non-space and non-tab character and calls "eoln()". */
  892. bool seekEoln();
  893. /* Moves stream pointer to the first character of the next line (if exists). */
  894. void nextLine();
  895. /*
  896. * Reads new token. Ignores white-spaces into the non-strict mode
  897. * (strict mode is used in validators usually).
  898. */
  899. std::string readWord();
  900. /* The same as "readWord()", it is preffered to use "readToken()". */
  901. std::string readToken();
  902. /* The same as "readWord()", but ensures that token matches to given pattern. */
  903. std::string readWord(const std::string& ptrn, const std::string& variableName = "");
  904. /* The same as "readToken()", but ensures that token matches to given pattern. */
  905. std::string readToken(const std::string& ptrn, const std::string& variableName = "");
  906. /*
  907. * Reads new long long value. Ignores white-spaces into the non-strict mode
  908. * (strict mode is used in validators usually).
  909. */
  910. long long readLong();
  911. /*
  912. * Reads new int. Ignores white-spaces into the non-strict mode
  913. * (strict mode is used in validators usually).
  914. */
  915. int readInteger();
  916. /*
  917. * Reads new int. Ignores white-spaces into the non-strict mode
  918. * (strict mode is used in validators usually).
  919. */
  920. int readInt();
  921. /* As "readLong()" but ensures that value in the range [minv,maxv]. */
  922. long long readLong(long long minv, long long maxv, const std::string& variableName = "");
  923. /* As "readInteger()" but ensures that value in the range [minv,maxv]. */
  924. int readInteger(int minv, int maxv, const std::string& variableName = "");
  925. /* As "readInt()" but ensures that value in the range [minv,maxv]. */
  926. int readInt(int minv, int maxv, const std::string& variableName = "");
  927. /*
  928. * Reads new double. Ignores white-spaces into the non-strict mode
  929. * (strict mode is used in validators usually).
  930. */
  931. double readReal();
  932. /*
  933. * Reads new double. Ignores white-spaces into the non-strict mode
  934. * (strict mode is used in validators usually).
  935. */
  936. double readDouble();
  937. /* As "readReal()" but ensures that value in the range [minv,maxv]. */
  938. double readReal(double minv, double maxv, const std::string& variableName = "");
  939. /* As "readDouble()" but ensures that value in the range [minv,maxv]. */
  940. double readDouble(double minv, double maxv, const std::string& variableName = "");
  941. /*
  942. * As "readReal()" but ensures that value in the range [minv,maxv] and
  943. * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]
  944. * and number is in the form "[-]digit(s)[.digit(s)]".
  945. */
  946. double readStrictReal(double minv, double maxv,
  947. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  948. const std::string& variableName = "");
  949. /*
  950. * As "readDouble()" but ensures that value in the range [minv,maxv] and
  951. * number of digit after the decimal point is in range [minAfterPointDigitCount,maxAfterPointDigitCount]
  952. * and number is in the form "[-]digit(s)[.digit(s)]".
  953. */
  954. double readStrictDouble(double minv, double maxv,
  955. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  956. const std::string& variableName = "");
  957. /* As readLine(). */
  958. std::string readString();
  959. /*
  960. * Reads line from the current position to EOLN or EOF. Moves stream pointer to
  961. * the first character of the new line (if possible).
  962. */
  963. std::string readLine();
  964. /* The same as "readLine()", but ensures that line matches to the given pattern. */
  965. std::string readLine(const std::string& ptrn, const std::string& variableName = "");
  966. /* See readLine(const std::string& ptrn). */
  967. std::string readString(const std::string& ptrn, const std::string& variableName = "");
  968. /* Reads EOLN or fails. Use it in validators. Calls "eoln()" method internally. */
  969. void readEoln();
  970. /* Reads EOF or fails. Use it in validators. Calls "eof()" method internally. */
  971. void readEof();
  972. void quit(TResult result, const char* msg);
  973. void quits(TResult result, std::string msg);
  974. void close();
  975. const static WORD LightGray = 0x07;
  976. const static WORD LightRed = 0x0c;
  977. const static WORD LightCyan = 0x0b;
  978. const static WORD LightGreen = 0x0a;
  979. const static WORD LightYellow = 0x0e;
  980. static void textColor(WORD color);
  981. static void quitscr(WORD color, const char* msg);
  982. static void quitscrS(WORD color, std::string msg);
  983. void xmlSafeWrite(std::FILE * file, const char* msg);
  984. };
  985. InStream inf;
  986. InStream ouf;
  987. InStream ans;
  988. bool appesMode;
  989. std::string resultName;
  990. std::string checkerName = "untitled checker";
  991. random_t rnd;
  992. TTestlibMode testlibMode = _unknown;
  993. struct TestlibFinalizeGuard
  994. {
  995. static bool alive;
  996. int quitCount, readEofCount;
  997. TestlibFinalizeGuard() : quitCount(0), readEofCount(0)
  998. {
  999. // No operations.
  1000. }
  1001. ~TestlibFinalizeGuard()
  1002. {
  1003. bool _alive = alive;
  1004. alive = false;
  1005. if (_alive)
  1006. {
  1007. if (testlibMode == _checker && quitCount == 0)
  1008. {
  1009. __testlib_fail("Checker must end with quit or quitf call.");
  1010. }
  1011. if (testlibMode == _validator && readEofCount == 0 && quitCount == 0)
  1012. {
  1013. __testlib_fail("Validator must end with readEof call.");
  1014. }
  1015. }
  1016. }
  1017. };
  1018. bool TestlibFinalizeGuard::alive = true;
  1019. TestlibFinalizeGuard testlibFinalizeGuard;
  1020. /* Interactor streams.
  1021. */
  1022. std::fstream tout;
  1023. /* implementation
  1024. */
  1025. template <typename T>
  1026. static std::string vtos(const T& t)
  1027. {
  1028. std::string s;
  1029. std::stringstream ss;
  1030. ss << t;
  1031. ss >> s;
  1032. return s;
  1033. }
  1034. InStream::InStream()
  1035. {
  1036. file = NULL;
  1037. name = "";
  1038. mode = _input;
  1039. strict = false;
  1040. stdfile = false;
  1041. }
  1042. int resultExitCode(TResult r)
  1043. {
  1044. if (r == _ok)
  1045. return OK_EXIT_CODE;
  1046. if (r == _wa)
  1047. return WA_EXIT_CODE;
  1048. if (r == _pe)
  1049. return PE_EXIT_CODE;
  1050. if (r == _fail)
  1051. return FAIL_EXIT_CODE;
  1052. if (r == _dirt)
  1053. return DIRT_EXIT_CODE;
  1054. if (r == _points)
  1055. return POINTS_EXIT_CODE;
  1056. if (r >= _partially)
  1057. return PC_BASE_EXIT_CODE + (r - _partially);
  1058. return FAIL_EXIT_CODE;
  1059. }
  1060. void InStream::textColor(WORD color)
  1061. {
  1062. #ifdef ON_WINDOWS
  1063. HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
  1064. SetConsoleTextAttribute(handle, color);
  1065. #endif
  1066. }
  1067. void halt(int exitCode)
  1068. {
  1069. #ifdef FOOTER
  1070. InStream::textColor(InStream::LightGray);
  1071. std::fprintf(stderr, "Checker: \"%s\"\n", checkerName.c_str());
  1072. std::fprintf(stderr, "Exit code: %d\n", exitCode);
  1073. InStream::textColor(InStream::LightGray);
  1074. #endif
  1075. std::exit(exitCode);
  1076. }
  1077. void InStream::quit(TResult result, const char* msg)
  1078. {
  1079. if (TestlibFinalizeGuard::alive && (result != _ok || testlibMode != _validator))
  1080. testlibFinalizeGuard.quitCount++;
  1081. if (mode != _output && result != _fail)
  1082. quits(_fail, std::string(msg) + " (" + name + ")");
  1083. std::FILE * resultFile;
  1084. std::string errorName;
  1085. if (result == _ok)
  1086. {
  1087. if (testlibMode != _interactor && !ouf.seekEof())
  1088. quit(_dirt, "Extra information in the output file");
  1089. }
  1090. int pctype = result - _partially;
  1091. switch (result)
  1092. {
  1093. case _fail:
  1094. errorName = "FAIL ";
  1095. quitscrS(LightRed, errorName);
  1096. break;
  1097. case _dirt:
  1098. errorName = "wrong output format ";
  1099. quitscrS(LightCyan, errorName);
  1100. result = _pe;
  1101. break;
  1102. case _pe:
  1103. errorName = "wrong output format ";
  1104. quitscrS(LightRed, errorName);
  1105. break;
  1106. case _ok:
  1107. errorName = "ok ";
  1108. quitscrS(LightGreen, errorName);
  1109. break;
  1110. case _wa:
  1111. errorName = "wrong answer ";
  1112. quitscrS(LightRed, errorName);
  1113. break;
  1114. case _points:
  1115. errorName = "points ";
  1116. quitscrS(LightYellow, errorName);
  1117. break;
  1118. default:
  1119. if (result >= _partially)
  1120. {
  1121. char message[1023];
  1122. std::sprintf(message, "partially correct (%d) ", pctype);
  1123. errorName = std::string(message);
  1124. quitscrS(LightYellow, errorName);
  1125. }
  1126. else
  1127. quit(_fail, "What is the code ??? ");
  1128. }
  1129. if (resultName != "")
  1130. {
  1131. resultFile = std::fopen(resultName.c_str(), "w");
  1132. if (resultFile == NULL)
  1133. quit(_fail, "Can not write to Result file");
  1134. if (appesMode)
  1135. {
  1136. fprintf(resultFile, "<?xml version=\"1.0\" encoding=\"windows-1251\"?>");
  1137. if (result >= _partially)
  1138. fprintf(resultFile, "<result outcome = \"%s\" pctype = \"%d\">", outcomes[(int)_partially].c_str(), pctype);
  1139. else
  1140. fprintf(resultFile, "<result outcome = \"%s\">", outcomes[(int)result].c_str());
  1141. xmlSafeWrite(resultFile, msg);
  1142. fprintf(resultFile, "</result>\n");
  1143. }
  1144. else
  1145. fprintf(resultFile, "%s", msg);
  1146. if (NULL == resultFile || fclose(resultFile) != 0)
  1147. quit(_fail, "Can not write to Result file");
  1148. }
  1149. quitscr(LightGray, msg);
  1150. std::fprintf(stderr, "\n");
  1151. if (inf.file)
  1152. fclose(inf.file);
  1153. if (ouf.file)
  1154. fclose(ouf.file);
  1155. if (ans.file)
  1156. fclose(ans.file);
  1157. if (tout.is_open())
  1158. tout.close();
  1159. textColor(LightGray);
  1160. if (resultName != "")
  1161. std::fprintf(stderr, "See file to check exit message\n");
  1162. halt(resultExitCode(result));
  1163. }
  1164. void InStream::quits(TResult result, std::string msg)
  1165. {
  1166. InStream::quit(result, msg.c_str());
  1167. }
  1168. void InStream::xmlSafeWrite(std::FILE * file, const char* msg)
  1169. {
  1170. size_t lmsg = strlen(msg);
  1171. for (size_t i = 0; i < lmsg; i++)
  1172. {
  1173. if (msg[i] == '&')
  1174. {
  1175. fprintf(file, "%s", "&amp;");
  1176. continue;
  1177. }
  1178. if (msg[i] == '<')
  1179. {
  1180. fprintf(file, "%s", "&lt;");
  1181. continue;
  1182. }
  1183. if (msg[i] == '>')
  1184. {
  1185. fprintf(file, "%s", "&gt;");
  1186. continue;
  1187. }
  1188. if (msg[i] == '"')
  1189. {
  1190. fprintf(file, "%s", "&quot;");
  1191. continue;
  1192. }
  1193. if (0 <= msg[i] && msg[i] <= 31)
  1194. {
  1195. fprintf(file, "%c", '.');
  1196. continue;
  1197. }
  1198. fprintf(file, "%c", msg[i]);
  1199. }
  1200. }
  1201. void InStream::quitscrS(WORD color, std::string msg)
  1202. {
  1203. quitscr(color, msg.c_str());
  1204. }
  1205. void InStream::quitscr(WORD color, const char* msg)
  1206. {
  1207. if (resultName == "")
  1208. {
  1209. textColor(color);
  1210. std::fprintf(stderr, "%s", msg);
  1211. textColor(LightGray);
  1212. }
  1213. }
  1214. void InStream::reset()
  1215. {
  1216. if (opened && stdfile)
  1217. quit(_fail, "Can't reset standard handle");
  1218. if (opened)
  1219. close();
  1220. if (!stdfile)
  1221. if (NULL == (file = std::fopen(name.c_str(), "rb")))
  1222. {
  1223. if (mode == _output)
  1224. quits(_pe, std::string("File not found: \"") + name + "\"");
  1225. }
  1226. opened = true;
  1227. __testlib_set_binary(file);
  1228. }
  1229. void InStream::init(std::string fileName, TMode mode)
  1230. {
  1231. opened = false;
  1232. name = fileName;
  1233. stdfile = false;
  1234. this->mode = mode;
  1235. reset();
  1236. }
  1237. void InStream::init(std::FILE* f, TMode mode)
  1238. {
  1239. opened = false;
  1240. name = "untitled";
  1241. if (f == stdin)
  1242. name = "stdin", stdfile = true;
  1243. if (f == stdout)
  1244. name = "stdout", stdfile = true;
  1245. if (f == stderr)
  1246. name = "stderr", stdfile = true;
  1247. this->file = f;
  1248. this->mode = mode;
  1249. reset();
  1250. }
  1251. char InStream::curChar()
  1252. {
  1253. char c = (char)getc(file);
  1254. ungetc(c, file);
  1255. return c;
  1256. }
  1257. char InStream::nextChar()
  1258. {
  1259. return (char)getc(file);
  1260. }
  1261. char InStream::readChar()
  1262. {
  1263. return nextChar();
  1264. }
  1265. char InStream::readChar(char c)
  1266. {
  1267. char found = readChar();
  1268. if (c != found)
  1269. {
  1270. if (!isEoln(found))
  1271. quit(_pe, ("Unexpected character '" + std::string(1, found) + "', but '" + std::string(1, c) + "' expected").c_str());
  1272. else
  1273. quit(_pe, ("Unexpected character " + ("#" + vtos(int(found))) + ", but '" + std::string(1, c) + "' expected").c_str());
  1274. }
  1275. return found;
  1276. }
  1277. char InStream::readSpace()
  1278. {
  1279. return readChar(' ');
  1280. }
  1281. void InStream::unreadChar(char c)
  1282. {
  1283. ungetc(c, file);
  1284. }
  1285. void InStream::skipChar()
  1286. {
  1287. getc(file);
  1288. }
  1289. void InStream::skipBlanks()
  1290. {
  1291. char cur;
  1292. while (isBlanks(cur = readChar()));
  1293. unreadChar(cur);
  1294. }
  1295. std::string InStream::readWord()
  1296. {
  1297. if (!strict)
  1298. skipBlanks();
  1299. char cur = readChar();
  1300. if (isEof(cur))
  1301. quit(_pe, "Unexpected end of file - token expected");
  1302. if (isBlanks(cur))
  1303. quit(_pe, "Unexpected white-space - token expected");
  1304. std::string result = "";
  1305. while (!(isBlanks(cur) || cur == EOF))
  1306. {
  1307. result += cur;
  1308. cur = nextChar();
  1309. }
  1310. unreadChar(cur);
  1311. if (result.length() == 0)
  1312. quit(_pe, "Unexpected end of file or white-space - token expected");
  1313. return result;
  1314. }
  1315. std::string InStream::readToken()
  1316. {
  1317. return readWord();
  1318. }
  1319. static std::string __testlib_part(const std::string& s)
  1320. {
  1321. if (s.length() <= 64)
  1322. return s;
  1323. else
  1324. return s.substr(0, 30) + "..." + s.substr(s.length() - 31, 31);
  1325. }
  1326. std::string InStream::readWord(const std::string& ptrn, const std::string& variableName)
  1327. {
  1328. pattern p(ptrn);
  1329. std::string result = readWord();
  1330. if (!p.matches(result))
  1331. {
  1332. if (variableName.empty())
  1333. quit(_wa, ("Token \"" + __testlib_part(result) + "\" doesn't correspond to pattern \"" + ptrn + "\"").c_str());
  1334. else
  1335. quit(_wa, ("Token parameter [name=" + variableName + "] equals to \"" + __testlib_part(result) + "\", doesn't correspond to pattern \"" + ptrn + "\"").c_str());
  1336. }
  1337. return result;
  1338. }
  1339. std::string InStream::readToken(const std::string& ptrn, const std::string& variableName)
  1340. {
  1341. return readWord(ptrn, variableName);
  1342. }
  1343. static bool equals(long long integer, const char* s)
  1344. {
  1345. if (integer == LLONG_MIN)
  1346. return strcmp(s, "-9223372036854775808") == 0;
  1347. if (integer == 0LL)
  1348. return strcmp(s, "0") == 0;
  1349. size_t length = strlen(s);
  1350. if (length == 0)
  1351. return false;
  1352. if (integer < 0 && s[0] != '-')
  1353. return false;
  1354. if (integer < 0)
  1355. s++, length--, integer = -integer;
  1356. if (length == 0)
  1357. return false;
  1358. while (integer > 0)
  1359. {
  1360. int digit = int(integer % 10);
  1361. if (s[length - 1] != '0' + digit)
  1362. return false;
  1363. length--;
  1364. integer /= 10;
  1365. }
  1366. return length == 0;
  1367. }
  1368. static double stringToDouble(InStream& in, const char* buffer)
  1369. {
  1370. double retval;
  1371. size_t length = strlen(buffer);
  1372. for (size_t i = 0; i < length; i++)
  1373. if (isBlanks(buffer[i]))
  1374. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1375. char* suffix = new char[length + 1];
  1376. int scanned = std::sscanf(buffer, "%lf%s", &retval, suffix);
  1377. bool empty = strlen(suffix) == 0;
  1378. delete[] suffix;
  1379. if (scanned == 1 || (scanned == 2 && empty))
  1380. return retval;
  1381. else
  1382. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1383. __testlib_fail("Unexpected case in stringToDouble");
  1384. return retval;
  1385. }
  1386. static double stringToStrictDouble(InStream& in, const char* buffer, int minAfterPointDigitCount, int maxAfterPointDigitCount)
  1387. {
  1388. double retval;
  1389. size_t length = strlen(buffer);
  1390. if (length == 0 || length > 20)
  1391. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1392. if (buffer[0] != '-' && (buffer[0] < '0' || buffer[0] > '9'))
  1393. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1394. int pointPos = -1;
  1395. for (size_t i = 1; i + 1 < length; i++)
  1396. {
  1397. if (buffer[i] == '.')
  1398. {
  1399. if (pointPos > -1)
  1400. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1401. pointPos = i;
  1402. }
  1403. if (buffer[i] != '.' && (buffer[i] < '0' || buffer[i] > '9'))
  1404. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1405. }
  1406. if (buffer[length - 1] < '0' || buffer[length - 1] > '9')
  1407. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1408. int afterDigitsCount = (pointPos == -1 ? 0 : length - pointPos - 1);
  1409. if (afterDigitsCount < minAfterPointDigitCount || afterDigitsCount > maxAfterPointDigitCount)
  1410. in.quit(_pe, ("Expected strict double with number of digits after point in range ["
  1411. + vtos(minAfterPointDigitCount)
  1412. + ","
  1413. + vtos(maxAfterPointDigitCount)
  1414. + "], but \"" + __testlib_part(buffer) + "\" found").c_str()
  1415. );
  1416. int firstDigitPos = -1;
  1417. for (size_t i = 0; i < length; i++)
  1418. if (buffer[i] >= '0' && buffer[i] <= '9')
  1419. {
  1420. firstDigitPos = i;
  1421. break;
  1422. }
  1423. if (firstDigitPos > 1 || firstDigitPos == -1)
  1424. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1425. if (buffer[firstDigitPos] == '0' && firstDigitPos + 1 < int(length)
  1426. && buffer[firstDigitPos + 1] >= '0' && buffer[firstDigitPos + 1] <= '9')
  1427. in.quit(_pe, ("Expected strict double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1428. char* suffix = new char[length + 1];
  1429. int scanned = std::sscanf(buffer, "%lf%s", &retval, suffix);
  1430. bool empty = strlen(suffix) == 0;
  1431. delete[] suffix;
  1432. if (scanned == 1 || (scanned == 2 && empty))
  1433. return retval;
  1434. else
  1435. in.quit(_pe, ("Expected double, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1436. __testlib_fail("Unexpected case in stringToStrictDouble");
  1437. return retval;
  1438. }
  1439. static long long stringToLongLong(InStream& in, const char* buffer)
  1440. {
  1441. if (strcmp(buffer, "-9223372036854775808") == 0)
  1442. return LLONG_MIN;
  1443. bool minus = false;
  1444. size_t length = strlen(buffer);
  1445. if (length > 1 && buffer[0] == '-')
  1446. minus = true;
  1447. if (length > 20)
  1448. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1449. long long retval = 0LL;
  1450. int zeroes = 0;
  1451. int processingZeroes = true;
  1452. for (size_t i = (minus ? 1 : 0); i < length; i++)
  1453. {
  1454. if (buffer[i] == '0' && processingZeroes)
  1455. zeroes++;
  1456. else
  1457. processingZeroes = false;
  1458. if (buffer[i] < '0' || buffer[i] > '9')
  1459. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1460. retval = retval * 10 + (buffer[i] - '0');
  1461. }
  1462. if (retval < 0)
  1463. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1464. if ((zeroes > 0 && (retval != 0 || minus)) || zeroes > 1)
  1465. in.quit(_pe, ("Expected integer, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1466. retval = (minus ? -retval : +retval);
  1467. if (length < 19)
  1468. return retval;
  1469. if (equals(retval, buffer))
  1470. return retval;
  1471. else
  1472. in.quit(_pe, ("Expected int64, but \"" + __testlib_part(buffer) + "\" found").c_str());
  1473. __testlib_fail("Unexpected case in stringToLongLong");
  1474. return retval;
  1475. }
  1476. int InStream::readInteger()
  1477. {
  1478. if (!strict && seekEof())
  1479. quit(_pe, "Unexpected end of file - int32 expected");
  1480. std::string token = readWord();
  1481. long long value = stringToLongLong(*this, token.c_str());
  1482. if (value < INT_MIN || value > INT_MAX)
  1483. quit(_pe, ("Expected int32, but \"" + token + "\" found").c_str());
  1484. return int(value);
  1485. }
  1486. long long InStream::readLong()
  1487. {
  1488. if (!strict && seekEof())
  1489. quit(_pe, "Unexpected end of file - int64 expected");
  1490. std::string token = readWord();
  1491. return stringToLongLong(*this, token.c_str());
  1492. }
  1493. long long InStream::readLong(long long minv, long long maxv, const std::string& variableName)
  1494. {
  1495. long long result = readLong();
  1496. if (result < minv || result > maxv)
  1497. {
  1498. if (variableName.empty())
  1499. quit(_wa, ("Integer " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1500. else
  1501. quit(_wa, ("Integer parameter [name=" + variableName + "] equals to " + vtos(result) + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1502. }
  1503. return result;
  1504. }
  1505. int InStream::readInt()
  1506. {
  1507. return readInteger();
  1508. }
  1509. int InStream::readInt(int minv, int maxv, const std::string& variableName)
  1510. {
  1511. int result = readInt();
  1512. if (result < minv || result > maxv)
  1513. {
  1514. if (variableName.empty())
  1515. quit(_wa, ("Integer " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1516. else
  1517. quit(_wa, ("Integer parameter [name=" + std::string(variableName) + "] equals to " + vtos(result) + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1518. }
  1519. return result;
  1520. }
  1521. int InStream::readInteger(int minv, int maxv, const std::string& variableName)
  1522. {
  1523. return readInt(minv, maxv, variableName);
  1524. }
  1525. double InStream::readReal()
  1526. {
  1527. if (!strict && seekEof())
  1528. quit(_pe, "Unexpected end of file - double expected");
  1529. return stringToDouble(*this, readWord().c_str());
  1530. }
  1531. double InStream::readDouble()
  1532. {
  1533. return readReal();
  1534. }
  1535. double InStream::readReal(double minv, double maxv, const std::string& variableName)
  1536. {
  1537. double result = readReal();
  1538. if (result < minv || result > maxv)
  1539. {
  1540. if (variableName.empty())
  1541. quit(_wa, ("Double " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1542. else
  1543. quit(_wa, ("Double parameter [name=" + variableName + "] equals to " + vtos(result) + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1544. }
  1545. return result;
  1546. }
  1547. double InStream::readStrictReal(double minv, double maxv,
  1548. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  1549. const std::string& variableName)
  1550. {
  1551. if (!strict && seekEof())
  1552. quit(_pe, "Unexpected end of file - strict double expected");
  1553. double result = stringToStrictDouble(*this, readWord().c_str(),
  1554. minAfterPointDigitCount, maxAfterPointDigitCount);
  1555. if (result < minv || result > maxv)
  1556. {
  1557. if (variableName.empty())
  1558. quit(_wa, ("Strict double " + vtos(result) + " violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1559. else
  1560. quit(_wa, ("Strict double parameter [name=" + variableName + "] equals to " + vtos(result) + ", violates the range [" + vtos(minv) + ", " + vtos(maxv) + "]").c_str());
  1561. }
  1562. return result;
  1563. }
  1564. double InStream::readStrictDouble(double minv, double maxv,
  1565. int minAfterPointDigitCount, int maxAfterPointDigitCount,
  1566. const std::string& variableName)
  1567. {
  1568. return readStrictReal(minv, maxv,
  1569. minAfterPointDigitCount, maxAfterPointDigitCount,
  1570. variableName);
  1571. }
  1572. bool InStream::eof()
  1573. {
  1574. if (!strict && NULL == file)
  1575. return true;
  1576. if (feof(file) != 0)
  1577. return true;
  1578. else
  1579. {
  1580. int cur = getc(file);
  1581. if (isEof(char(cur)))
  1582. return true;
  1583. else
  1584. {
  1585. ungetc(cur, file);
  1586. return false;
  1587. }
  1588. }
  1589. }
  1590. bool InStream::seekEof()
  1591. {
  1592. if (NULL == file)
  1593. return true;
  1594. skipBlanks();
  1595. return eof();
  1596. }
  1597. bool InStream::eoln()
  1598. {
  1599. if (!strict && NULL == file)
  1600. return true;
  1601. char c = nextChar();
  1602. if (!strict)
  1603. {
  1604. if (isEof(c))
  1605. return true;
  1606. if (c == CR)
  1607. {
  1608. c = nextChar();
  1609. if (c != LF)
  1610. {
  1611. unreadChar(CR);
  1612. unreadChar(c);
  1613. return false;
  1614. }
  1615. else
  1616. return true;
  1617. }
  1618. if (c == LF)
  1619. return true;
  1620. unreadChar(c);
  1621. return false;
  1622. }
  1623. else
  1624. {
  1625. bool returnCr = false;
  1626. #ifdef ON_WINDOWS
  1627. if (c != CR)
  1628. {
  1629. unreadChar(c);
  1630. return false;
  1631. }
  1632. else
  1633. {
  1634. if (!returnCr)
  1635. returnCr = true;
  1636. c = nextChar();
  1637. }
  1638. #endif
  1639. if (c != LF)
  1640. {
  1641. if (returnCr)
  1642. unreadChar(CR);
  1643. unreadChar(LF);
  1644. return false;
  1645. }
  1646. return true;
  1647. }
  1648. }
  1649. void InStream::readEoln()
  1650. {
  1651. if (!eoln())
  1652. quit(_pe, "Expected EOLN");
  1653. }
  1654. void InStream::readEof()
  1655. {
  1656. if (!eof())
  1657. quit(_pe, "Expected EOF");
  1658. if (TestlibFinalizeGuard::alive)
  1659. testlibFinalizeGuard.readEofCount++;
  1660. }
  1661. bool InStream::seekEoln()
  1662. {
  1663. if (NULL == file)
  1664. return true;
  1665. char cur;
  1666. do
  1667. {
  1668. cur = nextChar();
  1669. }
  1670. while (cur == SPACE || cur == TAB);
  1671. ungetc(cur, file);
  1672. return eoln();
  1673. }
  1674. void InStream::nextLine()
  1675. {
  1676. readLine();
  1677. }
  1678. std::string InStream::readString()
  1679. {
  1680. if (NULL == file)
  1681. quit(_pe, "Expected line");
  1682. std::string retval = "";
  1683. char cur;
  1684. for (;;)
  1685. {
  1686. cur = readChar();
  1687. if (isEoln(cur))
  1688. break;
  1689. if (isEof(cur))
  1690. break;
  1691. retval += cur;
  1692. }
  1693. unreadChar(cur);
  1694. if (strict)
  1695. readEoln();
  1696. else
  1697. eoln();
  1698. return retval;
  1699. }
  1700. std::string InStream::readString(const std::string& ptrn, const std::string& variableName)
  1701. {
  1702. pattern p(ptrn);
  1703. std::string result = readString();
  1704. if (!p.matches(result))
  1705. {
  1706. if (variableName.empty())
  1707. quit(_wa, ("Line \"" + __testlib_part(result) + "\" doesn't correspond to pattern \"" + ptrn + "\"").c_str());
  1708. else
  1709. quit(_wa, ("Line [name=" + variableName + "] equals to \"" + __testlib_part(result) + "\", doesn't correspond to pattern \"" + ptrn + "\"").c_str());
  1710. }
  1711. return result;
  1712. }
  1713. std::string InStream::readLine()
  1714. {
  1715. return readString();
  1716. }
  1717. std::string InStream::readLine(const std::string& ptrn, const std::string& variableName)
  1718. {
  1719. return readString(ptrn, variableName);
  1720. }
  1721. void InStream::close()
  1722. {
  1723. if (opened)
  1724. fclose(file);
  1725. opened = false;
  1726. }
  1727. void quit(TResult result, const std::string& msg)
  1728. {
  1729. ouf.quit(result, msg.c_str());
  1730. }
  1731. void quit(TResult result, const char* msg)
  1732. {
  1733. ouf.quit(result, msg);
  1734. }
  1735. void __testlib_quitp(double points, const char* message)
  1736. {
  1737. char buffer[512];
  1738. if (NULL == message || 0 == strlen(message))
  1739. std::sprintf(buffer, "%.10lf", points);
  1740. else
  1741. std::sprintf(buffer, "%.10lf %s", points, message);
  1742. quit(_points, buffer);
  1743. }
  1744. void quitp(float points, const std::string& message = "")
  1745. {
  1746. __testlib_quitp(double(points), message.c_str());
  1747. }
  1748. void quitp(double points, const std::string& message = "")
  1749. {
  1750. __testlib_quitp(points, message.c_str());
  1751. }
  1752. void quitp(long double points, const std::string& message = "")
  1753. {
  1754. __testlib_quitp(double(points), message.c_str());
  1755. }
  1756. template<typename F>
  1757. #ifdef __GNUC__
  1758. __attribute__ ((format (printf, 2, 3)))
  1759. #endif
  1760. void quitp(F points, const char* format, ...)
  1761. {
  1762. char* buffer = new char [MAX_FORMAT_BUFFER_SIZE];
  1763. va_list ap;
  1764. va_start(ap, format);
  1765. std::vsprintf(buffer, format, ap);
  1766. va_end(ap);
  1767. std::string output(buffer);
  1768. delete[] buffer;
  1769. quitp(points, output);
  1770. }
  1771. #ifdef __GNUC__
  1772. __attribute__ ((format (printf, 2, 3)))
  1773. #endif
  1774. void quitf(TResult result, const char* format, ...)
  1775. {
  1776. char* buffer = new char [MAX_FORMAT_BUFFER_SIZE];
  1777. va_list ap;
  1778. va_start(ap, format);
  1779. std::vsprintf(buffer, format, ap);
  1780. va_end(ap);
  1781. std::string output(buffer);
  1782. delete[] buffer;
  1783. quit(result, output);
  1784. }
  1785. #ifdef __GNUC__
  1786. __attribute__ ((format (printf, 3, 4)))
  1787. #endif
  1788. void quitif(bool condition, TResult result, const char* format, ...)
  1789. {
  1790. if (condition)
  1791. {
  1792. char* buffer = new char [MAX_FORMAT_BUFFER_SIZE];
  1793. va_list ap;
  1794. va_start(ap, format);
  1795. std::vsprintf(buffer, format, ap);
  1796. va_end(ap);
  1797. std::string output(buffer);
  1798. delete[] buffer;
  1799. quit(result, output);
  1800. }
  1801. }
  1802. void __testlib_help()
  1803. {
  1804. InStream::textColor(InStream::LightCyan);
  1805. std::fprintf(stderr, "TESTLIB %s, http://code.google.com/p/testlib/ ", VERSION);
  1806. std::fprintf(stderr, "by Mike Mirzayanov, copyright(c) 2005-2013\n");
  1807. std::fprintf(stderr, "Checker name: \"%s\"\n", checkerName.c_str());
  1808. InStream::textColor(InStream::LightGray);
  1809. std::fprintf(stderr, "\n");
  1810. std::fprintf(stderr, "Latest features: \n");
  1811. for (size_t i = 0; i < sizeof(latestFeatures) / sizeof(char*); i++)
  1812. {
  1813. std::fprintf(stderr, "*) %s\n", latestFeatures[i]);
  1814. }
  1815. std::fprintf(stderr, "\n");
  1816. std::fprintf(stderr, "Program must be run with the following arguments: \n");
  1817. std::fprintf(stderr, " <input-file> <output-file> <answer-file> [<report-file> [<-appes>]]\n\n");
  1818. std::exit(0);
  1819. }
  1820. void registerGen(int argc, char* argv[])
  1821. {
  1822. testlibMode = _generator;
  1823. __testlib_set_binary(stdin);
  1824. rnd.setSeed(argc, argv);
  1825. }
  1826. void registerInteraction(int argc, char* argv[])
  1827. {
  1828. testlibMode = _interactor;
  1829. __testlib_set_binary(stdin);
  1830. if (argc > 1 && !strcmp("--help", argv[1]))
  1831. __testlib_help();
  1832. // testlib assumes: sizeof(int) = 4.
  1833. __TESTLIB_STATIC_ASSERT(sizeof(int) == 4);
  1834. // testlib assumes: INT_MAX == 2147483647.
  1835. __TESTLIB_STATIC_ASSERT(INT_MAX == 2147483647);
  1836. // testlib assumes: sizeof(long long) = 8.
  1837. __TESTLIB_STATIC_ASSERT(sizeof(long long) == 8);
  1838. if (argc < 3 || argc > 6)
  1839. {
  1840. quit(_fail, std::string("Program must be run with the following arguments: ") +
  1841. std::string("<input-file> <output-file> [<answer-file> [<report-file> [<-appes>]]]") +
  1842. "\nUse \"--help\" to get help information");
  1843. }
  1844. if (argc <= 4)
  1845. {
  1846. resultName = "";
  1847. appesMode = false;
  1848. }
  1849. if (argc == 5)
  1850. {
  1851. resultName = argv[4];
  1852. appesMode = false;
  1853. }
  1854. if (argc == 6)
  1855. {
  1856. if (strcmp("-APPES", argv[5]) && strcmp("-appes", argv[5]))
  1857. {
  1858. quit(_fail, std::string("Program must be run with the following arguments: ") +
  1859. "<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]");
  1860. }
  1861. else
  1862. {
  1863. resultName = argv[4];
  1864. appesMode = true;
  1865. }
  1866. }
  1867. if (setvbuf(stdin, NULL, _IONBF, 0) != 0)
  1868. quit(_fail, std::string("Can not disable buffer for stdin"));
  1869. if (setvbuf(stdout, NULL, _IONBF, 0) != 0)
  1870. quit(_fail, std::string("Can not disable buffer for stdout"));
  1871. if (setvbuf(stderr, NULL, _IONBF, 0) != 0)
  1872. quit(_fail, std::string("Can not disable buffer for stderr"));
  1873. inf.init(argv[1], _input);
  1874. tout.open(argv[2], std::ios_base::out);
  1875. if (tout.fail() || !tout.is_open())
  1876. quit(_fail, std::string("Can not write to the test-output-file '") + argv[2] + std::string("'"));
  1877. ouf.init(stdin, _output);
  1878. if (argc >= 4)
  1879. ans.init(argv[3], _answer);
  1880. }
  1881. void registerValidation()
  1882. {
  1883. testlibMode = _validator;
  1884. __testlib_set_binary(stdin);
  1885. // testlib assumes: sizeof(int) = 4.
  1886. __TESTLIB_STATIC_ASSERT(sizeof(int) == 4);
  1887. // testlib assumes: INT_MAX == 2147483647.
  1888. __TESTLIB_STATIC_ASSERT(INT_MAX == 2147483647);
  1889. // testlib assumes: sizeof(long long) = 8.
  1890. __TESTLIB_STATIC_ASSERT(sizeof(long long) == 8);
  1891. inf.init(stdin, _input);
  1892. inf.strict = true;
  1893. }
  1894. void registerTestlibCmd(int argc, char* argv[])
  1895. {
  1896. testlibMode = _checker;
  1897. __testlib_set_binary(stdin);
  1898. if (argc > 1 && !strcmp("--help", argv[1]))
  1899. __testlib_help();
  1900. // testlib assumes: sizeof(int) = 4.
  1901. __TESTLIB_STATIC_ASSERT(sizeof(int) == 4);
  1902. // testlib assumes: INT_MAX == 2147483647.
  1903. __TESTLIB_STATIC_ASSERT(INT_MAX == 2147483647);
  1904. // testlib assumes: sizeof(long long) = 8.
  1905. __TESTLIB_STATIC_ASSERT(sizeof(long long) == 8);
  1906. if (argc < 4 || argc > 6)
  1907. {
  1908. quit(_fail, std::string("Program must be run with the following arguments: ") +
  1909. std::string("<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]") +
  1910. "\nUse \"--help\" to get help information");
  1911. }
  1912. if (argc == 4)
  1913. {
  1914. resultName = "";
  1915. appesMode = false;
  1916. }
  1917. if (argc == 5)
  1918. {
  1919. resultName = argv[4];
  1920. appesMode = false;
  1921. }
  1922. if (argc == 6)
  1923. {
  1924. if (strcmp("-APPES", argv[5]) && strcmp("-appes", argv[5]))
  1925. {
  1926. quit(_fail, std::string("Program must be run with the following arguments: ") +
  1927. "<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]");
  1928. }
  1929. else
  1930. {
  1931. resultName = argv[4];
  1932. appesMode = true;
  1933. }
  1934. }
  1935. inf.init(argv[1], _input);
  1936. ouf.init(argv[2], _output);
  1937. ans.init(argv[3], _answer);
  1938. }
  1939. void registerTestlib(int argc, ...)
  1940. {
  1941. if (argc < 3 || argc > 5)
  1942. quit(_fail, std::string("Program must be run with the following arguments: ") +
  1943. "<input-file> <output-file> <answer-file> [<report-file> [<-appes>]]");
  1944. char** argv = new char*[argc + 1];
  1945. va_list ap;
  1946. va_start(ap, argc);
  1947. argv[0] = NULL;
  1948. for (int i = 0; i < argc; i++)
  1949. {
  1950. argv[i + 1] = va_arg(ap, char*);
  1951. }
  1952. va_end(ap);
  1953. registerTestlibCmd(argc + 1, argv);
  1954. delete[] argv;
  1955. }
  1956. inline bool isNaN(double r)
  1957. {
  1958. return ((r != r) == true) && ((r == r) == false) && ((1.0 > r) == false) && ((1.0 < r) == false);
  1959. }
  1960. inline bool isInfinite(double r)
  1961. {
  1962. return (r > 1E100 || r < -1E100);
  1963. }
  1964. bool doubleCompare(double expected, double result, double MAX_DOUBLE_ERROR)
  1965. {
  1966. if(isNaN(expected))
  1967. {
  1968. return isNaN(result);
  1969. }
  1970. else
  1971. if(isInfinite(expected))
  1972. {
  1973. if(expected > 0)
  1974. {
  1975. return result > 0 && isInfinite(result);
  1976. }
  1977. else
  1978. {
  1979. return result < 0 && isInfinite(result);
  1980. }
  1981. }
  1982. else
  1983. if(isNaN(result) || isInfinite(result))
  1984. {
  1985. return false;
  1986. }
  1987. else
  1988. if(__testlib_abs(result - expected) <= MAX_DOUBLE_ERROR + 1E-15)
  1989. {
  1990. return true;
  1991. }
  1992. else
  1993. {
  1994. double minv = __testlib_min(expected * (1.0 - MAX_DOUBLE_ERROR),
  1995. expected * (1.0 + MAX_DOUBLE_ERROR));
  1996. double maxv = __testlib_max(expected * (1.0 - MAX_DOUBLE_ERROR),
  1997. expected * (1.0 + MAX_DOUBLE_ERROR));
  1998. return result + 1E-15 >= minv && result <= maxv + 1E-15;
  1999. }
  2000. }
  2001. double doubleDelta(double expected, double result)
  2002. {
  2003. double absolute = __testlib_abs(result - expected);
  2004. if (__testlib_abs(expected) > 1E-9)
  2005. {
  2006. double relative = __testlib_abs(absolute / expected);
  2007. return __testlib_min(absolute, relative);
  2008. }
  2009. else
  2010. return absolute;
  2011. }
  2012. static void __testlib_ensure(bool cond, const std::string msg)
  2013. {
  2014. if (!cond)
  2015. quit(_fail, msg.c_str());
  2016. }
  2017. #define ensure(cond) __testlib_ensure(cond, std::string("Condition failed: \"") + #cond + "\"")
  2018. #ifdef __GNUC__
  2019. __attribute__ ((format (printf, 2, 3)))
  2020. #endif
  2021. void ensuref(bool cond, const char* format, ...)
  2022. {
  2023. if (!cond)
  2024. {
  2025. char* buffer = new char [MAX_FORMAT_BUFFER_SIZE];
  2026. va_list ap;
  2027. va_start(ap, format);
  2028. std::vsprintf(buffer, format, ap);
  2029. va_end(ap);
  2030. std::string message(buffer);
  2031. delete[] buffer;
  2032. __testlib_ensure(cond, message);
  2033. }
  2034. }
  2035. #ifdef __GNUC__
  2036. __attribute__ ((format (printf, 1, 2)))
  2037. #endif
  2038. void setName(const char* format, ...)
  2039. {
  2040. char* buffer = new char [MAX_FORMAT_BUFFER_SIZE];
  2041. va_list ap;
  2042. va_start(ap, format);
  2043. std::vsprintf(buffer, format, ap);
  2044. va_end(ap);
  2045. std::string name(buffer);
  2046. delete[] buffer;
  2047. checkerName = name;
  2048. }
  2049. /*
  2050. * Do not use random_shuffle, because it will produce different result
  2051. * for different C++ compilers.
  2052. *
  2053. * This implementation uses testlib random_t to produce random numbers, so
  2054. * it is stable.
  2055. */
  2056. template<typename _RandomAccessIter>
  2057. void shuffle(_RandomAccessIter __first, _RandomAccessIter __last)
  2058. {
  2059. if (__first == __last) return;
  2060. for (_RandomAccessIter __i = __first + 1; __i != __last; ++__i)
  2061. iter_swap(__i, __first + rnd.next(int(__i - __first) + 1));
  2062. }
  2063. template<typename _RandomAccessIter>
  2064. void random_shuffle(_RandomAccessIter __first, _RandomAccessIter __last)
  2065. {
  2066. quitf(_fail, "Don't use random_shuffle(), use shuffle() instead");
  2067. }
  2068. int rand()
  2069. {
  2070. quitf(_fail, "Don't use rand(), use rnd.next() instead");
  2071. return 0;
  2072. }
  2073. void srand(unsigned int seed)
  2074. {
  2075. quitf(_fail, "Don't use srand(), you should use "
  2076. "'registerGen(argc, argv);' to initialize generator seed "
  2077. "by hash code of the command line params [seed=%d ignored]", seed);
  2078. }
  2079. void startTest(int test)
  2080. {
  2081. char c[16];
  2082. std::sprintf(c, "%d", test);
  2083. fclose(stdout);
  2084. freopen(c, "wt", stdout);
  2085. }
  2086. #ifdef __GNUC__
  2087. __attribute__ ((format (printf, 1, 2)))
  2088. #endif
  2089. std::string format(const char* fmt, ...)
  2090. {
  2091. if (strlen(fmt) > MAX_FORMAT_BUFFER_SIZE / 2)
  2092. __testlib_fail("format(const std::string& format, ...): format exceeds maximal length");
  2093. char* buffer = new char[MAX_FORMAT_BUFFER_SIZE];
  2094. va_list ap;
  2095. va_start(ap, fmt);
  2096. std::vsprintf(buffer, fmt, ap);
  2097. va_end(ap);
  2098. std::string output(buffer);
  2099. delete[] buffer;
  2100. return output;
  2101. }
  2102. std::string format(const std::string& fmt, ...)
  2103. {
  2104. if (fmt.length() > MAX_FORMAT_BUFFER_SIZE / 2)
  2105. __testlib_fail("format(const std::string& format, ...): format exceeds maximal length");
  2106. char* buffer = new char[MAX_FORMAT_BUFFER_SIZE];
  2107. va_list ap;
  2108. va_start(ap, fmt);
  2109. std::vsprintf(buffer, fmt.c_str(), ap);
  2110. va_end(ap);
  2111. std::string output(buffer);
  2112. delete[] buffer;
  2113. return output;
  2114. }
  2115. static void __testlib_fail(const std::string& message)
  2116. {
  2117. quitf(_fail, message.c_str());
  2118. }
  2119. #endif