-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathvalidation.h
1495 lines (1302 loc) · 44.5 KB
/
validation.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#pragma once
// A header library to safely parse team input.
// It does not support big integers.
// Author: Ragnar Groot Koerkamp
// The easiest way to use this is to symlink it from a validator directory,
// so that it will be picked up when creating a contest zip.
// The default checking behaviour is strict for case, whitespace, and floats.
// This strict checking mode is used for *.in and *.ans files.
// When validating submission outputs, the checking is more lenient,
// but the case_sensitive and space_change_sensitive flags can be passed
// via the output_validator_args in testdata.yaml to enable strict checking behaviour
// for submission outputs regarding case and whitespace, respectively.
#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <charconv>
#include <cstring>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <optional>
#include <random>
#include <regex>
#include <set>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <variant>
#include <vector>
constexpr std::string_view case_sensitive_flag = "case_sensitive";
constexpr std::string_view ws_sensitive_flag = "space_change_sensitive";
constexpr std::string_view constraints_file_flag = "--constraints_file";
constexpr std::string_view generate_flag = "--generate";
constexpr std::string_view generate_binary_substring = "generat";
// Only use non-capturing groups, and optimize the RegEx during initialization (improves run time at the cost of build time)
constexpr auto regex_options = std::regex::nosubs | std::regex::optimize;
// Source: https://icpc.io/problem-package-format/spec/2023-07-draft.html
// Made stricter by:
// - Disallowing '+' as sign (both at the start and in the exponent)
// - Disallowing 'E' as exponent
// - Disallowing superfluous leading zeroes before the decimal dot and in the exponent (the former can be 0, the latter cannot)
// - Disallowing decimal dot without following digits
const std::regex float_regex("-?(0|[1-9][0-9]*)(\\.[0-9]+)?(e-?[1-9][0-9]*)?", regex_options);
inline struct ArbitraryTag {
static constexpr bool unique = false;
static constexpr bool strict = false;
static constexpr bool increasing = false;
static constexpr bool decreasing = false;
} Arbitrary;
inline struct UniqueTag : ArbitraryTag {
static constexpr bool unique = true;
static constexpr bool strict = false;
static constexpr bool increasing = false;
static constexpr bool decreasing = false;
} Unique;
inline struct IncreasingTag : ArbitraryTag {
static constexpr bool increasing = true;
} Increasing;
inline struct DecreasingTag : ArbitraryTag {
static constexpr bool decreasing = true;
} Decreasing;
inline struct StrictlyIncreasingTag : ArbitraryTag {
static constexpr bool strict = true;
static constexpr bool increasing = true;
} StrictlyIncreasing;
inline struct StrictlyDecreasingTag : ArbitraryTag {
static constexpr bool strict = true;
static constexpr bool decreasing = true;
} StrictlyDecreasing;
template <typename... T>
struct Merge : T... {
static constexpr bool unique = (T::unique || ...);
static constexpr bool strict = (T::strict || ...);
static constexpr bool increasing = (T::increasing || ...);
static constexpr bool decreasing = (T::decreasing || ...);
};
template <typename T1, typename T2,
std::enable_if_t<
std::is_base_of_v<ArbitraryTag, T1> and std::is_base_of_v<ArbitraryTag, T2>, int> = 0>
auto operator|(T1 /*unused*/, T2 /*unused*/) {
return Merge<T1, T2>();
}
enum Separator { Space, Newline };
// this contains some specific code which emulates c++20 features
namespace cpp20 {
constexpr int countl_zero(unsigned long long x) {
int res = 64;
for(int i = 32; i > 0; i >>= 1) {
if((x >> i) > 0) {
res -= i;
x >>= i;
}
}
if(x > 0) res--;
return res;
}
int popcount(unsigned long long x) {
return static_cast<int>(std::bitset<64>(x).count());
}
constexpr long double PI = 3.141592653589793238462643383279502884l;
} // namespace cpp20
namespace Random {
constexpr unsigned int default_seed = 3141592653; // some digits of PI
unsigned long long bits64(std::mt19937_64& rng) {
static_assert(std::mt19937_64::max() == 0xFFFF'FFFF'FFFF'FFFFull);
static_assert(std::mt19937_64::min() == 0ull);
return rng();
}
// generates a uniform real in [0, 1)
long double real64(std::mt19937_64& rng) {
// a long double can represent more than 2^64 values in the range [0, 1)...
// another problem is that real64() < 1.0/3.0 is technically biased.
long double res = bits64(rng) / 0x1.0p64l;
res += bits64(rng) / 0x1.0p128l;
assert(res < 1.0l);
return res;
}
bool bit(std::mt19937_64& rng) {
return cpp20::popcount(bits64(rng)) & 1;
}
} // namespace Random
template <typename T>
constexpr bool is_number_v = std::is_same_v<T, long long> or std::is_same_v<T, long double>;
namespace Generators {
template <typename T>
struct ConstGenerator {
static_assert(is_number_v<T> or std::is_same_v<T, char> or std::is_same_v<T, std::string>);
static constexpr std::string_view name = "const";
using Args = std::tuple<T>;
const T const_;
explicit ConstGenerator(T val) : const_(std::move(val)) {}
// For char and string, the constant store has a different type than the min and max length
// passed in.
template <typename U>
T operator()(U low, U high, std::mt19937_64& rng) const {
return std::clamp(const_, low, high);
}
};
struct MinGenerator {
static constexpr std::string_view name = "min";
using Args = std::tuple<>;
explicit MinGenerator() = default;
template <typename T>
T operator()(T low, T high, std::mt19937_64& rng) const {
static_assert(is_number_v<T>);
return low;
}
};
struct MaxGenerator {
static constexpr std::string_view name = "max";
using Args = std::tuple<>;
explicit MaxGenerator() = default;
template <typename T>
T operator()(T low, T high, std::mt19937_64& rng) const {
static_assert(is_number_v<T>);
return high;
}
};
struct UniformGenerator {
static constexpr std::string_view name = "uniform";
using Args = std::tuple<>;
explicit UniformGenerator() = default;
template <typename T>
T operator()(T low, T high, std::mt19937_64& rng) const {
static_assert(is_number_v<T>);
if(low == high) return low;
if constexpr(std::is_same_v<T, long long>) {
assert(low < high);
// Since C++20 we can assume Two's Complement but any sane system used it before anyway.
// Rejection sampling is not as fast as possible but definitely unbiased.
auto ul = static_cast<unsigned long long>(low);
auto uh = static_cast<unsigned long long>(high);
int shitfs = cpp20::countl_zero(uh - ul);
unsigned long long res;
do {
res = Random::bits64(rng) >> shitfs;
} while(res > uh - ul);
return static_cast<long long>(res + ul);
} else {
assert(low < high);
return low + Random::real64(rng) * (high - low);
}
}
};
template <typename T>
struct RangeGenerator {
static_assert(is_number_v<T>);
static constexpr std::string_view name = "range";
using Args = std::tuple<T, T>;
const T low_, high_;
explicit RangeGenerator(T low, T high) : low_(low), high_(high) {}
T operator()(T low, T high, std::mt19937_64& rng) const {
return UniformGenerator()(std::max(low, low_), std::min(high, high_), rng);
}
};
template <typename T>
struct StepRangeGenerator {
static_assert(is_number_v<T>);
static constexpr std::string_view name = "steprange";
using Args = std::tuple<T, T, T>;
const T low_, high_, step_;
explicit StepRangeGenerator(T low, T high, T step) : low_(low), high_(high), step_(step) {}
T operator()(T low, T high, std::mt19937_64& rng) const {
// round up low to the first multiple of step_.
T start;
if(low <= low_) {
start = low_;
} else {
// first multiple of low_+k*step_ >= low
start = low_ + (long long)((low - low_) / step_) * step_;
if(start < low) start += step_;
assert(low <= start && start < low + step_);
}
long long maxsteps = (std::min(high, high_) - start) / step_;
long long steps = UniformGenerator()(0ll, maxsteps, rng);
return start + steps * step_;
}
};
struct NormalDistributionGenerator {
static constexpr std::string_view name = "normal";
using T = long double;
using Args = std::tuple<T, T>;
const T mean_, stddev_;
explicit NormalDistributionGenerator(T mean, T stddev) : mean_(mean), stddev_(stddev) {
assert(stddev_ >= 0);
}
// NOTE: Currently this retries instead of clamping to the interval.
T operator()(T low, T high, std::mt19937_64& rng) const {
assert(low < high);
T v;
while(true) {
T u1 = Random::real64(rng);
T u2 = Random::real64(rng);
// Box-Muller-Methode
// https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform
v = std::sqrt(-2.0l * std::log(u1)) * std::cos(2.0l * cpp20::PI * u2);
v = std::sqrt(stddev_) * v + mean_;
if(v >= low && v < high) return v;
v = std::sqrt(-2.0l * std::log(u1)) * std::sin(2.0l * cpp20::PI * u2);
v = std::sqrt(stddev_) * v + mean_;
if(v >= low && v < high) return v;
}
return v;
}
};
struct ExponentialDistributionGenerator {
static constexpr std::string_view name = "exponential";
using T = long double;
using Args = std::tuple<T>;
T lambda_;
explicit ExponentialDistributionGenerator(T lambda) : lambda_(lambda) { assert(lambda_ > 0); }
// NOTE: Currently this retries instead of clamping to the interval.
T operator()(T low, T high, std::mt19937_64& rng) const {
assert(low < high);
T v;
while(true) {
v = low - std::log(Random::real64(rng)) / lambda_;
if(v < high) return v;
}
}
};
struct GeometricDistributionGenerator {
static constexpr std::string_view name = "geometric";
using T = long long;
using Args = std::tuple<long double>;
double p_;
explicit GeometricDistributionGenerator(double p) : p_(p) {
assert(p_ > 0);
assert(p_ < 1);
}
// NOTE: Currently this retries instead of clamping to the interval.
T operator()(T low, T high, std::mt19937_64& rng) const {
assert(low <= high);
T v;
while(true) {
// https://en.wikipedia.org/wiki/Geometric_distribution
// "The exponential distribution is the continuous analogue of the geometric
// distribution[...]"
v = low + std::floor(std::log(Random::real64(rng)) / std::log1p(-p_));
if(v <= high) return v;
}
}
};
struct BinomialDistributionGenerator {
static constexpr std::string_view name = "binomial";
using T = long long;
using Args = std::tuple<long long, long double>;
long long n_;
double p_;
explicit BinomialDistributionGenerator(long long n, double p) : n_(n), p_(p) {
assert(p_ >= 0);
assert(p_ <= 1);
std::cerr << "Warning: Large n (" << n_ << ") is slow for BinomialDistributionGenerator!"
<< std::endl;
}
// NOTE: Currently this retries instead of clamping to the interval.
T operator()(T low, T high, std::mt19937_64& rng) const {
assert(low <= high);
// this will be slow for large n
// (a faster implementation requires efficient poisson sampling)
while(true) {
T v = 0;
for(long long i = 0; i < n_; i++) {
v += Random::real64(rng) < p_ ? 1 : 0;
}
if(v >= low && v <= high) return v;
}
}
};
template <typename T>
struct ChoiceGenerator {
using GeneratorType = std::conditional_t<
std::is_same_v<T, long long>,
std::variant<ConstGenerator<T>, MinGenerator, MaxGenerator, UniformGenerator,
RangeGenerator<T>, StepRangeGenerator<T>, GeometricDistributionGenerator,
BinomialDistributionGenerator>,
std::variant<ConstGenerator<T>, MinGenerator, MaxGenerator, UniformGenerator,
RangeGenerator<T>, StepRangeGenerator<T>, NormalDistributionGenerator,
ExponentialDistributionGenerator>>;
std::vector<std::pair<GeneratorType, double>> generators_;
double total_weight_;
template <typename>
struct Pack {};
template <typename A>
static A parse_number(std::string_view s) {
static_assert(is_number_v<A>);
if constexpr(std::is_same_v<A, long long>)
return stoll(std::string(s));
else
return stold(std::string(s));
}
template <typename A>
static A parse_argument(std::string_view& s) {
auto end = s.find_first_of(",)");
assert(end != std::string_view::npos);
auto v = parse_number<A>(s.substr(0, end));
s.remove_prefix(end);
// Pop the trailing , or )
s.remove_prefix(1);
return v;
}
template <typename... As>
static std::tuple<As...> parse_arguments(std::string_view& s,
Pack<std::tuple<As...>> /*unused*/) {
std::tuple<As...> args{parse_argument<As>(s)...};
return args;
}
// Try parsing one generator type from the start of s.
template <typename G>
static void parse_generator(std::string_view& s, std::optional<GeneratorType>& out) {
if(out) return;
if(s.substr(0, G::name.size()) != G::name) return;
// Drop the name.
s.remove_prefix(G::name.size());
if constexpr(std::tuple_size_v<typename G::Args> == 0) {
out.emplace(std::in_place_type_t<G>{});
return;
}
// Drop the (
assert(not s.empty() and s.front() == '(');
s.remove_prefix(1);
auto args = parse_arguments(s, Pack<typename G::Args>{});
// Construct the resulting generator in-place in the variant..
std::apply([&](const auto&... _args) { out.emplace(std::in_place_type_t<G>{}, _args...); },
args);
}
template <typename... Gs>
static std::optional<GeneratorType> parse_generators(std::string_view& s,
Pack<std::variant<Gs...>> /*unused*/) {
std::optional<GeneratorType> out;
(parse_generator<Gs>(s, out), ...);
return out;
}
explicit ChoiceGenerator(std::string_view s) : total_weight_(0) {
// PARSE
while(not s.empty()) {
auto generator = parse_generators(s, Pack<GeneratorType>{});
if(!generator) {
// Check for range syntax:
auto comma = s.find_first_of(",:");
if(comma == std::string::npos) comma = s.size();
auto dots = s.find("..");
if(dots != std::string_view::npos and dots < comma) {
auto start = s.substr(0, dots);
auto end = s.substr(dots + 2, comma - dots - 2);
generator.emplace(std::in_place_type_t<RangeGenerator<T>>{},
parse_number<T>(start), parse_number<T>(end));
s.remove_prefix(comma);
}
// Fall back to constant.
if(!generator) {
generator.emplace(std::in_place_type_t<ConstGenerator<T>>{},
parse_number<T>(s.substr(0, comma)));
s.remove_prefix(comma);
}
}
// Parse weight if given.
double weight = 1;
if(not s.empty() and s.front() == ':') {
s.remove_prefix(1);
auto comma = s.find(',');
if(comma == std::string_view::npos) comma = s.size();
weight = parse_number<long double>(s.substr(0, comma));
s.remove_prefix(comma);
}
// should now be at , or end
assert(s.empty() or s.front() == ',');
if(not s.empty()) s.remove_prefix(1);
generators_.emplace_back(std::move(*generator), weight);
total_weight_ += weight;
}
}
T operator()(T low, T high, std::mt19937_64& rng) const {
Generators::UniformGenerator uniform;
double x = uniform.operator()<long double>(0, total_weight_, rng);
for(size_t i = 0; i < generators_.size(); ++i) {
x -= generators_[i].second;
if(x <= 0)
return std::visit([&](auto& g) { return g(low, high, rng); }, generators_[i].first);
}
assert(false);
}
};
struct ParamGenerator {
std::variant<std::string_view, ChoiceGenerator<long long>, ChoiceGenerator<long double>>
generator;
explicit ParamGenerator(std::string_view s) : generator(s) {}
template <typename T>
T operator()(T low, T high, std::mt19937_64& rng) {
static_assert(is_number_v<T>);
if(std::holds_alternative<std::string_view>(generator)) {
generator = ChoiceGenerator<T>(std::get<std::string_view>(generator));
}
return std::get<ChoiceGenerator<T>>(generator)(low, high, rng);
}
};
} // namespace Generators
using Generators::ParamGenerator;
namespace Random {
template <class RandomIt>
void shuffle(RandomIt first, RandomIt last, std::mt19937_64& rng) {
Generators::UniformGenerator uniform;
long long n = last - first;
for(long long i = n - 1; i > 0; i--) {
std::swap(first[i], first[uniform(0ll, i, rng)]);
}
}
template <class T>
void shuffle(std::pair<T, T>& in, std::mt19937_64& rng) {
if(bit(rng)) std::swap(in.first, in.second);
}
template <class RandomIt>
auto& select(RandomIt first, RandomIt last, std::mt19937_64& rng) {
assert(first != last);
Generators::UniformGenerator uniform;
long long n = last - first;
return first[uniform(0ll, n - 1, rng)];
}
template <class T>
const T& select(const std::pair<T, T>& in, std::mt19937_64& rng) {
return bit(rng) ? in.first : in.second;
}
template <class T>
T& select(std::pair<T, T>& in, std::mt19937_64& rng) {
return bit(rng) ? in.first : in.second;
}
} // namespace Random
class Validator {
protected:
Validator(bool ws_, bool case_, bool sf_, std::istream& in_, std::string constraints_file_path_ = "",
std::optional<unsigned int> seed = std::nullopt,
std::unordered_map<std::string, ParamGenerator> params_ = {})
: in(in_), ws(ws_), case_sensitive(case_), strict_float(sf_),
constraints_file_path(std::move(constraints_file_path_)), gen(seed.has_value()),
rng(seed.value_or(Random::default_seed)), params(std::move(params_)) {
std::ios_base::sync_with_stdio(false);
in.tie(nullptr);
if(gen) return;
if(ws)
in >> std::noskipws;
else
in >> std::skipws;
}
public:
// No copying, no moving.
Validator(const Validator&) = delete;
Validator(Validator&&) = delete;
void operator=(const Validator&) = delete;
void operator=(Validator&&) = delete;
// At the end of the scope, check whether the EOF has been reached.
// If so, return AC. Otherwise, return WA.
~Validator() {
eof();
write_constraints();
AC();
}
void space() {
if(gen) {
out << ' ';
return;
}
if(ws) {
char c;
in >> c;
check(!in.eof(), "Expected space, found EOF.");
if(c != ' ')
expected("space", std::string("\"") +
((c == '\n' or c == '\r') ? std::string("newline")
: std::string(1, c)) +
"\"");
}
}
void newline() {
if(gen) {
out << '\n';
return;
}
if(ws) {
char c;
in >> c;
check(!in.eof(), "Expected newline, found EOF.");
if(c != '\n') {
if(c == '\r')
expected("newline", "DOS line ending (\\r)");
else
expected("newline", std::string("\"") + c + "\"");
}
}
}
private:
void separator(Separator s) {
switch(s) {
case Separator::Space: space(); break;
case Separator::Newline: newline(); break;
}
}
template <typename T>
auto& seen() {
static std::unordered_map<std::string, std::set<T>> seen;
return seen;
}
template <typename T>
auto& last_seen() {
static std::unordered_map<std::string, T> last_seen;
return last_seen;
}
template <typename T>
auto& integers_seen() {
static std::unordered_map<std::string, std::tuple<std::set<T>, std::vector<T>, bool>>
integers_seen;
return integers_seen;
}
template <typename T>
void reset(std::string name) {
seen<T>().erase(name);
last_seen<T>().erase(name);
integers_seen<T>().erase(name);
}
template <typename T, typename Tag>
void check_number(const std::string& name, T low, T high, T v, Tag /*unused*/) {
static_assert(is_number_v<T>);
if(v < low or v > high) {
std::string type_name;
if constexpr(std::is_integral_v<T>) {
type_name = "integer";
}
if constexpr(std::is_floating_point_v<T>) {
type_name = "float";
}
expected(name + ": " + type_name + " between " + std::to_string(low) + " and " +
std::to_string(high),
std::to_string(v));
}
log_constraint(name, low, high, v);
if constexpr(Tag::unique) {
auto [it, inserted] = seen<T>()[name].emplace(v);
check(inserted, name, ": Value ", v, " seen twice, but must be unique!");
} else {
auto [it, inserted] = last_seen<T>().emplace(name, v);
if(inserted) return;
auto last = it->second;
it->second = v;
if constexpr(Tag::increasing)
check(v >= last, name, " is not increasing: value ", v, " follows ", last);
if constexpr(Tag::decreasing)
check(v <= last, name, " is not decreasing: value ", v, " follows ", last);
if constexpr(Tag::strict)
check(v != last, name, " is not strict: value ", v, " equals ", last);
}
}
template <typename Tag>
void check_string(const std::string& name, int low, int high, const std::string& v,
Tag /*unused*/) {
using T = std::string;
if((int)v.size() < low or (int) v.size() > high) {
expected(name + ": " + "string with" + " length between " + std::to_string(low) +
" and " + std::to_string(high),
v);
}
log_constraint("|" + name + "|", low, high, static_cast<int>(v.size()));
if constexpr(Tag::unique) {
auto [it, inserted] = seen<T>()[name].emplace(v);
check(inserted, name, ": Value ", v, " seen twice, but must be unique!");
} else if(Tag::increasing or Tag::decreasing) {
auto [it, inserted] = last_seen<T>().emplace(name, v);
if(inserted) return;
auto last = it->second;
it->second = v;
if constexpr(Tag::increasing)
check(v >= last, name, " is not increasing: value ", v, " follows ", last);
if constexpr(Tag::decreasing)
check(v <= last, name, " is not decreasing: value ", v, " follows ", last);
if constexpr(Tag::strict)
check(v != last, name, " is not strict: value ", v, " equals ", last);
}
}
// Generate a random integer in [low, high] or float in [low, high).
template <typename T>
T uniform_number(T low, T high) {
assert(low <= high);
Generators::UniformGenerator uniform;
if constexpr(std::is_integral<T>::value)
return uniform.operator()<long long>(low, high, rng);
else
return uniform.operator()<long double>(low, high, rng);
}
template <typename T, typename Tag>
T gen_number(const std::string& name, T low, T high, Tag /*unused*/) {
static_assert(is_number_v<T>);
T v;
if constexpr(Tag::unique) {
assert(params.find(name) == params.end() &&
"Parameters are not supported for unique values.");
if constexpr(std::is_integral<T>::value) {
auto& [seen_here, remaining_here, use_remaining] = integers_seen<T>()[name];
if(use_remaining) {
check(!remaining_here.empty(), name, ": no unique values left");
v = remaining_here.back();
remaining_here.pop_back();
} else {
do {
v = uniform_number(low, high);
} while(!seen_here.insert(v).second);
struct CountIterator {
T v;
T& operator*() { return v; }
T& operator++() { return ++v; }
T operator++(int) { return v++; }
bool operator!=(CountIterator r) { return v != r.v; }
};
if(seen_here.size() > (high - low) / 2) {
use_remaining = true;
set_difference(CountIterator{low}, CountIterator{high + 1},
seen_here.begin(), seen_here.end(),
std::back_inserter(remaining_here));
}
}
} else {
// For floats, just regenerate numbers until success.
auto& seen_here = seen<T>()[name];
do {
v = uniform_number(low, high);
} while(!seen_here.insert(v).second);
}
} else {
assert(not Tag::increasing && "Generating increasing sequences is not yet supported!");
assert(not Tag::decreasing && "Generating decreasing sequences is not yet supported!");
assert((std::is_same<Tag, ArbitraryTag>::value) &&
"Only Unique and Arbitrary are supported!");
if(params.find(name) != params.end()) {
v = params.at(name).operator()<T>(low, high, rng);
// This will be checked during input validation of the generated case.
// assert(low <= v and v <= high);
} else {
v = uniform_number<T>(low, high);
}
}
return v;
}
std::string gen_string(const std::string& name, long long low, long long high,
std::string_view chars) {
assert(!chars.empty());
int len;
if(params.find(name + ".length") != params.end())
len = params.at(name + ".length").operator()<long long>(low, high, rng);
else
len = uniform_number(low, high);
std::string s(len, ' ');
for(auto& x : s) x = chars[uniform_number<int>(0, chars.size() - 1)];
out << s;
return s;
}
public:
template <typename Tag = ArbitraryTag>
long long gen_integer(const std::string& name, long long low, long long high, Tag tag = Tag{}) {
return gen_number(name, low, high, tag);
}
template <typename Tag = ArbitraryTag>
long double gen_float(const std::string& name, long double low, long double high,
Tag tag = Tag{}) {
return gen_number(name, low, high, tag);
}
private:
template <typename T, typename Tag>
std::vector<T> gen_numbers(const std::string& name, int count, T low, T high, Tag /*unused*/) {
static_assert(is_number_v<T>);
std::vector<T> v;
v.reserve(count);
if constexpr(std::is_same_v<Tag, ArbitraryTag>) {
if(params.find(name) != params.end()) {
auto& generator = params.at(name);
for(int i = 0; i < count; ++i) {
auto val = generator.operator()<T>(low, high, rng);
assert(low <= val and val <= high);
v.push_back(val);
}
} else {
for(int i = 0; i < count; ++i) {
v.push_back(uniform_number<T>(low, high));
}
}
} else if constexpr(Tag::unique) {
assert(params.find(name) == params.end() &&
"Parameters are not supported for unique values.");
std::set<T> seen_here;
if constexpr(std::is_integral_v<T>) {
if(2 * count < high - low) {
for(int i = 0; i < count; ++i) {
// If density < 1/2: retry.
T w;
do {
w = uniform_number(low, high);
} while(!seen_here.insert(w).second);
v.push_back(w);
}
} else {
// If density >= 1/2, crop a random permutation.
v.resize(high - low + 1);
iota(begin(v), end(v), low);
Random::shuffle(begin(v), end(v), rng);
v.resize(count);
}
} else {
for(int i = 0; i < count; ++i) {
// For floats, just regenerate numbers until success.
T w;
do {
w = uniform_number(low, high);
} while(!seen_here.insert(w).second);
v.push_back(w);
}
}
} else {
static_assert(Tag::increasing or Tag::decreasing);
constexpr bool integral_strict = Tag::strict and std::is_integral<T>::value;
if(integral_strict) {
assert(params.find(name) == params.end() &&
"Parameters are not supported for strict integer values.");
high = high - count + 1;
}
if(params.find(name) != params.end()) {
auto& generator = params.at(name);
for(int i = 0; i < count; ++i) {
auto val = generator.operator()<T>(low, high, rng);
assert(low <= val and val <= high);
v.push_back(val);
}
} else {
for(int i = 0; i < count; ++i) {
v.push_back(uniform_number<T>(low, high));
}
}
sort(begin(v), end(v));
if(integral_strict) {
for(int i = 0; i < count; ++i) v[i] += i;
}
if(Tag::decreasing) reverse(begin(v), end(v));
}
return v;
}
public:
template <typename Tag = ArbitraryTag>
std::vector<long long> gen_integers(const std::string& name, int count, long long low,
long long high, Tag tag = Tag{}) {
return gen_numbers(name, count, low, high, tag);
}
template <typename Tag = ArbitraryTag>
std::vector<long double> gen_floats(const std::string& name, int count, long double low,
long double high, Tag tag = Tag{}) {
return gen_numbers(name, count, low, high, tag);
}
private:
template <typename T, typename Tag>
T read_number(const std::string& name, T low, T high, Tag tag) {
if(gen) {
auto v = gen_number(name, low, high, tag);
out << std::setprecision(10) << std::fixed << v;
return v;
}
const auto v = [&] {
if constexpr(std::is_integral<T>::value)
return read_integer(name);
else
return read_float(name);
}();
check_number(name, low, high, v, tag);
return v;
}
// Read a vector of numbers, separated by spaces and ended by a newline.
template <typename T, typename Tag>
std::vector<T> read_numbers(const std::string& name, int count, T low, T high, Tag tag,
Separator sep) {
if(gen) {
auto v = gen_numbers(name, count, low, high, tag);
out << std::setprecision(10) << std::fixed;
for(int i = 0; i < count; ++i) {
out << v[i];
if(i < count - 1) separator(sep);
}
newline();
return v;
}
reset<T>(name);
std::vector<T> v(count);
for(int i = 0; i < count; ++i) {
if constexpr(std::is_integral<T>::value)
v[i] = read_integer(name);
else
v[i] = read_float(name);
check_number(name, low, high, v[i], tag);
if(i < count - 1) separator(sep);
}
newline();
return v;
}
public:
template <typename Tag = ArbitraryTag>
long long read_integer(const std::string& name, long long low, long long high,
Tag tag = Tag{}) {
return read_number(name, low, high, tag);
}
template <typename Tag = ArbitraryTag>
std::vector<long long> read_integers(const std::string& name, int count, long long low,
long long high, Tag tag = Tag{}, Separator sep = Space) {
return read_numbers(name, count, low, high, tag, sep);
}
template <typename Tag = ArbitraryTag>
long double read_float(const std::string& name, long double low, long double high,
Tag tag = Tag{}) {
return read_number(name, low, high, tag);
}
template <typename Tag = ArbitraryTag>
std::vector<long double> read_floats(const std::string& name, int count, long double low,
long double high, Tag tag = Tag{}, Separator sep = Space) {
return read_numbers(name, count, low, high, tag, sep);
}
// Read a vector of strings, separated by spaces and ended by a newline.