-
Notifications
You must be signed in to change notification settings - Fork 115
/
tester109.py
5990 lines (5359 loc) · 206 KB
/
tester109.py
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
# Automated tester for the problems in the collection
# "109 Python Problems for CCPS 109" by Ilkka Kokkarinen.
# Report errors and improvements to [email protected]
# Requires Python 3.7+ for the guarantee to iterate collections
# in the insertion order, needed to run some test case generators
# the exact same way in every platform and future Python version.
from hashlib import sha256
from time import time
from itertools import islice, permutations, combinations, zip_longest, cycle, product, count, chain
from math import isqrt, gcd
from random import Random
import gzip
import os.path
import string
from sys import version_info, exit
import labs109
from fractions import Fraction as F
from datetime import date
# During development, this dictionary contains the functions whose calls and
# results you want to see first during the test run. Make each entry "name":N,
# where N is how many test cases you want to see printed out. This also makes
# the tester to run the tests for these functions first, regardless of their
# position in the labs109.py file. Use the limit of -1 to say "all test cases".
verbose_execution = {
# "function_one": 42, # Print the first 42 test cases of function_one
# "function_two": -1, # Print all test cases of function_two, however many there are
# "function_three": 0 # Be silent with function_three (but run it early)
}
# Whether to use the expected answers from the expected answers file when they exist.
use_expected_answers = True
# The release date of this version of the tester.
version = "November 2, 2024"
# Fixed seed used to generate pseudorandom numbers.
fixed_seed = 12345
# Name of the file that contains the expected answers.
expected_answers_file = 'expected_answers'
# Markers used to separate the parts of the expected answers file.
# These should never appear as the prefix of any expected answer.
version_prefix = '<$$$$>'
function_prefix = '<****>'
# Timeout cutoff for individual function tests, in seconds.
timeout_cutoff = 20
# How many test cases to record in the file for each function.
testcase_cutoff = 300
# Is the script allowed to create a new expected_answers file? Do not
# change this unless you know what you are doing.
can_record = False
# For instructors who want to add their own problems to this set:
#
# 1. Set the value of use_record to False. Update the version info
# of this tester script in the above settings.
# 2. Write your private solution function to your model solutions
# file labs109.py.
# 3. Write the corresponding test case generator in this script below.
# 4. Add the individual test into the list of testcases list below,
# using None as its expected checksum for the moment.
# 5. Run this test script.
# 6. Replace None in the test case with the printed checksum.
# 7. Run this test script again to make sure the test passes.
# 8. Once you have done the above for all the functions that you
# want to add, set the value of use_record back to True.
# 9. Delete the expected_answers file from the same folder that
# this script is located in.
# 10. Run this test script to generate the new expected answers file.
# 11. Release the new version of tester and record to students.
# Convert a dictionary or set result to a list sorted by keys to
# guarantee that such results are identical in all environments.
def canonize(result):
if isinstance(result, dict):
result = [(key, result[key]) for key in result]
result.sort()
elif isinstance(result, set):
result = [key for key in result]
result.sort()
return result
# Convert the arguments given to the student function into a string for safekeeping,
# just in case the student function messes up the contents of the argument objects.
# This makes the discrepancy outputs accurate and less confusing to students. Also,
# when arguments are long, we will try not to flood the user console.
def stringify_args(args, cutoff=2000):
result = ""
for (i, a) in enumerate(args):
if i > 0:
result += ", "
if type(a) == list or type(a) == tuple:
if len(a) < cutoff:
result += str(a)
else:
left = ", ".join([str(x) for x in a[:5]])
right = ", ".join([str(x) for x in a[-5:]])
result += f"[{left}, <{len(a) - 10} omitted...>, {right}]"
else:
result += repr(a) if len(repr(a)) < cutoff else '[...]'
return result
# Runs the function f for its test cases, calculating SHA256 checksum
# for the results. If the checksum matches the expected, return the
# running time, otherwise return -1. If expected == None, print out
# the computed checksum instead. If recorder != None, print out the
# arguments and the result returned from function into the recorder.
def test_one_function(f, test_generator, expected_checksum=None, recorder=None, expected_answers=None):
function_name, recorded, output_len = f.__name__, None, 0
print(f"{function_name}: ", end="", flush=True)
# How many results of function calls to print out.
verb_count = verbose_execution.get(function_name, 0)
if recorder:
print(f"{function_prefix}{function_name}", file=recorder)
if expected_answers:
recorded = expected_answers.get(function_name, None)
chk, start_time, crashed = sha256(), time(), False
for (test_case_idx, test_args) in enumerate(test_generator(fixed_seed)):
# Convert a singleton of any non-tuple into singleton tuple.
if not isinstance(test_args, tuple):
test_args = (test_args,)
# Convert arguments to a string for safekeeping in case of discrepancy.
test_args_string = stringify_args(test_args)
# Call the function to be tested with the arguments from the test tuple.
try:
result = f(*test_args)
except Exception as e: # catch any exception
crashed = True
print(f"CRASH AT TEST CASE #{test_case_idx} WITH ARGS: {test_args_string}")
print(f"CAUGHT EXCEPTION: {e}")
break
# If the result is a set or dictionary, turn it into sorted list first.
result = canonize(result)
# Print out the argument and result, if in verbose mode.
if verb_count > 0 or verb_count == -1:
verb_count -= 1 if verb_count > 0 else 0
print(f"{function_name} #{test_case_idx}: ", end="", flush=True)
print(test_args_string)
print(f"RESULT: {result}", flush=True)
# Update the checksum.
sr = str(result)
chk.update(sr.encode('utf-8'))
# When in recording mode, write the answer to the record file.
if recorder:
output = sr.strip()
print(output, file=recorder)
output_len += len(output) + 1
if test_case_idx >= testcase_cutoff:
break
if use_expected_answers and expected_answers and test_case_idx < testcase_cutoff and recorded:
if sr.strip() != recorded[test_case_idx]:
crashed = True
print(f"DISCREPANCY AT TEST CASE #{test_case_idx}: ")
print("ARGUMENTS: ", end="")
print(test_args_string)
print(f"EXPECTED: {recorded[test_case_idx]}")
print(f"RETURNED: {sr}")
break
total_time = time() - start_time
if total_time > timeout_cutoff:
print(f"TIMEOUT AFTER TEST CASE #{test_case_idx}. FUNCTION REJECTED AS TOO SLOW.")
crashed = True
break
if not recorder:
total_time = time() - start_time
digest = chk.hexdigest()
if not crashed and not expected_checksum:
print(digest) # Expected checksum for the instructor to copy-paste
return total_time
elif not crashed and digest[:len(expected_checksum)] == expected_checksum:
print(f"Success in {total_time:.3f} seconds.")
return total_time
elif crashed:
return -1
else:
print("CHECKSUM MISMATCH: AT LEAST ONE ANSWER WAS WRONG.")
print("YOUR FUNCTION HAS SOME EDGE CASE BUG THAT DID NOT MANIFEST")
print(f"IN THE FIRST {testcase_cutoff} TEST CASES. IF YOU CAN'T FIND THIS")
print("BUG AFTER SLEEPING OVER IT ONCE, PLEASE SEND YOUR FUNCTION")
print("TO [email protected] TO HELP IMPROVE THE QUALITY OF")
print(f"THESE AUTOMATED TEST CASES. ENSURE THAT YOUR {function_name}")
print("DOES NOT USE ANY FLOATING POINT CALCULATIONS WHOSE PRECISION")
print("RUNS OUT ONCE THE NUMBERS INVOLVED BECOME LARGE ENOUGH.")
return -1
else:
print(f"({output_len}) ", end='')
return 0
# Sort the suite of test cases according to the order in which
# they appear in the student source code.
def sort_by_source():
funcs, recognized = dict(), set(f for (f, _, _) in testcases)
need_check = [f for (f, test, check) in testcases if check is None]
with open('labs109.py', 'r', encoding='utf-8') as source:
for (line_no, line) in enumerate(source):
if line.startswith("def "):
function_name = line[4:line.find('(')].strip()
if function_name in funcs: # Who knows how many future students this will save.
print(f"WARNING: MULTIPLE DEFINITION FOR {function_name}")
if function_name in recognized:
funcs[function_name] = 0 if function_name in verbose_execution or function_name in need_check else line_no
testcases.sort(key=lambda x: funcs.get(x[0], 9999999))
return sorted(funcs.keys())
# Runs the tests for all functions in the suite, returning the
# count of how many of those were implemented and passed the test.
def test_all_functions(module, recorder=None, known=None):
if recorder:
print("\nRECORDING THE RESULTS OF INSTRUCTOR MODEL SOLUTIONS.")
print("IF YOU ARE A STUDENT, YOU SHOULD NOT BE SEEING THIS")
print(f"MESSAGE!!! ENSURE THAT THE FILE {expected_answers_file} FROM")
print("WHEREVER YOU DOWNLOADED THIS AUTOMATED TESTER IS ALSO")
print("PROPERLY PLACED IN THIS VERY SAME WORKING DIRECTORY!!!\n")
print(f"Recording {testcase_cutoff} test cases per problem.\n")
accepted_count, total = 0, 0
if recorder:
print(f"{version_prefix}{version}", file=recorder)
for (f_name, test_cases, expected) in testcases:
try:
f = module.__dict__[f_name]
except KeyError:
continue
total += 1
result = test_one_function(f, test_cases, expected, recorder, known)
if result >= 0:
accepted_count += 1
if recorder:
print("\nRecording model answers complete.")
else:
print(f"{accepted_count} out of {total} functions ", end="")
print(f"of {len(testcases)} possible work.")
return accepted_count
# Named constants used by some test case generators.
ups = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lows = "abcdefghijklmnopqrstuvwxyz"
__primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
__names = [
"hu", "oh", "eye", "kro", "atz", "put",
"ross", "rachel", "monica", "phoebe", "joey", "chandler",
"johndorian", "elliot", "turk", "carla", "perry", "bob",
"eddie", "joy", "jeff", "steph", "allison", "doug",
"jules", "ellie", "laurie", "travis", "grayson", "andy",
"donald", "melania", "hillary", "barack", "bill", "kamala",
"mxuzptlk", "ouagadougou", "oumoumou", "auervaara",
"britain", "germany", "france", "canada", "exit",
"urban", "zuauaua", "aueiosh", "knickerbocker",
"keihanaikukauakahihuliheekahaunaele",
"llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch"
]
__knight_moves = [(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)]
# Some utility functions to help writing test generators.
# Produce an infinite sequence of exponentially increasing integers.
# The parameters scale and skip determine how quickly the sequence grows.
def scale_random(seed, scale, skip):
# The seed value determines the future random sequence.
rng = Random(seed)
curr, count_until_increase, orig = 1, 0, scale
while True:
curr += rng.randint(1, scale)
yield curr
count_until_increase += 1
if count_until_increase == skip:
scale = scale * orig
count_until_increase = 0
# Produce a random (n+1)-digit integer with adjustable repeating digits.
def random_int(rng, n, prob=70):
r, curr = 0, rng.randint(1, 9)
for _ in range(n):
r = 10 * r + curr
if rng.randint(0, 99) < prob:
curr = rng.randint(0, 9)
return r
# Create a random n-character string from the given alphabet.
def random_string(alphabet, n, rng):
result = ''
for _ in range(n):
result += rng.choice(alphabet)
return result
# The pyramid series is handy for yielding test case lengths in the
# manner of 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, ...
def pyramid(n=1, goal=5, inc=1):
count_until_increase = 0
while True:
yield n
count_until_increase += 1
if count_until_increase == goal:
goal, count_until_increase, n = goal + inc, 0, n + 1
# XXX Test case generators for the individual functions.
def lehmer_decode_generator(seed):
rng = Random(seed)
for n in islice(pyramid(2, 3, 3), 3000):
inv = [rng.randint(0, n - i) for i in range(n)]
yield inv,
def lehmer_encode_generator(seed):
rng = Random(seed)
for n in range(1, 6):
for p in permutations(range(n)):
yield list(p),
p = list(range(7))
for n in islice(pyramid(7, 2, 2), 2000):
if len(p) < n:
p.append(n - 1)
rng.shuffle(p)
yield p[:],
def loopless_walk_generator(seed):
rng = Random(seed)
for n, p in islice(zip(pyramid(2, 1, 1), cycle([20, 50, 70])), 4000):
steps = []
for _ in range(n):
if len(steps) > 0 and rng.randint(0, 99) < p:
steps.append(rng.choice(steps))
else:
steps.append(rng.choice(lows))
yield "".join(steps)
def square_root_sum_generator(seed):
rng = Random(seed)
for n in islice(pyramid(3, 2, 2), 2000):
n1, n2, d = [], [], rng.randint(0, 1)
for _ in range(n):
p = rng.randint(2, 3 * n) if n1 == [] else max(n1[-1], n2[-1])
p1 = rng.randint(p + 1, p + 4)
p2 = p1 + 1
if d == 0:
n1.append(p1)
n2.append(p2)
else:
n1.append(p2)
n2.append(p1)
d = 1 - d
yield n1, n2
def friendship_paradox_generator(seed):
rng = Random(seed)
for n, p in islice(zip(pyramid(3, 2, 2), cycle([30, 50, 80])), 2000):
friend_set = set()
for i in range(0, n):
friends = set()
while len(friends) < 1 or rng.randint(0, 99) < p:
j = rng.randint(0, n - 1)
if i != j:
friends.add((i, j))
for (i, j) in friends:
friend_set.add((i, j))
friend_set.add((j, i))
friends = [[] for _ in range(n)]
for (i, j) in friend_set:
friends[i].append(j)
yield friends,
def factoradic_base_generator(seed):
for n in range(1, 100):
yield n,
for n in islice(scale_random(seed, 3, 4), 1500):
yield n,
def tchuka_ruma_generator(seed):
rng = Random(seed)
for n in islice(pyramid(3, 5, 6), 150):
board = [0 for _ in range(n)]
for i in range(1, n):
board[i] = rng.randint(0, n)
yield board,
def gauss_circle_generator(seed):
for r in range(1, 2001):
yield r,
def maximal_palindrome_generator(seed):
for digits in ['0', '00', '123', '98', '123123123', '225588770099']:
yield digits,
rng = Random(seed)
for n, p in islice(zip(pyramid(2, 2, 2), cycle([10, 50, 90])), 3000):
digits = []
for d in range(10):
if rng.randint(0, 100) < 40:
m = rng.randint(2, n//2 + 3)
if rng.randint(0, 99) < p and m % 2 == 1:
m += 1
digits.extend(str(d) for _ in range(m))
if digits:
rng.shuffle(digits)
yield "".join(digits),
def ants_on_the_rod_generator(seed):
yield [[1, 1], [2, 1], [3, 1], [4, -1]], 5
rng = Random(seed)
for n in islice(pyramid(2, 2, 3), 3000):
w = rng.randint(2 * n, 3 * n)
ants = [[pos, rng.choice([-1, +1])] for pos in sorted(rng.sample(range(1, w), n))]
yield ants, w
def split_at_none_generator(seed):
rng = Random(seed)
for n, p in islice(zip(pyramid(3, 2, 2), cycle([10, 30, 50])), 4000):
items = [None if rng.randint(0, 99) < p else rng.randint(-3*n, 3*n) for _ in range(n)]
yield items,
def multiply_and_sort_generator(seed):
rng = Random(seed)
for n in range(2, 4000):
for mul in rng.sample(range(2, 13), 3):
yield n, mul
def magic_knight_generator(seed):
rng = Random(seed)
for n in range(5, 300):
if n % 2 != 0 and n % 3 != 0:
items = sorted(rng.sample(range(1, n * n), 5))
items.append(n * n)
yield n, items
def power_prefix_generator(seed):
rng = Random(seed)
p = 1024
for n in islice(pyramid(6, 2, 3), 300):
power = str(p)
prefix = power[:rng.randint(4, min(len(power), n))]
prefix = "".join(d if rng.randint(0, 100) < 70 else '*' for d in prefix)
yield prefix,
p = p * (2 ** rng.randint(2, n))
def pinch_moves_generator(seed):
yield ".BWW.WB", 'B'
yield "RBW.BW", 'W'
rng = Random(seed)
for n in islice(pyramid(8, 10, 10), 500):
board = ""
captured = False
player = rng.choice('BW')
other = 'W' if player == 'B' else 'B'
prev = rng.choice("BW")
while len(board) < n:
move = rng.randint(0, 100)
if move < 20 and not captured:
o1 = rng.randint(1, 3)
o2 = rng.randint(1, 3)
if rng.randint(0, 100) < 70:
board += f"{other * o1}{'R' * rng.randint(1, 2)}{other * o2}"
else:
board += f"{other * o1}{'R' * rng.randint(1, 2)}{other}{'R' * rng.randint(1, 2)}{other * o2}"
captured = True
elif move < 50:
board += '.'
elif move < 80:
board += f".{prev * rng.randint(1, 2)}"
prev = 'B' if prev == 'W' else 'W'
else:
p = rng.randint(0, 2)
o = rng.randint(0, 2)
board += f".{player * p}{other * o}" if rng.randint(0, 100) < 50 else f".{other * o}{player * p}"
yield board, player
def tom_and_jerry_generator(seed):
rng = Random(seed)
for n in islice(pyramid(6, 5, 8), 1500):
edge_set = set()
for u in range(1, n + 1):
for _ in range(rng.randint(1, 3)):
v = rng.randint(max(0, u - n//4), u - 1)
edge_set.add((u, v))
edges = [[] for _ in range(n + 1)]
for (u, v) in edge_set:
edges[u].append(v)
edges[v].append(u)
for u in range(1, n):
if all(v < u for v in edges[u]):
v = rng.randint(u + 1, n)
edges[u].append(v)
edges[v].append(u)
yield n, edges
def cubes_on_trailer_generator(seed):
rng = Random(seed)
for n in islice(pyramid(2, 15, 8), 60):
xs = n
ys = rng.randint(n, n + 2)
zs = rng.randint(2, n + 1)
xy = [[False for _ in range(ys)] for _ in range(xs)]
xz = [[False for _ in range(zs)] for _ in range(xs)]
yz = [[False for _ in range(zs)] for _ in range(ys)]
for x in range(xs):
for y in range(ys):
z = rng.randint(1, zs) if rng.randint(0, 99) < 50 else 0
if z > 0:
xy[x][y] = True
for zz in range(z):
xz[x][zz] = True
yz[y][zz] = True
yield xy, xz, yz,
def powertrain_generator(seed):
rng = Random(seed)
for m in islice(pyramid(2, 4, 5), 5000):
n = int(random_string("123456789", m, rng))
if n != 2592:
yield n,
def complex_base_decode_generator(seed):
# All bit strings up to length 8
yield "0",
yield "1",
for n in range(1, 8):
for bits in product([0, 1], repeat=n):
yield "1" + "".join(str(b) for b in bits),
# The rest with fuzzing
rng = Random(seed)
for n in range(8, 2000):
yield "1" + "".join(str(rng.randint(0, 1)) for _ in range(n)),
def set_splitting_generator(seed):
rng = Random(seed)
for n, w in islice(zip(pyramid(6, 10, 12), pyramid(3, 11, 12)), 2000):
subsets = []
m = rng.randint(n, 2 * n)
while len(subsets) < m:
k = rng.randint(2, w) if rng.randint(0, 99) < 60 else 2
subset = sorted(rng.sample(range(n), k))
if subset not in subsets:
subsets.append(subset)
yield n, subsets
def bandwidth_generator(seed):
yield from islice(__graph_generator(Random(seed)), 70)
def manimix_generator(seed):
for expr in ["[1]", "(2)", "[45]", "[54]", "(19)", "(123456)", "(90)", "[(13)2]", "([13]2)", "[(45)(27)]"]:
yield expr,
rng = Random(seed)
def expr(d, m):
if d == 0:
return rng.choice("0123456789")
else:
inner = "".join([expr(rng.randint(0, d - 1), m) for _ in range(rng.randint(2, m))])
return f"[{inner}]" if rng.randint(0, 99) < 50 else f"({inner})"
for d, m in islice(zip(pyramid(3, 7, 9), pyramid(3, 6, 8)), 200):
yield expr(d, m),
def accumulating_merge_generator(seed):
rng = Random(seed)
for n in islice(pyramid(4, 3, 3), 3000):
items1 = [rng.randint(1, 3*n) for _ in range(rng.randint(1, n))]
items2 = [rng.randint(1, 3*n) for _ in range(rng.randint(1, n))]
yield items1, items2
def string_stretching_generator(seed):
rng = Random(seed)
for n, p in islice(zip(pyramid(3, 4, 5), cycle([20, 40, 60])), 500):
m = rng.randint(2, n)
pattern = rng.choice(lows[:n+1])
repeats = 0
for _ in range(m - 1):
if repeats < 3 and rng.randint(0, 99) < p:
repeats += 1
pattern += rng.choice(pattern)
else:
pattern += rng.choice(lows[:n+1])
text = pattern
for _ in range(rng.randint(1, (n//2) + 1)):
i = rng.randint(0, len(text))
text = text[:i] + pattern + text[i:]
yield text,
def conway_coin_race_generator(seed):
rng = Random(seed)
# Try out explicitly all patterns up to length 4
for n in range(1, 5):
for a in product([0, 1], repeat=n):
a = "".join(str(bit) for bit in a)
for b in product([0, 1], repeat=n):
b = "".join(str(bit) for bit in b)
if a < b:
yield a, b
# Rest with fuzzing
for n in islice(pyramid(5, 3, 3), 2000):
a = "".join([rng.choice(["0", "1"]) for _ in range(n)])
m = rng.randint(3, n)
b = "".join([rng.choice(["0", "1"]) for _ in range(m)])
if b not in a:
yield a, b
def baker_norine_dollar_game_generator(seed):
rng = Random(seed)
for n in islice(pyramid(4, 2, 3), 150):
edge_set = set()
for u in range(1, n):
v = rng.randint(0, u - 1)
edge_set.add((u, v))
edge_set.add((v, u))
m = rng.randint(n, (n*(n-1))//3)
while len(edge_set) < 2 * m:
u = rng.randint(0, n - 1)
v = rng.randint(0, n - 1)
if u != v:
edge_set.add((u, v))
edge_set.add((v, u))
edges = [[] for _ in range(n)]
for (u, v) in edge_set:
edges[u].append(v)
balance = [0 for _ in range(n)]
debt = rng.randint(1, n - 1)
for _ in range(debt):
balance[rng.randint(0, n - 1)] -= 1
no_debt = [u for u in range(n) if balance[u] >= 0]
for _ in range(debt + rng.randint(m, 2*m - n)):
balance[rng.choice(no_debt)] += 1
yield edges, balance
def recaman_generator(seed):
for n in range(1, 1000001):
yield n,
def is_caterpillar_generator(seed):
rng = Random(seed)
for n in islice(pyramid(5, 1, 1), 2000):
edges = [[] for _ in range(n)]
m = rng.randint(2, n - 2)
for u in range(1, m):
edges[u].append(u - 1)
edges[u - 1].append(u)
for u in range(m, n):
if rng.randint(0, 99) < 80:
v = rng.randint(0, m - 1)
else:
v = rng.randint(0, u - 1)
edges[u].append(v)
edges[v].append(u)
perm = list(range(n))
rng.shuffle(perm)
inv = [0 for _ in range(n)]
for (i, e) in enumerate(perm):
inv[e] = i
edges = [[perm[v] for v in edges[inv[u]]] for u in range(n)]
while rng.randint(0, 99) < 20:
if rng.randint(0, 99) < 80:
u = rng.randint(0, n - 1)
v = rng.randint(0, n - 1)
if u != v and v not in edges[u]:
edges[u].append(v)
edges[v].append(u)
else:
u = rng.randint(0, n - 1)
if len(edges[u]) > 0:
v = rng.choice(edges[u])
edges[u].remove(v)
edges[v].remove(u)
for e in edges:
e.sort()
yield edges,
def sneaking_generator(seed):
def choose():
x = rng.randint(0, n - 1)
y = rng.randint(0, n - 1)
while (x, y) in knights:
x = rng.randint(0, n - 1)
y = rng.randint(0, n - 1)
return (x, y)
rng = Random(seed)
for n in islice(pyramid(4, 6, 7), 100):
knights = set()
m = rng.randint(n // 2, n + 1)
while len(knights) < m:
x = rng.randint(0, n - 1)
y = rng.randint(0, n - 1)
knights.add((x, y))
(gx, gy) = choose()
while True:
(kx, ky) = choose()
is_ok = True
for (xx, yy) in knights:
for (dx, dy) in __knight_moves:
if (kx, ky) == (xx + dx, yy + dy):
is_ok = False
break
if not is_ok:
break
if is_ok:
yield n, (kx, ky), (gx, gy), list(knights)
break
def first_fit_bin_packing_generator(seed):
rng = Random(seed)
for n in islice(pyramid(2, 1, 1), 3000):
items = [rng.randint(1, 2*n) for _ in range(n)]
m = max(items)
capacity = rng.randint(m, 3 * m)
yield items, capacity
def word_bin_packing_generator(seed):
rng = Random(seed)
with open('words_sorted.txt', 'r', encoding='utf-8') as f:
words = [w.strip() for w in f if len(w) == 5]
for n in islice(pyramid(3, 1, 1), 250):
yield rng.sample(words, n),
def word_positions_generator(seed):
yield 'Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo', 'buffalo'
yield 'James while John had had had had had had had had had had had a better effect on the teacher', 'had'
yield 'That that is is that that is not is not is that it it is', 'that'
yield 'That that is is that that is not is not is that it it is', 'is'
rng = Random(seed)
words = [random_string(ups + lows, rng.randint(1, 10), rng) for _ in range(100)]
for n, p in islice(zip(pyramid(2, 1, 1), cycle([20, 50, 80])), 2000):
sentence = []
for i in range(n):
if i > 0 and rng.randint(0, 99) < p:
sentence.append(rng.choice(sentence))
else:
sentence.append(rng.choice(words))
yield " ".join(sentence), rng.choice(sentence)
def __graph_generator(rng):
for n, w in zip(pyramid(5, 2, 1), cycle(range(3, 8))):
edge_set = set()
m = 2 * rng.randint(n, 2*n)
while len(edge_set) < m:
u = rng.randint(0, n - 1)
s = rng.randint(1, w)
s = s * rng.choice([-1, +1])
v = (u + s) % n
if u != v:
edge_set.add((u, v))
edge_set.add((v, u))
edges = [[] for _ in range(n)]
for (u, v) in edge_set:
edges[u].append(v)
yield edges,
def independent_dominating_set_generator(seed):
yield from islice(__graph_generator(Random(seed)), 200)
def vertex_cover_generator(seed):
yield from islice(__graph_generator(Random(seed)), 800)
def spiral_matrix_generator(seed):
rng = Random(seed)
# Try all positions of all spiral matrices up to size 5 systematically
for n in range(1, 6):
for row in range(n):
for col in range(n):
yield n, row, col
# Rest with random fuzzing
for n in range(6, 500):
for _ in range(n//2):
row = rng.randint(0, n - 1)
col = rng.randint(0, n - 1)
yield n, row, col
def unity_partition_generator(seed):
for n in range(78, 200):
yield n,
def jai_alai_generator(seed):
rng = Random(seed)
yield 2, 'WLWL'
yield 2, 'LLLLLL'
yield 4, 'WWWWWWWWW'
for n, m, p in islice(zip(pyramid(3, 15, 20), pyramid(4, 2, 2), cycle([30, 40, 50])), 2000):
results = [rng.choice('WL')]
for _ in range(m):
result = results[-1] if rng.randint(0, 99) < p else rng.choice('WL')
results.append(result)
yield n, "".join(results)
def __random_frac(rng, p):
if rng.randint(0, 99) < p:
den = rng.randint(2, 10)
num = rng.randint(1, den)
return F(num, den)
else:
den = rng.randint(10, 100)
num = rng.randint(den // 2, den)
return F(num, den)
def tic_tac_generator(seed):
rng = Random(seed)
for p in islice(cycle([10, 20, 30, 40]), 100):
board = [['.', '.', '.'], ['.', '.', '.'], ['.', '.', '.']]
probs = [[__random_frac(rng, p) for _ in range(3)] for _ in range(3)]
for _ in range(rng.randint(6, 8)):
row = rng.randint(0, 2)
col = rng.randint(0, 2)
mark = rng.choice("XO")
board[row][col] = mark
yield board[:], 'X', probs
yield board[:], 'O', probs
def lowest_fraction_between_generator(seed):
rng = Random(seed)
for n in islice(pyramid(3, 1, 1), 3000):
a = rng.randint(1, 3*n)
b = n
if rng.randint(0, 99) < 50:
c = rng.randint(1, n)
d = rng.randint(n+1, n*n)
else:
c = rng.randint(a, a+2)
d = rng.randint(b-1, b+1)
first = F(a, b)
second = first + F(c, d)
first, second = min(first, second), max(first, second)
yield first, second
def lamp_pairs_generator(seed):
rng = Random(seed)
for n in islice(pyramid(2, 1, 1), 500):
lamps = "".join([rng.choice("01") for _ in range(n)])
if lamps.count('0') % 2 == 1:
lamps += '0'
yield lamps,
def count_friday_13s_generator(seed):
rng = Random(seed)
days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def random_date(n):
year = 2024 + rng.randint(-n, n)
month = rng.randint(1, 12)
is_leap_year = year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
if rng.randint(0, 99) < 20:
day = rng.randint(12, 14)
elif month == 2 and is_leap_year:
day = rng.randint(1, 29)
else:
day = rng.randint(1, days_in_month[month])
return date(year, month, day)
for n in islice(pyramid(1, 2, 2), 3000):
start = random_date(n)
end = random_date(n)
yield (start, end) if start <= end else (end, start)
def twos_and_threes_generator(seed):
for n in islice(scale_random(seed, 2, 2), 600):
yield n,
def infected_cells_generator(seed):
yield [(0, 0), (1, 1), (1, 3), (3, 2)],
rng = Random(seed)
for n in islice(pyramid(2, 2, 2), 2000):
infected = set()
x = rng.randint(-n, n)
y = rng.randint(-n, n)
while len(infected) < n:
infected.add((x, y))
if rng.randint(0, 99) < 20:
x = rng.randint(-n, n)
y = rng.randint(-n, n)
else:
x += rng.choice([-2, -1, -1, 0, 1, 1, 2])
y += rng.choice([-2, -1, -1, 0, 1, 1, 2])
yield list(infected),
def knight_jam_generator(seed):
rng = Random(seed)
for n in islice(pyramid(2, 5, 6), 100):
knights = set()
while len(knights) < n:
x = rng.randint(0, 2 + n // 2)
y = rng.randint(0, 2 + n // 2)
knights.add((x, y))
yield knights, rng.randint(0, 1)
def arithmetic_skip_generator(seed):
rng = Random(seed)
for n in range(6000):
yield rng.choice([-n, n]),
def trip_flip_generator(seed):
rng = Random(seed)
for n in islice(pyramid(5, 5, 6), 1300):
yield [rng.randint(0, 3) for _ in range(n)],
def square_lamps_generator(seed):
rng = Random(seed)
for n in islice(pyramid(3, 2, 2), 3000):
flips = []
for _ in range(rng.randint(n, 3*n)):
i = rng.randint(1, n)
sign = rng.choice([-1, 1])
flips.append(i * sign)
yield n, flips
def lychrel_generator(seed):
for n, giveup in zip(range(100, 20000), pyramid(100, 5, 5)):
yield n, giveup
def condorcet_election_generator(seed):
rng = Random(seed)
for c, n in islice(zip(pyramid(2, 5, 7 ), pyramid(1, 1, 1)), 800):
ballot = rng.sample(range(c), c)
ballots = []
while len(ballots) < n:
ballots.append(ballot[:])
for _ in range(rng.randint(0, 3)):
i = rng.randint(0, c-1)
j = rng.randint(0, c-1)
ballot[i], ballot[j] = ballot[j], ballot[i]
yield ballots,
def nfa_generator(seed):
rng = Random(seed)