1
0

testlib.h 56 KB

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