diff --git a/LICENSE.md b/LICENSE.md index 456ee2faedb2514e72a6d3c735adb745dc943146..a2d0276c6a0bac19a7690ca901f7c39418e8950a 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -2,8 +2,10 @@ This collection repackages tasks from several sources. Each row's `license` column gives the license of its source: -- MIT: RLVE-Gym, NPPC, EinsteinArena (platform and baselines) -- CC-BY-4.0: MathConstraint; AlphaEvolve repository of problems (materials) -- Apache-2.0: Reasoning Gym, FunSearch, AlphaEvolve repository of problems (code), Finch / Evolution Fine-Tuning (code) +- MIT: RLVE-Gym, NPPC, EinsteinArena (platform and baselines), Leaps in Bounds (D. Munro), FrontierCO, FrontierCS +- CC-BY-4.0: MathConstraint; AlphaEvolve repository of problems (materials); EdgeBench (task directories; the underlying AtCoder problem statements remain © AtCoder) +- Apache-2.0: Reasoning Gym, FunSearch, AlphaEvolve repository of problems (code), Finch / Evolution Fine-Tuning (code), Optimization Constants in Mathematics (T. Tao, D. Davis, P. Ivanisvili et al.) +- **CC-BY-ND-4.0 (restricted): ALE-Bench (Sakana AI; AtCoder Heuristic Contest problems).** No derivatives: statements are reproduced verbatim; do not redistribute modified versions of these tasks without checking compatibility. Tagged `license_restricted`. +- **unknown: FrontierShift open problems (AItonomy Foundation).** The public registry states no license and its repository is not public. Tagged `license_unknown`. Please attribute the original authors when using the corresponding tasks. diff --git a/README.md b/README.md index 44db126ecd89e85e34fb3d5a0d129672fc8feae4..66a5ca817e3c69a6afa41ee07b4c493bf0e2c39c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ --- license: other -license_name: mixed-permissive +license_name: mixed license_link: LICENSE.md configs: - config_name: construct @@ -19,14 +19,14 @@ size_categories: # MathConstructOptimize-Envs -**3,577 RL tasks in 142 families where the model must *construct a mathematical object*, graded by a deterministic checker.** There is no answer matching and no LLM judge in the reward path. +**3,793 RL tasks in 219 families where the model must *construct a mathematical object*, graded by a deterministic checker.** There is no answer matching and no LLM judge in the reward path. Most math RL data asks for a final number. Here the model has to produce the object itself: a colouring, a design, a counterexample, a point configuration, a polynomial. The checker accepts **any** valid object, not a stored answer. The collection has two subsets: | subset | what the model does | reward | families | tasks | |---|---|---|---|---| | `construct` | produce any object satisfying stated conditions (a witness) | 1 if valid, else 0 | 80 | 3,464 | -| `optimize` | produce a valid object with the best objective it can (extremal constructions, bound improvement) | 0 if invalid; otherwise 0.1 + 0.9 × progress from a trivial baseline to the best known value | 62 | 113 | +| `optimize` | produce a valid object with the best objective it can (extremal constructions, bound improvement) | 0 if invalid; otherwise 0.1 + 0.9 × progress from a trivial baseline to the best known value | 139 | 329 | The runnable sandboxed version (one [Harbor](https://github.com/laude-institute/harbor) task directory per row) is in [`amphora/MathConstructOptimize-Envs-harbor`](https://huggingface.co/datasets/amphora/MathConstructOptimize-Envs-harbor). @@ -41,12 +41,19 @@ Tasks are converted from existing generator suites and research-problem reposito | [MathConstraint](https://github.com/vireshpati/Math-Constraint) | construct | competition | 33 | 875 | | [NPPC](https://github.com/SMU-DIGA/nppc) | construct | competition | 8 | 480 | | [Reasoning Gym](https://github.com/open-thought/reasoning-gym) | construct | competition | 3 | 180 | -| [AlphaEvolve repository of problems](https://github.com/google-deepmind/alphaevolve_repository_of_problems) | construct + optimize | research (mostly) | 27 | 187 | +| [AlphaEvolve repository of problems](https://github.com/google-deepmind/alphaevolve_repository_of_problems) | construct + optimize | research (mostly) | 34 | 203 | | [EinsteinArena](https://einsteinarena.com) | optimize | research | 26 | 28 | | [FunSearch](https://github.com/google-deepmind/funsearch) | optimize | research | 3 | 15 | | [Finch / Evolution Fine-Tuning](https://github.com/Open-Galapagos/evolution-fine-tuning) (`erdos_*` tasks) | optimize | research / competition | 12 | 12 | +| [Optimization Constants in Mathematics](https://github.com/teorth/optimizationproblems) (Tao, Davis, Ivanisvili) | optimize | research | 13 | 17 | +| [Leaps in Bounds](https://leapsinbounds.org) (D. Munro) | optimize | research | 14 | 82 | +| [FrontierShift open problems](https://aitonomy.org/projects/open-problems) (AItonomy Foundation) | optimize | research | 8 | 9 | +| [FrontierCO](https://huggingface.co/datasets/CO-Bench/FrontierCO) (minimum dominating set only) | optimize | competition | 1 | 15 | +| [ALE-Bench](https://huggingface.co/datasets/SakanaAI/ALE-Bench) (AtCoder Heuristic Contest) | optimize | competition | 18 | 36 | +| [FrontierCS](https://github.com/FrontierCS/Frontier-CS) (algorithmic track) | optimize | competition | 14 | 37 | +| [EdgeBench](https://github.com/ByteDance-Seed/EdgeBench) (released task dirs) | optimize | competition | 2 | 4 | -Construct generators have 4–6 difficulty levels × 10 seeds. Optimize tasks are single research problems, some at several sizes *n*. `families.csv` lists every family with its source, license, domain, `problem_key` and tags. +Construct generators have 4–6 difficulty levels × 10 seeds. Optimize tasks are single research problems or contest instances, some at several sizes *n*. Sources added in v2 (2026-11-18) are described in the v2 section below. `families.csv` lists every family with its source, license, domain, `problem_key` and tags. ## Row schema @@ -92,6 +99,11 @@ The **optimize reward** is `0` for an invalid answer, else `0.1 + 0.9 · clip(pr | `ea_under_review` | EinsteinArena marks the problem as under review. We audited each one and included it only when we could make the check sound | | `unique_answer` | the answer is unique, but it is still verified as a witness (e.g. by expanding a factorization) | | `float_objective`, `exact_integer`, `exact_rational`, ... | how the objective is computed | +| `reference_is_baseline` / `reference_below_record` | the shipped `reference_answer` is the weak baseline (reward 0.1) or a valid construction weaker than `best_known` | +| `known_optimum` | `best_known` is a proved optimum, so the reward cannot exceed 1 by improving it | +| `record_memorizable` | the record object is famous; an agent that recalls it saturates the reward | +| `license_restricted` | source license restricts derivatives (ALE-Bench, CC BY-ND 4.0) | +| `license_unknown` | the source states no license (FrontierShift) | ## Reference pass rates (pilot, 66 tasks) @@ -135,9 +147,37 @@ Re-implementing the checkers surfaced problems in the source verifiers that an R - AlphaEvolve problem 6: the notebook's functional differs from the one a construction-checker can certify. - Problems with no checkable objective (proof-only or meta problems), or no recoverable construction or verifier. - FunSearch corner-free sets (checker not released). -- Sources without a license. +- Sources without a license (v1). v2 includes FrontierShift, which states no license, tagged `license_unknown`. - Duplicate problem and size pairs across sources (deduplicated by `problem_key`). +## v2 (2026-11-18): optimize extension + +216 new optimize tasks in 77 families (the `construct` subset is unchanged; the previous version is git tag `pre-v2`). Same reward contract and graders interface; every reference answer was re-graded in an isolated copy of the task's `tests/` dir, through `grade.py`, and by the Harbor oracle agent in the sandbox image; a no-op answer scores 0 everywhere. All checks run in under 10 s. + +| source | families | tasks | license | notes | +|---|---|---|---|---| +| Optimization Constants in Mathematics | 13 | 17 | Apache-2.0 | one family per constant where a finite object certifies a bound (Lehmer/Mahler measure, degree vs sensitivity, Komlós discrepancy, matrix-multiplication exponent from exact small-format algorithms, biplanar chromatic number, Bohnenblust–Hille, Berry–Esseen, Brezis–Gallouet–Wainger, sunflower-free families, Fourier entropy–influence, hollow lattice width, narrowest admissible tuples, covering systems) | +| AlphaEvolve repository (new problems/sizes) | 7 | 16 | CC-BY-4.0 | 2D Nikodym over F_{p²}, Hausdorff–Young, Thomson n=292/306, hexagons in a hexagon, Erdős discrepancy C=3, Szemerédi–Trotter incidences, Rudin L4/L2 spherical harmonics | +| Leaps in Bounds | 14 | 82 | MIT | cages, degree–diameter, superpermutations, snake/coil-in-the-box, Golomb rulers, no-three-in-line, sorting-network size/depth, equal circles in a square/triangle, isosceles sets, unit squares in a square, disk covering | +| FrontierShift | 8 | 9 | **unknown** | matrix-multiplication rank 3×3/4×4 over Q, max-determinant ±1 23×23, Boolean nonlinearity n=9, low-weight codeword (decoding challenge n=1280), abc quality, Cramér–Shanks–Granville gap ratio, rational Diophantine septuples, tetrahedra packing density | +| FrontierCO | 1 | 15 | MIT | minimum dominating set only (the other 7 types overlap CO-Bench) | +| ALE-Bench | 18 | 36 | **CC BY-ND 4.0** | non-interactive AtCoder Heuristic Contest problems, 2 public-seed instances each; statements kept verbatim; scorers re-implemented in Python and matched against the official tools on ~7,700 outputs | +| FrontierCS | 14 | 37 | MIT | algorithmic-track problems with deterministic scorers (Max-Cut, Max-3-SAT, Zarankiewicz grids, XOR-Sidon sets, ...); each port matched the upstream checker on ≥100 outputs | +| EdgeBench | 2 | 4 | CC-BY-4.0 | the two released task directories that run offline (AHC056, AHC058) | + +**License caveats.** ALE-Bench is CC BY-ND 4.0 (no derivatives): its statements are reproduced verbatim and its tasks carry `license_restricted`; check that your use is compatible before redistributing modified versions. FrontierShift states no license (its repository is not public); those tasks carry `license_unknown`. AtCoder problem statements (ALE-Bench, EdgeBench) remain © AtCoder. + +**`best_known` provenance.** Values are the published records where available (cited in `tests/instance.json` → `best_known_source`, hidden from the agent). For contest instances and several FrontierCS/ALE problems no per-instance record is published, so `best_known` is our own best solution (tag `best_known_uncertain`); agents can beat it and the reward clips at 1. + +**Excluded in v2.** Anything overlapping the problem families of HorizonMath, HeuriGym or CO-Bench is left out at every size (e.g. Ramsey/Schur/van der Waerden colourings, kissing numbers, Tammes, spherical designs, difference bases, merit factor, codes and covering designs, Hadamard matrices, sphere packing, TSP/routing, scheduling, bin/rectangle/circle-unequal packing, facility location, set cover, graph colouring, MIS). Also skipped: constants whose certificate is a proof rather than an object, interactive or program-output problems, problems needing a GPU/network/hardware, and problems whose verifier could not be made sound and fast. + +**Upstream verifier bugs found in v2 sources** (all fixed in our checkers): +- AlphaEvolve p6 scores a different functional than stated; p13 never checks f̂ ≥ 0; p14 truncates the Fourier integral; p33 clamps coincident points to distance 1e-12; the hexagon-packing outer side is taken as input, not computed; p40 scores the longest valid prefix plus a bonus; p55's sample layout overlaps; p56 silently drops duplicate lines; p57 drops coefficients below 1e-8. +- EdgeBench AHC058: the eval script reads any `Score = …` line, so a submission can forge the score. +- FrontierCS 58/8 compare counts only modulo primes; 192/176 ignore trailing tokens; 227 has no range check; 111 and 27 accept empty answers; 193 is a re-encoding of 192. +- FrontierCO MDS accepts `3.0`/`True` as node ids. +- ALE-Bench tools: ahc014 turn count wrong, ahc004 panics on Unicode whitespace, ahc024/041 accept an empty output at turn 0. + ## License -Each row carries the license of its source (`license` column): MIT (64 families), CC-BY-4.0 (59), Apache-2.0 (19). Attribution belongs to the original authors of each source listed above. Our packaging, checkers and generators are released under the same terms as the corresponding source. +Each row carries the license of its source (`license` column): MIT (93 families), CC-BY-4.0 (68), Apache-2.0 (32), CC-BY-ND-4.0 (18, ALE-Bench), unknown (8, FrontierShift). Attribution belongs to the original authors of each source listed above. Our packaging, checkers and generators are released under the same terms as the corresponding source. diff --git a/data/optimize.parquet b/data/optimize.parquet index 02156e5dacb7f8c2ed5e17e7fe2938c33478901c..a934cb248811c46f9d8d5aa41906cf6510678c2d 100644 --- a/data/optimize.parquet +++ b/data/optimize.parquet @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:d3c912b1d13d289de6b85cc381ecb0f5d13b55d4ec8cc5b8df8e0ec6d0da171c -size 1949811 +oid sha256:8056bade5c94873af4cbda5787fbc025d9e42638d36f8367e512c78f6ef6f689 +size 11690357 diff --git a/families.csv b/families.csv index 3875c156bf33d0282c91e0fc64277db963691396..ac12f98eeef9e6088f87d48bc1da8e2eb3f5925f 100644 --- a/families.csv +++ b/families.csv @@ -1,143 +1,220 @@ -family,subset,tier,domain,source,license,problem_key,n_tasks,tags -ae_p10_kakeya_3d,optimize,research,geometry,AlphaEvolve-Repository-of-Problems/10-3d-kakeya,CC-BY-4.0,kakeya_needle_3d_prisms,1,exact_piecewise_integration;float_objective -ae_p16_gagliardo_nirenberg,optimize,research,analysis,AlphaEvolve-Repository-of-Problems/16-gagliardo-nirenberg-special-case,CC-BY-4.0,nagy_gagliardo_nirenberg_sharp_constant,3,float_objective;known_optimum -ae_p17_young_convolution,optimize,research,analysis,AlphaEvolve-Repository-of-Problems/17-young-convolution,CC-BY-4.0,young_convolution_sharp_constant,3,float_objective;known_optimum -ae_p18_hardy_littlewood_maximal,optimize,research,analysis,AlphaEvolve-Repository-of-Problems/18-hardy-littlewood-maximal,CC-BY-4.0,centered_hardy_littlewood_weak11_constant_1d,1,exact_rational;known_optimum -ae_p1_ff_kakeya,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/1-finite-field-kakeya,CC-BY-4.0,finite_field_kakeya_min_size,10,exact_integer;finite_fields -ae_p1_ff_nikodym,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/1-finite-field-nikodym,CC-BY-4.0,finite_field_nikodym_min_size_d3,4,exact_integer;finite_fields -ae_p24_de_bruijn_sharma,optimize,research,analysis,AlphaEvolve-Repository-of-Problems/24-de-bruijn-sharma,CC-BY-4.0,de_bruijn_sharma_x_intercept,4,float_objective;polynomials -ae_p29_block_stacking,optimize,competition,analysis,AlphaEvolve-Repository-of-Problems/29-block-stacking,CC-BY-4.0,block_stacking_overhang_one_per_level,3,agentic_trivial;exact_rational;known_optimum -ae_p30_arithmetic_kakeya,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/30-arithmetic-kakeya,CC-BY-4.0,arithmetic_kakeya_entropy_sum_difference,2,additive_combinatorics;entropy;float_objective -ae_p31_furstenberg_sarkozy,optimize,research,number_theory,AlphaEvolve-Repository-of-Problems/31-furstenberg-sarkozy,CC-BY-4.0,furstenberg_sarkozy_modular_exponent,2,additive_combinatorics;exact_integer -ae_p32_spherical_designs,construct,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/32-spherical-designs,CC-BY-4.0,spherical_t_design_s2,6,float_tolerance;numerical_design -ae_p35_cubes_in_cube,optimize,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/35-packing-in-a-dilate,CC-BY-4.0,unit_cubes_in_smallest_cube_n11,1,float_objective;packing -ae_p37_turan_tetrahedron,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/37-hypergraph-turan-tetrahedron,CC-BY-4.0,turan_density_K4_3,1,blow_up;extremal_hypergraph -ae_p38_factorial_factors,construct,research,number_theory,AlphaEvolve-Repository-of-Problems/38-factoring-N-factorial,CC-BY-4.0,factorial_into_n_large_factors_A034258,60,agentic_trivial;exact_integer;ilp_friendly;np_search -ae_p39_beat_the_average,optimize,research,probability,AlphaEvolve-Repository-of-Problems/39-beat-the-average,CC-BY-4.0,beat_the_average_X1X2X3_lt_2X4,1,discrete_measure;float_objective -ae_p40_erdos_discrepancy,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/40-erdos-discrepancy,CC-BY-4.0,erdos_discrepancy_C2_max_length,1,exact_integer;np_search;sat_friendly -ae_p41_sphere_max_volume,optimize,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/41-points-on-sphere-max-volume,CC-BY-4.0,max_volume_inscribed_polyhedron_n_vertices,7,float_objective -ae_p42_sum_difference_i,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/42-sum-difference-I,CC-BY-4.0,sum_difference_sumset_vs_diffset_exponent,1,additive_combinatorics;exact_integer -ae_p43_sum_difference_ii,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/43-sum-difference-II,CC-BY-4.0,sum_difference_diffset_vs_sumset_exponent,1,additive_combinatorics;exact_integer -ae_p44_sum_difference_iii,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/44-sum-difference-III,CC-BY-4.0,sum_difference_A_plus_B_vs_A_minus_B_exponent,1,additive_combinatorics;exact_integer -ae_p45_sum_product_fp,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/45-sum-product-finite-field,Apache-2.0,finite_field_sum_product_sqrt_p,3,additive_combinatorics;exact_integer -ae_p52_erdos_squarefree,construct,research,number_theory,AlphaEvolve-Repository-of-Problems/52-erdos-squarefree,CC-BY-4.0,erdos_ab_plus_1_never_squarefree,50,exact_integer -ae_p54_touching_cylinders,construct,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/54-pairwise-touching-cylinders,CC-BY-4.0,mutually_touching_infinite_cylinders,2,float_tolerance;nonlinear_system -ae_p58_happy_ending,construct,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/58-erdos-szekeres-happy-ending,CC-BY-4.0,erdos_szekeres_no_convex_k_gon_2pow_k_minus_2,5,exact_integer;np_search -ae_p59_isosceles_free_grid,optimize,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/59-no-isosceles-grid,CC-BY-4.0,isosceles_free_grid_subset,2,exact_integer;np_search -ae_p60_no5_on_sphere,optimize,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/60-no-5-on-a-sphere,CC-BY-4.0,no_five_cospherical_grid_subset,6,exact_integer;np_search -ae_p65_imo2025_p6_tiling,construct,competition,combinatorics,AlphaEvolve-Repository-of-Problems/65-imo-2025-p6,CC-BY-4.0,imo2025_p6_min_tiles,6,exact_integer -ea_circle_packing_26,optimize,research,discrete_geometry,EinsteinArena/circle-packing,MIT,circle_packing_square_sum_radii_n26,1,exact_check;float_objective -ea_circles_rectangle_21,optimize,research,discrete_geometry,EinsteinArena/circles-rectangle,MIT,circles_in_rectangle_perimeter4_sum_radii_n21,1,exact_check;float_objective -ea_difference_bases,optimize,research,number_theory,EinsteinArena/difference-bases,MIT,difference_basis_ratio,1,exact_check -ea_edges_vs_triangles,optimize,research,combinatorics,EinsteinArena/edges-vs-triangles,MIT,edges_vs_triangles_density_curve,1,float_objective -ea_erdos_min_overlap,optimize,research,analysis,EinsteinArena/erdos-min-overlap,MIT,erdos_minimum_overlap_upper,1,float_objective -ea_first_autocorrelation,optimize,research,analysis,EinsteinArena/first-autocorrelation-inequality,MIT,first_autocorrelation_inequality_upper,1,float_objective -ea_flat_polynomials_70,optimize,research,analysis,EinsteinArena/flat-polynomials,MIT,flat_littlewood_polynomial_n70,1,float_objective -ea_hadamard_det_51,optimize,research,combinatorics,EinsteinArena/hadamard-det-51,MIT,hadamard_maxdet_n51,1,ea_under_review;exact_check -ea_heilbronn_triangle_11,optimize,research,discrete_geometry,EinsteinArena/heilbronn-triangles,MIT,heilbronn_triangle_n11,1,exact_check;float_objective -ea_kakeya_needle_128,optimize,research,geometry,EinsteinArena/kakeya-needle-128,MIT,kakeya_needle_triangles_n128,1,ea_under_review;exact_check -ea_kissing_number,optimize,research,discrete_geometry,"EinsteinArena/kissing-number-d11,-d11-605,-d12",MIT,kissing_number_overlap_loss,3,best_known_uncertain;exact_check -ea_min_distance_ratio_16,optimize,research,discrete_geometry,EinsteinArena/min-distance-ratio-2d,MIT,max_min_distance_ratio_2d_n16,1,float_objective -ea_no_three_in_line_75,optimize,research,discrete_geometry,EinsteinArena/no-three-in-line-75,MIT,no_three_in_line_n75,1,ea_under_review;exact_check -ea_prime_number_theorem,optimize,research,number_theory,EinsteinArena/prime-number-theorem,MIT,pnt_chebyshev_certificate,1,float_objective;range_limited_certificate -ea_ring_loading_15,optimize,research,combinatorics,EinsteinArena/ring-loading-15,MIT,ring_loading_m15,1,ea_under_review;exact_check -ea_second_autocorrelation,optimize,research,analysis,EinsteinArena/second-autocorrelation-inequality,MIT,second_autocorrelation_inequality_lower,1,float_objective -ea_shannon_c7_5,optimize,research,graph_theory,EinsteinArena/shannon-capacity-c7-5,MIT,independent_set_c7_strong_power5,1,ea_under_review;exact_check -ea_sidon_45_set,optimize,research,number_theory,EinsteinArena/sidon-45-set,MIT,sidon_subsets_of_45_sets,1,ea_under_review;exact_check -ea_snake_in_the_box_13,optimize,research,graph_theory,EinsteinArena/snake-in-the-box-13,MIT,snake_in_the_box_d13,1,ea_under_review;exact_check -ea_sorting_network_16,optimize,research,combinatorics,EinsteinArena/sorting-network-16,MIT,sorting_network_size_n16,1,ea_under_review;exact_check -ea_spencer_discrepancy,optimize,research,combinatorics,EinsteinArena/spencer-discrepancy,MIT,spencer_discrepancy_square_n_le20,1,ea_under_review;exact_check -ea_tammes,optimize,research,discrete_geometry,EinsteinArena/tammes-problem,MIT,tammes_n50,1,float_objective -ea_third_autocorrelation,optimize,research,analysis,EinsteinArena/third-autocorrelation-inequality,MIT,third_autocorrelation_inequality_upper,1,float_objective -ea_thomson_282,optimize,research,discrete_geometry,EinsteinArena/thomson-problem,MIT,thomson_problem_n282,1,float_objective -ea_two_deletion_code_16,optimize,research,coding_theory,EinsteinArena/two-deletion-code-16,MIT,two_deletion_code_n16,1,ea_under_review;exact_check -ea_uncertainty_principle,optimize,research,analysis,EinsteinArena/uncertainty-principle,MIT,plus1_uncertainty_principle_upper,1,high_precision -finch_3ap_diffs_40,optimize,research,combinatorics,Finch-EFT/skydiscover/erdos_1097_3ap_diffs_n40,Apache-2.0,erdos1097_3ap_differences_n40_m400,1,best_known_uncertain;exact_check;np_search -finch_4subset_3dist_16,optimize,research,discrete_geometry,Finch-EFT/skydiscover/erdos_659_4subset_3dist_construction,Apache-2.0,erdos659_4sets_3dist_n16,1,best_known_uncertain;exact_check;np_search -finch_flat_poly_32,optimize,research,analysis,Finch-EFT/skydiscover/erdos_flat_polynomials_n32,Apache-2.0,flat_littlewood_polynomial_n32,1,best_known_uncertain;float_objective;np_search -finch_heilbronn_disk_12,optimize,research,discrete_geometry,Finch-EFT/skydiscover/erdos_507_heilbronn_disk_n12,Apache-2.0,heilbronn_disk_n12,1,best_known_uncertain;exact_check;float_objective -finch_isosceles_free_grid_8,optimize,competition,discrete_geometry,Finch-EFT/skydiscover/erdos_isosceles_free_grid,Apache-2.0,isosceles_free_grid_subset,1,exact_check;exact_optimum_known;np_search -finch_lcm_chain_10000,optimize,competition,number_theory,Finch-EFT/skydiscover/erdos_440_lcm_density,Apache-2.0,erdos440_lcm_consecutive_x10000,1,exact_check;exact_optimum_known -finch_newman_200,optimize,research,number_theory,Finch-EFT/skydiscover/erdos_480_newman_density,Apache-2.0,erdos480_newman_finite_n200,1,best_known_uncertain;float_objective -finch_no4_concyclic_12,optimize,research,discrete_geometry,Finch-EFT/skydiscover/erdos_654_no_four_concyclic_distances,Apache-2.0,erdos654_no4_concyclic_n12,1,best_known_uncertain;exact_check;np_search -finch_sidon_pair_100,optimize,research,number_theory,Finch-EFT/skydiscover/erdos_43_sidon_pair,Apache-2.0,erdos43_sidon_pair_n100,1,best_known_uncertain;exact_check;np_search -finch_sidon_set_121,optimize,competition,number_theory,Finch-EFT/skydiscover/erdos_difference_bases_N121,Apache-2.0,max_sidon_set_0_120,1,exact_check;exact_optimum_known -finch_square_packing_12,optimize,research,discrete_geometry,Finch-EFT/skydiscover/erdos_106_square_packing,Apache-2.0,erdos106_squares_in_square_n12,1,exact_check -finch_udg_girth_30,optimize,research,graph_theory,Finch-EFT/skydiscover/erdos_705_unit_distance_high_girth,Apache-2.0,erdos705_udg_chi4_girth_n30,1,best_known_uncertain;exact_check -fs_admissible_set,optimize,research,combinatorics,FunSearch/admissible_set,Apache-2.0,admissible_set_constant_weight,2,integer_objective -fs_cap_set,optimize,research,combinatorics,FunSearch/cap_set,Apache-2.0,cap_set_f3n,6,integer_objective -fs_cycle_independent_set,optimize,research,graph_theory,FunSearch/cyclic_graphs,Apache-2.0,independent_set_strong_power_odd_cycle,7,integer_objective -mc_all_interval,construct,competition,combinatorics,MathConstraint/all_interval,CC-BY-4.0,all_interval_series,40,agentic_trivial -mc_antimagic_square,construct,competition,combinatorics,MathConstraint/antimagic_square,CC-BY-4.0,antimagic_square,6,np_search -mc_bibd,construct,competition,combinatorics,MathConstraint/bibd,CC-BY-4.0,bibd,28,np_search -mc_costas_array,construct,competition,combinatorics,MathConstraint/costas_array,CC-BY-4.0,costas_array,23,np_search -mc_debruijn,construct,competition,combinatorics,MathConstraint/debruijn,CC-BY-4.0,de_bruijn_sequence,22,agentic_trivial -mc_golomb,construct,competition,combinatorics,MathConstraint/golomb,CC-BY-4.0,golomb_ruler,18,np_search -mc_graceful_graph,construct,competition,graph_theory,MathConstraint/graceful_graph,CC-BY-4.0,graceful_labeling,17,np_search -mc_graph_k_coloring,construct,competition,graph_theory,MathConstraint/graph_k_coloring,CC-BY-4.0,graph_k_coloring,48,np_search -mc_hadamard,construct,competition,combinatorics,MathConstraint/hadamard,CC-BY-4.0,legendre_pair,30,np_search -mc_langford,construct,competition,combinatorics,MathConstraint/langford,CC-BY-4.0,langford_pairing,27,agentic_trivial;np_search -mc_low_autocorrelation,construct,competition,combinatorics,MathConstraint/low_autocorrelation,CC-BY-4.0,low_autocorrelation_binary_sequence,31,np_search -mc_magic_sequence,construct,competition,combinatorics,MathConstraint/magic_sequence,CC-BY-4.0,magic_sequence,30,agentic_trivial -mc_max_clique,construct,competition,graph_theory,MathConstraint/max_clique,CC-BY-4.0,graph_clique,55,np_search -mc_max_independent_set,construct,competition,graph_theory,MathConstraint/max_independent_set,CC-BY-4.0,graph_independent_set,60,np_search -mc_non_transitive_dice,construct,competition,probability,MathConstraint/non_transitive_dice,CC-BY-4.0,intransitive_dice,15,agentic_trivial;np_search -mc_number_partitioning,construct,competition,number_theory,MathConstraint/number_partitioning,CC-BY-4.0,equal_sum_partition_1_to_n,59,agentic_trivial -mc_ortholatin,construct,competition,combinatorics,MathConstraint/ortholatin,CC-BY-4.0,orthogonal_latin_squares,21,np_search -mc_pysms_chromatic_girth,construct,competition,graph_theory,MathConstraint/pysms_chromatic_girth,CC-BY-4.0,graph_existence_chromatic_girth,25,np_search -mc_pysms_clique_coloring,construct,competition,graph_theory,MathConstraint/pysms_clique_coloring,CC-BY-4.0,graph_existence_clique_coloring,16,np_search -mc_pysms_degree_bounds,construct,competition,graph_theory,MathConstraint/pysms_degree_bounds,CC-BY-4.0,graph_existence_degree_bounds,11,agentic_trivial;np_search -mc_pysms_girth_degree,construct,competition,graph_theory,MathConstraint/pysms_girth_degree,CC-BY-4.0,graph_existence_girth_degree,18,np_search -mc_pysms_graph_builder,construct,competition,graph_theory,MathConstraint/pysms_graph_builder,CC-BY-4.0,graph_existence_graph_builder,8,np_search -mc_pysms_independent_connectivity,construct,competition,graph_theory,MathConstraint/pysms_independent_connectivity,CC-BY-4.0,graph_existence_independent_connectivity,15,np_search -mc_pysms_min_connectivity,construct,competition,graph_theory,MathConstraint/pysms_min_connectivity,CC-BY-4.0,graph_existence_min_connectivity,12,agentic_trivial;np_search -mc_pysms_min_degree,construct,competition,graph_theory,MathConstraint/pysms_min_degree,CC-BY-4.0,graph_existence_min_degree,12,agentic_trivial;np_search -mc_pysms_min_girth,construct,competition,graph_theory,MathConstraint/pysms_min_girth,CC-BY-4.0,graph_existence_min_girth,13,agentic_trivial;np_search -mc_pysms_mtf,construct,competition,graph_theory,MathConstraint/pysms_mtf,CC-BY-4.0,maximal_triangle_free_graph,12,agentic_trivial;np_search -mc_pysms_num_edges_bounds,construct,competition,graph_theory,MathConstraint/pysms_num_edges_bounds,CC-BY-4.0,graph_existence_num_edges_bounds,12,agentic_trivial;np_search -mc_quasigroup_idempotent,construct,competition,algebra,MathConstraint/quasigroup_idempotent,CC-BY-4.0,idempotent_qg3_quasigroup,12,np_search -mc_ramsey,construct,competition,combinatorics,MathConstraint/ramsey,CC-BY-4.0,ramsey_two_colouring,54,np_search -mc_social_golfers,construct,competition,combinatorics,MathConstraint/social_golfers,CC-BY-4.0,social_golfer,23,np_search -mc_van_der_waerden,construct,competition,combinatorics,MathConstraint/van_der_waerden,CC-BY-4.0,van_der_waerden_colouring,42,np_search -mc_vertex_cover,construct,competition,graph_theory,MathConstraint/vertex_cover,CC-BY-4.0,graph_vertex_cover,60,np_search -nppc_bandwidth,construct,competition,graph_theory,NPPC/bandwidth,MIT,graph_bandwidth,60,agentic_trivial;np_search -nppc_clique,construct,competition,graph_theory,NPPC/clique,MIT,graph_clique,60,agentic_trivial;np_search -nppc_dominating_set,construct,competition,graph_theory,NPPC/dominating_set,MIT,graph_dominating_set,60,agentic_trivial;np_search -nppc_independent_set,construct,competition,graph_theory,NPPC/independent_set,MIT,graph_independent_set,60,agentic_trivial;np_search -nppc_quad_diophantine,construct,competition,number_theory,NPPC/quad_diop_equ,MIT,quadratic_diophantine_ax2_by_c,60,agentic_trivial;np_search -nppc_quadratic_congruence,construct,competition,number_theory,NPPC/quadratic_congruence,MIT,quadratic_congruence_bounded,60,agentic_trivial;np_search -nppc_three_coloring,construct,competition,graph_theory,NPPC/graph_three_colorability,MIT,graph_3_coloring,60,agentic_trivial;np_search -nppc_vertex_cover,construct,competition,graph_theory,NPPC/vertex_cover,MIT,graph_vertex_cover,60,agentic_trivial;np_search -rg_graph_color,construct,competition,graph_theory,ReasoningGym/graph_color,Apache-2.0,graph_k_coloring,60,agentic_trivial;np_search -rg_intermediate_integration,construct,competition,analysis,ReasoningGym/intermediate_integration,Apache-2.0,symbolic_antiderivative,60,symbolic -rg_simple_integration,construct,competition,analysis,ReasoningGym/simple_integration,Apache-2.0,symbolic_antiderivative_polynomial,60,symbolic -rlve_antiderivative,construct,competition,analysis,RLVE-Gym/integral,MIT,symbolic_antiderivative,60, -rlve_bezout_identity,construct,competition,number_theory,RLVE-Gym/bezout_identity,MIT,bezout_coefficients,60,agentic_trivial -rlve_construct_hack_interval,construct,competition,number_theory,RLVE-Gym/construct_hack_interval,MIT,cf468c_hack_interval,60, -rlve_crt,construct,competition,number_theory,RLVE-Gym/crt,MIT,generalized_crt,60,agentic_trivial -rlve_distinct_subset_sum_permutation,construct,competition,combinatorics,RLVE-Gym/distinct_array_permutation,MIT,cf892d_gluttony,60,agentic_trivial -rlve_even_degree_partition,construct,competition,graph_theory,RLVE-Gym/even_degree_graph_partitioning,MIT,gallai_even_partition,60,agentic_trivial -rlve_graph_isomorphism,construct,competition,graph_theory,RLVE-Gym/graph_isomorphism,MIT,graph_isomorphism,60,agentic_trivial;np_search -rlve_grid_parity_construction,construct,competition,algebra,RLVE-Gym/grid_parity_construction,MIT,lights_out_gf2,60,agentic_trivial -rlve_imp_party,construct,competition,graph_theory,RLVE-Gym/imp_party,MIT,poi_party_clique_3n,60,agentic_trivial -rlve_integer_linear_system,construct,competition,algebra,RLVE-Gym/gaussian_elimination,MIT,integer_linear_system,60,agentic_trivial -rlve_largest_convex_polygon,construct,competition,discrete_geometry,RLVE-Gym/largest_convex_polygon,MIT,largest_convex_subset,60,agentic_trivial -rlve_largest_rectangle,construct,competition,discrete_geometry,RLVE-Gym/largest_rectangle_among_points,MIT,largest_rectangle_in_point_set,60,agentic_trivial -rlve_matrix_permutation_equivalence,construct,competition,combinatorics,RLVE-Gym/matrix_permutation_equivalence,MIT,binary_matrix_permutation_equivalence,60,agentic_trivial;np_search -rlve_max_achromatic_coloring,construct,competition,graph_theory,RLVE-Gym/maximum_achromatic_number,MIT,achromatic_number,60,agentic_trivial;np_search -rlve_maximum_clique,construct,competition,graph_theory,RLVE-Gym/maximum_clique,MIT,maximum_clique,60,agentic_trivial;np_search -rlve_min_chromatic_number,construct,competition,graph_theory,RLVE-Gym/minimum_chromatic_number,MIT,graph_k_coloring_chromatic,60,agentic_trivial;np_search -rlve_min_harmonious_coloring,construct,competition,graph_theory,RLVE-Gym/minimum_harmonious_chromatic_number,MIT,harmonious_chromatic_number,60,agentic_trivial;np_search -rlve_pairwise_sums_recovery,construct,competition,combinatorics,RLVE-Gym/squ_squarks,MIT,poi_squarks_pairwise_sums,60,agentic_trivial -rlve_pan_solar_panels,construct,competition,number_theory,RLVE-Gym/pan_solar_panels,MIT,poi_solar_panels_max_gcd,60,agentic_trivial -rlve_polynomial_global_minimum,construct,competition,analysis,RLVE-Gym/polynomial_minimum,MIT,polynomial_global_minimum,60,agentic_trivial -rlve_polynomial_integer_roots,construct,competition,algebra,RLVE-Gym/polynomial_factorization,MIT,integer_root_factorization,60,agentic_trivial;unique_answer -rlve_polynomial_interpolation,construct,competition,algebra,RLVE-Gym/polynomial_interpolation,MIT,lagrange_interpolation_integer,60,agentic_trivial;unique_answer -rlve_prefix_product_permutation,construct,competition,number_theory,RLVE-Gym/prefix_product_mod_distinct_permutation,MIT,cf487c_prefix_product_sequence,60, -rlve_prefix_sum_permutation,construct,competition,number_theory,RLVE-Gym/prefix_sum_mod_distinct_permutation,MIT,prefix_sum_mod_distinct_permutation,60, -rlve_prime_graph_coloring,construct,competition,graph_theory,RLVE-Gym/prime_graph_minimum_chromatic_number,MIT,prime_distance_graph_coloring,60,agentic_trivial -rlve_recursive_sequence_sum,construct,competition,number_theory,RLVE-Gym/recursive_sequence_sum_construction,MIT,linear_recurrence_subset_sum,60,agentic_trivial -rlve_round_robin_scores,construct,competition,combinatorics,RLVE-Gym/round_robin,MIT,tournament_score_realisation_3_1_0,60,agentic_trivial -rlve_shortest_path_count,construct,competition,combinatorics,RLVE-Gym/shortest_path_count_construction,MIT,cf388b_shortest_path_count,60, -rlve_smallest_enclosing_circle,construct,competition,geometry,RLVE-Gym/smallest_circle,MIT,minimum_enclosing_circle,60,agentic_trivial -rlve_subgraph_isomorphism,construct,competition,graph_theory,RLVE-Gym/subgraph_isomorphism,MIT,induced_subgraph_isomorphism,60,agentic_trivial;np_search +family,subset,tier,domain,source,license,problem_key,n_tasks,tags +ae_p10_kakeya_3d,optimize,research,geometry,AlphaEvolve-Repository-of-Problems/10-3d-kakeya,CC-BY-4.0,kakeya_needle_3d_prisms,1,exact_piecewise_integration;float_objective +ae_p16_gagliardo_nirenberg,optimize,research,analysis,AlphaEvolve-Repository-of-Problems/16-gagliardo-nirenberg-special-case,CC-BY-4.0,nagy_gagliardo_nirenberg_sharp_constant,3,float_objective;known_optimum +ae_p17_young_convolution,optimize,research,analysis,AlphaEvolve-Repository-of-Problems/17-young-convolution,CC-BY-4.0,young_convolution_sharp_constant,3,float_objective;known_optimum +ae_p18_hardy_littlewood_maximal,optimize,research,analysis,AlphaEvolve-Repository-of-Problems/18-hardy-littlewood-maximal,CC-BY-4.0,centered_hardy_littlewood_weak11_constant_1d,1,exact_rational;known_optimum +ae_p1_ff_kakeya,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/1-finite-field-kakeya,CC-BY-4.0,finite_field_kakeya_min_size,10,exact_integer;finite_fields +ae_p1_ff_nikodym,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/1-finite-field-nikodym,CC-BY-4.0,finite_field_nikodym_min_size_d3,4,exact_integer;finite_fields +ae_p24_de_bruijn_sharma,optimize,research,analysis,AlphaEvolve-Repository-of-Problems/24-de-bruijn-sharma,CC-BY-4.0,de_bruijn_sharma_x_intercept,4,float_objective;polynomials +ae_p29_block_stacking,optimize,competition,analysis,AlphaEvolve-Repository-of-Problems/29-block-stacking,CC-BY-4.0,block_stacking_overhang_one_per_level,3,agentic_trivial;exact_rational;known_optimum +ae_p30_arithmetic_kakeya,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/30-arithmetic-kakeya,CC-BY-4.0,arithmetic_kakeya_entropy_sum_difference,2,additive_combinatorics;entropy;float_objective +ae_p31_furstenberg_sarkozy,optimize,research,number_theory,AlphaEvolve-Repository-of-Problems/31-furstenberg-sarkozy,CC-BY-4.0,furstenberg_sarkozy_modular_exponent,2,additive_combinatorics;exact_integer +ae_p32_spherical_designs,construct,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/32-spherical-designs,CC-BY-4.0,spherical_t_design_s2,6,float_tolerance;numerical_design +ae_p35_cubes_in_cube,optimize,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/35-packing-in-a-dilate,CC-BY-4.0,unit_cubes_in_smallest_cube_n11,1,float_objective;packing +ae_p37_turan_tetrahedron,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/37-hypergraph-turan-tetrahedron,CC-BY-4.0,turan_density_K4_3,1,blow_up;extremal_hypergraph +ae_p38_factorial_factors,construct,research,number_theory,AlphaEvolve-Repository-of-Problems/38-factoring-N-factorial,CC-BY-4.0,factorial_into_n_large_factors_A034258,60,agentic_trivial;exact_integer;ilp_friendly;np_search +ae_p39_beat_the_average,optimize,research,probability,AlphaEvolve-Repository-of-Problems/39-beat-the-average,CC-BY-4.0,beat_the_average_X1X2X3_lt_2X4,1,discrete_measure;float_objective +ae_p40_erdos_discrepancy,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/40-erdos-discrepancy,CC-BY-4.0,erdos_discrepancy_C2_max_length,1,exact_integer;np_search;sat_friendly +ae_p41_sphere_max_volume,optimize,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/41-points-on-sphere-max-volume,CC-BY-4.0,max_volume_inscribed_polyhedron_n_vertices,7,float_objective +ae_p42_sum_difference_i,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/42-sum-difference-I,CC-BY-4.0,sum_difference_sumset_vs_diffset_exponent,1,additive_combinatorics;exact_integer +ae_p43_sum_difference_ii,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/43-sum-difference-II,CC-BY-4.0,sum_difference_diffset_vs_sumset_exponent,1,additive_combinatorics;exact_integer +ae_p44_sum_difference_iii,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/44-sum-difference-III,CC-BY-4.0,sum_difference_A_plus_B_vs_A_minus_B_exponent,1,additive_combinatorics;exact_integer +ae_p45_sum_product_fp,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/45-sum-product-finite-field,Apache-2.0,finite_field_sum_product_sqrt_p,3,additive_combinatorics;exact_integer +ae_p52_erdos_squarefree,construct,research,number_theory,AlphaEvolve-Repository-of-Problems/52-erdos-squarefree,CC-BY-4.0,erdos_ab_plus_1_never_squarefree,50,exact_integer +ae_p54_touching_cylinders,construct,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/54-pairwise-touching-cylinders,CC-BY-4.0,mutually_touching_infinite_cylinders,2,float_tolerance;nonlinear_system +ae_p58_happy_ending,construct,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/58-erdos-szekeres-happy-ending,CC-BY-4.0,erdos_szekeres_no_convex_k_gon_2pow_k_minus_2,5,exact_integer;np_search +ae_p59_isosceles_free_grid,optimize,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/59-no-isosceles-grid,CC-BY-4.0,isosceles_free_grid_subset,2,exact_integer;np_search +ae_p60_no5_on_sphere,optimize,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/60-no-5-on-a-sphere,CC-BY-4.0,no_five_cospherical_grid_subset,6,exact_integer;np_search +ae_p65_imo2025_p6_tiling,construct,competition,combinatorics,AlphaEvolve-Repository-of-Problems/65-imo-2025-p6,CC-BY-4.0,imo2025_p6_min_tiles,6,exact_integer +ea_circle_packing_26,optimize,research,discrete_geometry,EinsteinArena/circle-packing,MIT,circle_packing_square_sum_radii_n26,1,exact_check;float_objective +ea_circles_rectangle_21,optimize,research,discrete_geometry,EinsteinArena/circles-rectangle,MIT,circles_in_rectangle_perimeter4_sum_radii_n21,1,exact_check;float_objective +ea_difference_bases,optimize,research,number_theory,EinsteinArena/difference-bases,MIT,difference_basis_ratio,1,exact_check +ea_edges_vs_triangles,optimize,research,combinatorics,EinsteinArena/edges-vs-triangles,MIT,edges_vs_triangles_density_curve,1,float_objective +ea_erdos_min_overlap,optimize,research,analysis,EinsteinArena/erdos-min-overlap,MIT,erdos_minimum_overlap_upper,1,float_objective +ea_first_autocorrelation,optimize,research,analysis,EinsteinArena/first-autocorrelation-inequality,MIT,first_autocorrelation_inequality_upper,1,float_objective +ea_flat_polynomials_70,optimize,research,analysis,EinsteinArena/flat-polynomials,MIT,flat_littlewood_polynomial_n70,1,float_objective +ea_hadamard_det_51,optimize,research,combinatorics,EinsteinArena/hadamard-det-51,MIT,hadamard_maxdet_n51,1,ea_under_review;exact_check +ea_heilbronn_triangle_11,optimize,research,discrete_geometry,EinsteinArena/heilbronn-triangles,MIT,heilbronn_triangle_n11,1,exact_check;float_objective +ea_kakeya_needle_128,optimize,research,geometry,EinsteinArena/kakeya-needle-128,MIT,kakeya_needle_triangles_n128,1,ea_under_review;exact_check +ea_kissing_number,optimize,research,discrete_geometry,"EinsteinArena/kissing-number-d11,-d11-605,-d12",MIT,kissing_number_overlap_loss,3,best_known_uncertain;exact_check +ea_min_distance_ratio_16,optimize,research,discrete_geometry,EinsteinArena/min-distance-ratio-2d,MIT,max_min_distance_ratio_2d_n16,1,float_objective +ea_no_three_in_line_75,optimize,research,discrete_geometry,EinsteinArena/no-three-in-line-75,MIT,no_three_in_line_n75,1,ea_under_review;exact_check +ea_prime_number_theorem,optimize,research,number_theory,EinsteinArena/prime-number-theorem,MIT,pnt_chebyshev_certificate,1,float_objective;range_limited_certificate +ea_ring_loading_15,optimize,research,combinatorics,EinsteinArena/ring-loading-15,MIT,ring_loading_m15,1,ea_under_review;exact_check +ea_second_autocorrelation,optimize,research,analysis,EinsteinArena/second-autocorrelation-inequality,MIT,second_autocorrelation_inequality_lower,1,float_objective +ea_shannon_c7_5,optimize,research,graph_theory,EinsteinArena/shannon-capacity-c7-5,MIT,independent_set_c7_strong_power5,1,ea_under_review;exact_check +ea_sidon_45_set,optimize,research,number_theory,EinsteinArena/sidon-45-set,MIT,sidon_subsets_of_45_sets,1,ea_under_review;exact_check +ea_snake_in_the_box_13,optimize,research,graph_theory,EinsteinArena/snake-in-the-box-13,MIT,snake_in_the_box_d13,1,ea_under_review;exact_check +ea_sorting_network_16,optimize,research,combinatorics,EinsteinArena/sorting-network-16,MIT,sorting_network_size_n16,1,ea_under_review;exact_check +ea_spencer_discrepancy,optimize,research,combinatorics,EinsteinArena/spencer-discrepancy,MIT,spencer_discrepancy_square_n_le20,1,ea_under_review;exact_check +ea_tammes,optimize,research,discrete_geometry,EinsteinArena/tammes-problem,MIT,tammes_n50,1,float_objective +ea_third_autocorrelation,optimize,research,analysis,EinsteinArena/third-autocorrelation-inequality,MIT,third_autocorrelation_inequality_upper,1,float_objective +ea_thomson_282,optimize,research,discrete_geometry,EinsteinArena/thomson-problem,MIT,thomson_problem_n282,1,float_objective +ea_two_deletion_code_16,optimize,research,coding_theory,EinsteinArena/two-deletion-code-16,MIT,two_deletion_code_n16,1,ea_under_review;exact_check +ea_uncertainty_principle,optimize,research,analysis,EinsteinArena/uncertainty-principle,MIT,plus1_uncertainty_principle_upper,1,high_precision +finch_3ap_diffs_40,optimize,research,combinatorics,Finch-EFT/skydiscover/erdos_1097_3ap_diffs_n40,Apache-2.0,erdos1097_3ap_differences_n40_m400,1,best_known_uncertain;exact_check;np_search +finch_4subset_3dist_16,optimize,research,discrete_geometry,Finch-EFT/skydiscover/erdos_659_4subset_3dist_construction,Apache-2.0,erdos659_4sets_3dist_n16,1,best_known_uncertain;exact_check;np_search +finch_flat_poly_32,optimize,research,analysis,Finch-EFT/skydiscover/erdos_flat_polynomials_n32,Apache-2.0,flat_littlewood_polynomial_n32,1,best_known_uncertain;float_objective;np_search +finch_heilbronn_disk_12,optimize,research,discrete_geometry,Finch-EFT/skydiscover/erdos_507_heilbronn_disk_n12,Apache-2.0,heilbronn_disk_n12,1,best_known_uncertain;exact_check;float_objective +finch_isosceles_free_grid_8,optimize,competition,discrete_geometry,Finch-EFT/skydiscover/erdos_isosceles_free_grid,Apache-2.0,isosceles_free_grid_subset,1,exact_check;exact_optimum_known;np_search +finch_lcm_chain_10000,optimize,competition,number_theory,Finch-EFT/skydiscover/erdos_440_lcm_density,Apache-2.0,erdos440_lcm_consecutive_x10000,1,exact_check;exact_optimum_known +finch_newman_200,optimize,research,number_theory,Finch-EFT/skydiscover/erdos_480_newman_density,Apache-2.0,erdos480_newman_finite_n200,1,best_known_uncertain;float_objective +finch_no4_concyclic_12,optimize,research,discrete_geometry,Finch-EFT/skydiscover/erdos_654_no_four_concyclic_distances,Apache-2.0,erdos654_no4_concyclic_n12,1,best_known_uncertain;exact_check;np_search +finch_sidon_pair_100,optimize,research,number_theory,Finch-EFT/skydiscover/erdos_43_sidon_pair,Apache-2.0,erdos43_sidon_pair_n100,1,best_known_uncertain;exact_check;np_search +finch_sidon_set_121,optimize,competition,number_theory,Finch-EFT/skydiscover/erdos_difference_bases_N121,Apache-2.0,max_sidon_set_0_120,1,exact_check;exact_optimum_known +finch_square_packing_12,optimize,research,discrete_geometry,Finch-EFT/skydiscover/erdos_106_square_packing,Apache-2.0,erdos106_squares_in_square_n12,1,exact_check +finch_udg_girth_30,optimize,research,graph_theory,Finch-EFT/skydiscover/erdos_705_unit_distance_high_girth,Apache-2.0,erdos705_udg_chi4_girth_n30,1,best_known_uncertain;exact_check +fs_admissible_set,optimize,research,combinatorics,FunSearch/admissible_set,Apache-2.0,admissible_set_constant_weight,2,integer_objective +fs_cap_set,optimize,research,combinatorics,FunSearch/cap_set,Apache-2.0,cap_set_f3n,6,integer_objective +fs_cycle_independent_set,optimize,research,graph_theory,FunSearch/cyclic_graphs,Apache-2.0,independent_set_strong_power_odd_cycle,7,integer_objective +mc_all_interval,construct,competition,combinatorics,MathConstraint/all_interval,CC-BY-4.0,all_interval_series,40,agentic_trivial +mc_antimagic_square,construct,competition,combinatorics,MathConstraint/antimagic_square,CC-BY-4.0,antimagic_square,6,np_search +mc_bibd,construct,competition,combinatorics,MathConstraint/bibd,CC-BY-4.0,bibd,28,np_search +mc_costas_array,construct,competition,combinatorics,MathConstraint/costas_array,CC-BY-4.0,costas_array,23,np_search +mc_debruijn,construct,competition,combinatorics,MathConstraint/debruijn,CC-BY-4.0,de_bruijn_sequence,22,agentic_trivial +mc_golomb,construct,competition,combinatorics,MathConstraint/golomb,CC-BY-4.0,golomb_ruler,18,np_search +mc_graceful_graph,construct,competition,graph_theory,MathConstraint/graceful_graph,CC-BY-4.0,graceful_labeling,17,np_search +mc_graph_k_coloring,construct,competition,graph_theory,MathConstraint/graph_k_coloring,CC-BY-4.0,graph_k_coloring,48,np_search +mc_hadamard,construct,competition,combinatorics,MathConstraint/hadamard,CC-BY-4.0,legendre_pair,30,np_search +mc_langford,construct,competition,combinatorics,MathConstraint/langford,CC-BY-4.0,langford_pairing,27,agentic_trivial;np_search +mc_low_autocorrelation,construct,competition,combinatorics,MathConstraint/low_autocorrelation,CC-BY-4.0,low_autocorrelation_binary_sequence,31,np_search +mc_magic_sequence,construct,competition,combinatorics,MathConstraint/magic_sequence,CC-BY-4.0,magic_sequence,30,agentic_trivial +mc_max_clique,construct,competition,graph_theory,MathConstraint/max_clique,CC-BY-4.0,graph_clique,55,np_search +mc_max_independent_set,construct,competition,graph_theory,MathConstraint/max_independent_set,CC-BY-4.0,graph_independent_set,60,np_search +mc_non_transitive_dice,construct,competition,probability,MathConstraint/non_transitive_dice,CC-BY-4.0,intransitive_dice,15,agentic_trivial;np_search +mc_number_partitioning,construct,competition,number_theory,MathConstraint/number_partitioning,CC-BY-4.0,equal_sum_partition_1_to_n,59,agentic_trivial +mc_ortholatin,construct,competition,combinatorics,MathConstraint/ortholatin,CC-BY-4.0,orthogonal_latin_squares,21,np_search +mc_pysms_chromatic_girth,construct,competition,graph_theory,MathConstraint/pysms_chromatic_girth,CC-BY-4.0,graph_existence_chromatic_girth,25,np_search +mc_pysms_clique_coloring,construct,competition,graph_theory,MathConstraint/pysms_clique_coloring,CC-BY-4.0,graph_existence_clique_coloring,16,np_search +mc_pysms_degree_bounds,construct,competition,graph_theory,MathConstraint/pysms_degree_bounds,CC-BY-4.0,graph_existence_degree_bounds,11,agentic_trivial;np_search +mc_pysms_girth_degree,construct,competition,graph_theory,MathConstraint/pysms_girth_degree,CC-BY-4.0,graph_existence_girth_degree,18,np_search +mc_pysms_graph_builder,construct,competition,graph_theory,MathConstraint/pysms_graph_builder,CC-BY-4.0,graph_existence_graph_builder,8,np_search +mc_pysms_independent_connectivity,construct,competition,graph_theory,MathConstraint/pysms_independent_connectivity,CC-BY-4.0,graph_existence_independent_connectivity,15,np_search +mc_pysms_min_connectivity,construct,competition,graph_theory,MathConstraint/pysms_min_connectivity,CC-BY-4.0,graph_existence_min_connectivity,12,agentic_trivial;np_search +mc_pysms_min_degree,construct,competition,graph_theory,MathConstraint/pysms_min_degree,CC-BY-4.0,graph_existence_min_degree,12,agentic_trivial;np_search +mc_pysms_min_girth,construct,competition,graph_theory,MathConstraint/pysms_min_girth,CC-BY-4.0,graph_existence_min_girth,13,agentic_trivial;np_search +mc_pysms_mtf,construct,competition,graph_theory,MathConstraint/pysms_mtf,CC-BY-4.0,maximal_triangle_free_graph,12,agentic_trivial;np_search +mc_pysms_num_edges_bounds,construct,competition,graph_theory,MathConstraint/pysms_num_edges_bounds,CC-BY-4.0,graph_existence_num_edges_bounds,12,agentic_trivial;np_search +mc_quasigroup_idempotent,construct,competition,algebra,MathConstraint/quasigroup_idempotent,CC-BY-4.0,idempotent_qg3_quasigroup,12,np_search +mc_ramsey,construct,competition,combinatorics,MathConstraint/ramsey,CC-BY-4.0,ramsey_two_colouring,54,np_search +mc_social_golfers,construct,competition,combinatorics,MathConstraint/social_golfers,CC-BY-4.0,social_golfer,23,np_search +mc_van_der_waerden,construct,competition,combinatorics,MathConstraint/van_der_waerden,CC-BY-4.0,van_der_waerden_colouring,42,np_search +mc_vertex_cover,construct,competition,graph_theory,MathConstraint/vertex_cover,CC-BY-4.0,graph_vertex_cover,60,np_search +nppc_bandwidth,construct,competition,graph_theory,NPPC/bandwidth,MIT,graph_bandwidth,60,agentic_trivial;np_search +nppc_clique,construct,competition,graph_theory,NPPC/clique,MIT,graph_clique,60,agentic_trivial;np_search +nppc_dominating_set,construct,competition,graph_theory,NPPC/dominating_set,MIT,graph_dominating_set,60,agentic_trivial;np_search +nppc_independent_set,construct,competition,graph_theory,NPPC/independent_set,MIT,graph_independent_set,60,agentic_trivial;np_search +nppc_quad_diophantine,construct,competition,number_theory,NPPC/quad_diop_equ,MIT,quadratic_diophantine_ax2_by_c,60,agentic_trivial;np_search +nppc_quadratic_congruence,construct,competition,number_theory,NPPC/quadratic_congruence,MIT,quadratic_congruence_bounded,60,agentic_trivial;np_search +nppc_three_coloring,construct,competition,graph_theory,NPPC/graph_three_colorability,MIT,graph_3_coloring,60,agentic_trivial;np_search +nppc_vertex_cover,construct,competition,graph_theory,NPPC/vertex_cover,MIT,graph_vertex_cover,60,agentic_trivial;np_search +rg_graph_color,construct,competition,graph_theory,ReasoningGym/graph_color,Apache-2.0,graph_k_coloring,60,agentic_trivial;np_search +rg_intermediate_integration,construct,competition,analysis,ReasoningGym/intermediate_integration,Apache-2.0,symbolic_antiderivative,60,symbolic +rg_simple_integration,construct,competition,analysis,ReasoningGym/simple_integration,Apache-2.0,symbolic_antiderivative_polynomial,60,symbolic +rlve_antiderivative,construct,competition,analysis,RLVE-Gym/integral,MIT,symbolic_antiderivative,60, +rlve_bezout_identity,construct,competition,number_theory,RLVE-Gym/bezout_identity,MIT,bezout_coefficients,60,agentic_trivial +rlve_construct_hack_interval,construct,competition,number_theory,RLVE-Gym/construct_hack_interval,MIT,cf468c_hack_interval,60, +rlve_crt,construct,competition,number_theory,RLVE-Gym/crt,MIT,generalized_crt,60,agentic_trivial +rlve_distinct_subset_sum_permutation,construct,competition,combinatorics,RLVE-Gym/distinct_array_permutation,MIT,cf892d_gluttony,60,agentic_trivial +rlve_even_degree_partition,construct,competition,graph_theory,RLVE-Gym/even_degree_graph_partitioning,MIT,gallai_even_partition,60,agentic_trivial +rlve_graph_isomorphism,construct,competition,graph_theory,RLVE-Gym/graph_isomorphism,MIT,graph_isomorphism,60,agentic_trivial;np_search +rlve_grid_parity_construction,construct,competition,algebra,RLVE-Gym/grid_parity_construction,MIT,lights_out_gf2,60,agentic_trivial +rlve_imp_party,construct,competition,graph_theory,RLVE-Gym/imp_party,MIT,poi_party_clique_3n,60,agentic_trivial +rlve_integer_linear_system,construct,competition,algebra,RLVE-Gym/gaussian_elimination,MIT,integer_linear_system,60,agentic_trivial +rlve_largest_convex_polygon,construct,competition,discrete_geometry,RLVE-Gym/largest_convex_polygon,MIT,largest_convex_subset,60,agentic_trivial +rlve_largest_rectangle,construct,competition,discrete_geometry,RLVE-Gym/largest_rectangle_among_points,MIT,largest_rectangle_in_point_set,60,agentic_trivial +rlve_matrix_permutation_equivalence,construct,competition,combinatorics,RLVE-Gym/matrix_permutation_equivalence,MIT,binary_matrix_permutation_equivalence,60,agentic_trivial;np_search +rlve_max_achromatic_coloring,construct,competition,graph_theory,RLVE-Gym/maximum_achromatic_number,MIT,achromatic_number,60,agentic_trivial;np_search +rlve_maximum_clique,construct,competition,graph_theory,RLVE-Gym/maximum_clique,MIT,maximum_clique,60,agentic_trivial;np_search +rlve_min_chromatic_number,construct,competition,graph_theory,RLVE-Gym/minimum_chromatic_number,MIT,graph_k_coloring_chromatic,60,agentic_trivial;np_search +rlve_min_harmonious_coloring,construct,competition,graph_theory,RLVE-Gym/minimum_harmonious_chromatic_number,MIT,harmonious_chromatic_number,60,agentic_trivial;np_search +rlve_pairwise_sums_recovery,construct,competition,combinatorics,RLVE-Gym/squ_squarks,MIT,poi_squarks_pairwise_sums,60,agentic_trivial +rlve_pan_solar_panels,construct,competition,number_theory,RLVE-Gym/pan_solar_panels,MIT,poi_solar_panels_max_gcd,60,agentic_trivial +rlve_polynomial_global_minimum,construct,competition,analysis,RLVE-Gym/polynomial_minimum,MIT,polynomial_global_minimum,60,agentic_trivial +rlve_polynomial_integer_roots,construct,competition,algebra,RLVE-Gym/polynomial_factorization,MIT,integer_root_factorization,60,agentic_trivial;unique_answer +rlve_polynomial_interpolation,construct,competition,algebra,RLVE-Gym/polynomial_interpolation,MIT,lagrange_interpolation_integer,60,agentic_trivial;unique_answer +rlve_prefix_product_permutation,construct,competition,number_theory,RLVE-Gym/prefix_product_mod_distinct_permutation,MIT,cf487c_prefix_product_sequence,60, +rlve_prefix_sum_permutation,construct,competition,number_theory,RLVE-Gym/prefix_sum_mod_distinct_permutation,MIT,prefix_sum_mod_distinct_permutation,60, +rlve_prime_graph_coloring,construct,competition,graph_theory,RLVE-Gym/prime_graph_minimum_chromatic_number,MIT,prime_distance_graph_coloring,60,agentic_trivial +rlve_recursive_sequence_sum,construct,competition,number_theory,RLVE-Gym/recursive_sequence_sum_construction,MIT,linear_recurrence_subset_sum,60,agentic_trivial +rlve_round_robin_scores,construct,competition,combinatorics,RLVE-Gym/round_robin,MIT,tournament_score_realisation_3_1_0,60,agentic_trivial +rlve_shortest_path_count,construct,competition,combinatorics,RLVE-Gym/shortest_path_count_construction,MIT,cf388b_shortest_path_count,60, +rlve_smallest_enclosing_circle,construct,competition,geometry,RLVE-Gym/smallest_circle,MIT,minimum_enclosing_circle,60,agentic_trivial +rlve_subgraph_isomorphism,construct,competition,graph_theory,RLVE-Gym/subgraph_isomorphism,MIT,induced_subgraph_isomorphism,60,agentic_trivial;np_search +ae_p14_hausdorff_young,optimize,research,analysis,AlphaEvolve-Repository-of-Problems/14-hausdorff-young,CC-BY-4.0,hausdorff_young_sharp_constant,2,float_objective;known_optimum +ae_p1_ff_nikodym_2d,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/1-finite-field-nikodym,CC-BY-4.0,finite_field_nikodym_min_size_d2_q_square,3,best_known_uncertain;exact_integer;finite_fields +ae_p33_thomson,optimize,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/33-thomson-problem,CC-BY-4.0,thomson_problem,2,best_known_uncertain;float_objective +ae_p35_hexagons_in_hexagon,optimize,research,discrete_geometry,AlphaEvolve-Repository-of-Problems/35-packing-in-a-dilate,CC-BY-4.0,unit_hexagons_in_smallest_hexagon,2,float_objective;packing +ae_p40_erdos_discrepancy_c3,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/40-erdos-discrepancy,CC-BY-4.0,erdos_discrepancy_C3_max_length,1,best_known_uncertain;exact_integer;np_search;sat_friendly +ae_p56_szemeredi_trotter,optimize,research,combinatorics,AlphaEvolve-Repository-of-Problems/56-szemeredi-trotter,CC-BY-4.0,point_line_incidences_integer_n_eq_m,3,best_known_uncertain;exact_integer;incidence_geometry +ae_p57_rudin_l4,optimize,research,analysis,AlphaEvolve-Repository-of-Problems/57-rudin-problem,CC-BY-4.0,flat_spherical_harmonic_l4_l2_s2,3,best_known_uncertain;float_objective +ale_ahc002,optimize,competition,combinatorics,ALE-Bench/ahc002,CC-BY-ND-4.0,ale_ahc002,2,ale_bench;best_known_uncertain;exact_integer;license_restricted;np_search +ale_ahc004,optimize,competition,combinatorics,ALE-Bench/ahc004,CC-BY-ND-4.0,ale_ahc004,2,ale_bench;best_known_uncertain;exact_integer;license_restricted;np_search +ale_ahc009,optimize,competition,probability,ALE-Bench/ahc009,CC-BY-ND-4.0,ale_ahc009,2,ale_bench;best_known_uncertain;float_objective;license_restricted;np_search +ale_ahc010,optimize,competition,combinatorics,ALE-Bench/ahc010,CC-BY-ND-4.0,ale_ahc010,2,ale_bench;best_known_uncertain;exact_integer;license_restricted;np_search +ale_ahc011,optimize,competition,combinatorics,ALE-Bench/ahc011,CC-BY-ND-4.0,ale_ahc011,2,ale_bench;best_known_uncertain;exact_integer;license_restricted;np_search +ale_ahc014,optimize,competition,discrete_geometry,ALE-Bench/ahc014,CC-BY-ND-4.0,ale_ahc014,2,ale_bench;best_known_uncertain;exact_integer;license_restricted;np_search +ale_ahc017,optimize,competition,graph_theory,ALE-Bench/ahc017,CC-BY-ND-4.0,ale_ahc017,2,ale_bench;best_known_uncertain;exact_integer;license_restricted;np_search +ale_ahc019,optimize,competition,discrete_geometry,ALE-Bench/ahc019,CC-BY-ND-4.0,ale_ahc019,2,ale_bench;best_known_uncertain;exact_integer;license_restricted;np_search +ale_ahc021,optimize,competition,combinatorics,ALE-Bench/ahc021,CC-BY-ND-4.0,ale_ahc021,2,ale_bench;best_known_uncertain;exact_integer;license_restricted;np_search +ale_ahc024,optimize,competition,graph_theory,ALE-Bench/ahc024,CC-BY-ND-4.0,ale_ahc024,2,ale_bench;best_known_uncertain;exact_integer;license_restricted;np_search +ale_ahc026,optimize,competition,combinatorics,ALE-Bench/ahc026,CC-BY-ND-4.0,ale_ahc026,2,ale_bench;best_known_uncertain;exact_integer;license_restricted;np_search +ale_ahc032,optimize,competition,number_theory,ALE-Bench/ahc032,CC-BY-ND-4.0,ale_ahc032,2,ale_bench;best_known_uncertain;exact_integer;license_restricted;np_search +ale_ahc038,optimize,competition,other,ALE-Bench/ahc038,CC-BY-ND-4.0,ale_ahc038,2,ale_bench;best_known_uncertain;exact_integer;license_restricted;np_search +ale_ahc039,optimize,competition,discrete_geometry,ALE-Bench/ahc039,CC-BY-ND-4.0,ale_ahc039,2,ale_bench;best_known_uncertain;exact_integer;license_restricted;np_search +ale_ahc041,optimize,competition,graph_theory,ALE-Bench/ahc041,CC-BY-ND-4.0,ale_ahc041,2,ale_bench;best_known_uncertain;exact_integer;license_restricted;np_search +ale_ahc042,optimize,competition,combinatorics,ALE-Bench/ahc042,CC-BY-ND-4.0,ale_ahc042,2,ale_bench;best_known_uncertain;exact_integer;license_restricted;np_search +ale_ahc044,optimize,competition,combinatorics,ALE-Bench/ahc044,CC-BY-ND-4.0,ale_ahc044,2,ale_bench;best_known_uncertain;exact_integer;license_restricted;np_search +ale_ahc046,optimize,competition,combinatorics,ALE-Bench/ahc046,CC-BY-ND-4.0,ale_ahc046,2,ale_bench;best_known_uncertain;exact_integer;license_restricted;np_search +edge_apple_incremental,optimize,competition,combinatorics,EdgeBench/apple_incremental_game (AHC058),CC-BY-4.0,edge_ahc058_apple_incremental,2,best_known_uncertain;derived_from_atcoder;edgebench;exact_integer;np_search +edge_grid_turing_robot,optimize,competition,combinatorics,EdgeBench/grid_turing_robot (AHC056),CC-BY-4.0,edge_ahc056_grid_turing_robot,2,best_known_uncertain;derived_from_atcoder;edgebench;exact_integer;np_search +fco_mds,optimize,competition,graph_theory,FrontierCO/MDS (CO-Bench/FrontierCO),MIT,frontierco_mds,15,agentic_trivial;best_known_uncertain;exact_integer;frontierco;known_optimum;np_search;related_training:nppc_dominating_set +fcs_beacon,optimize,competition,combinatorics,FrontierCS/algorithmic/302,MIT,fcs_beacon_string_penalty,3,best_known_uncertain;exact_integer;frontiercs;np_search +fcs_digit_grid,optimize,competition,combinatorics,FrontierCS/algorithmic/110,MIT,fcs_digit_grid_8x14,1,exact_integer;frontiercs;np_search +fcs_gcd_chain,optimize,competition,number_theory,FrontierCS/algorithmic/41,MIT,fcs_gcd_increasing_chain_ksum,3,best_known_uncertain;exact_integer;frontiercs +fcs_inc_subseq_perm,optimize,competition,combinatorics,FrontierCS/algorithmic/33,MIT,fcs_perm_exact_increasing_subsequences,2,exact_integer;frontiercs +fcs_inverse_paths,optimize,competition,combinatorics,FrontierCS/algorithmic/58,MIT,fcs_inverse_counting_path,3,best_known_uncertain;exact_integer;frontiercs +fcs_lis_lds_split,optimize,competition,combinatorics,FrontierCS/algorithmic/227,MIT,fcs_lis_lds_four_split,3,best_known_uncertain;exact_integer;frontiercs +fcs_max3sat,optimize,competition,combinatorics,FrontierCS/algorithmic/176,MIT,fcs_max3sat,3,best_known_uncertain;exact_integer;frontiercs;np_search +fcs_maxcut,optimize,competition,graph_theory,FrontierCS/algorithmic/192,MIT,fcs_maxcut,3,best_known_uncertain;exact_integer;frontiercs;np_search +fcs_mult_partial_sums,optimize,competition,number_theory,FrontierCS/algorithmic/83,MIT,completely_multiplicative_min_partial_sum_n1e6,1,exact_integer;frontiercs;related_training:ae_p40_erdos_discrepancy +fcs_no_rectangle,optimize,competition,combinatorics,FrontierCS/algorithmic/27,MIT,fcs_no_rectangle,3,best_known_uncertain;exact_integer;frontiercs;np_search;zarankiewicz +fcs_prime_retune,optimize,competition,combinatorics,FrontierCS/algorithmic/314,MIT,fcs_prime_resonance_retuning,3,best_known_uncertain;exact_integer;frontiercs;np_search +fcs_shortcut3hop,optimize,competition,graph_theory,FrontierCS/algorithmic/239,MIT,fcs_path_shortcut_hop3,3,exact_integer;frontiercs +fcs_swap_shift,optimize,competition,combinatorics,FrontierCS/algorithmic/247,MIT,fcs_swap_shift_min_ops,3,exact_integer;frontiercs +fcs_xor_sidon,optimize,competition,combinatorics,FrontierCS/algorithmic/111,MIT,fcs_xor_sidon,3,best_known_uncertain;exact_integer;frontiercs;np_search +fsh_abc_quality,optimize,research,number_theory,FrontierShift/fs-0375,unknown,abc_triple_max_quality,1,exact_check;float_objective;frontiershift;license_unknown;record_memorizable +fsh_boolean_nonlinearity_9,optimize,research,coding_theory,FrontierShift/fs-0243,unknown,boolean_function_max_nonlinearity_n9,1,exact_integer;frontiershift;license_unknown;np_search;reference_below_best_known +fsh_cramer_gap_ratio,optimize,research,number_theory,FrontierShift/fs-0377,unknown,prime_gap_cramer_shanks_granville_ratio_p_lt_2pow64,1,exact_check;float_objective;frontiershift;known_optimum;license_unknown;record_memorizable +fsh_lwc_1280,optimize,research,coding_theory,FrontierShift/fs-0364 (decodingchallenge.org LW n=1280 seed 0),unknown,decoding_challenge_low_weight_codeword_n1280_seed0,1,cryptography;exact_check;frontiershift;license_unknown;np_search +fsh_matmul_rank,optimize,research,algebra,"FrontierShift/fs-0034,fs-0035",unknown,matmul_tensor_rank_nnn_over_Q,2,exact_check;exact_rational;frontiershift;license_unknown;record_memorizable;tensor_decomposition +fsh_maxdet_23,optimize,research,combinatorics,FrontierShift/fs-0164,unknown,hadamard_maxdet_n23,1,best_known_uncertain;exact_integer;frontiershift;license_unknown;np_search +fsh_rational_diophantine_7,optimize,research,number_theory,FrontierShift/fs-0395,unknown,rational_diophantine_septuple_square_pairs,1,exact_check;exact_rational;frontiershift;license_unknown;reference_below_best_known +fsh_tetrahedra_packing,optimize,research,discrete_geometry,FrontierShift/fs-0247,unknown,regular_tetrahedra_periodic_packing_density,1,best_known_is_open_target;exact_check;exact_rational;float_objective;frontiershift;license_unknown;reference_below_best_known +lib_cage,optimize,research,graph_theory,LeapsInBounds/cage,MIT,cage_order_k_g,8,exact_check;exact_integer;leaps_in_bounds;np_search;reference_below_record +lib_circle_in_square,optimize,research,discrete_geometry,LeapsInBounds/circle-in-square,MIT,equal_circles_in_square_min_side_n,6,best_known_uncertain;exact_check;float_objective;known_optimum;leaps_in_bounds +lib_circle_in_triangle,optimize,research,discrete_geometry,LeapsInBounds/circle-in-equilateral,MIT,equal_circles_in_equilateral_triangle_min_side_n,3,exact_check;float_objective;known_optimum;leaps_in_bounds +lib_coil_in_the_box,optimize,research,graph_theory,LeapsInBounds/coil-in-the-box,MIT,coil_in_the_box_dn,5,exact_check;exact_integer;leaps_in_bounds;np_search +lib_degree_diameter,optimize,research,graph_theory,LeapsInBounds/degree-diameter,MIT,degree_diameter_max_order_d_k,8,exact_check;exact_integer;leaps_in_bounds;np_search +lib_disk_covering,optimize,research,discrete_geometry,LeapsInBounds/disk-covering,MIT,unit_disk_covering_by_n_disks_min_radius,5,exact_check;exact_rational;float_objective;leaps_in_bounds;reference_below_record +lib_golomb_ruler,optimize,research,combinatorics,LeapsInBounds/golomb-ruler,MIT,golomb_ruler_min_length_n,7,exact_check;exact_integer;known_optimum;leaps_in_bounds;np_search +lib_isosceles_set,optimize,research,discrete_geometry,LeapsInBounds/isosceles-set,MIT,isosceles_set_max_size_rn,2,exact_check;exact_integer;known_optimum;leaps_in_bounds +lib_no_three_in_line,optimize,research,discrete_geometry,LeapsInBounds/no-three-in-line,MIT,no_three_in_line_grid_n,6,exact_check;exact_integer;known_optimum;leaps_in_bounds;np_search +lib_snake_in_the_box,optimize,research,graph_theory,LeapsInBounds/snake-in-the-box,MIT,snake_in_the_box_dn,4,exact_check;exact_integer;leaps_in_bounds;np_search +lib_sorting_network_depth,optimize,research,combinatorics,LeapsInBounds/sorting-network-depth,MIT,sorting_network_depth_n,8,exact_check;exact_integer;leaps_in_bounds;np_search +lib_sorting_network_size,optimize,research,combinatorics,LeapsInBounds/sorting-network-size,MIT,sorting_network_size_n,8,exact_check;exact_integer;leaps_in_bounds;np_search +lib_square_packing,optimize,research,discrete_geometry,LeapsInBounds/square-packing,MIT,unit_squares_in_square_min_side_n,8,exact_check;exact_rational;float_objective;leaps_in_bounds;reference_is_baseline +lib_superpermutation,optimize,research,combinatorics,LeapsInBounds/minimal-superpermutation,MIT,minimal_superpermutation_n,4,exact_check;exact_integer;leaps_in_bounds;reference_below_record +tao_c15a_matmul_rank_exponent,optimize,research,algebra,TaoOptimizationConstants/15a,Apache-2.0,matmul_exponent_exact_rank_formats_le6,1,best_known_uncertain;exact_check;exact_integer;float_objective;tao_constants +tao_c16a_brezis_gallouet_wainger,optimize,research,analysis,TaoOptimizationConstants/16a,Apache-2.0,brezis_gallouet_wainger_torus_L_radial_shell_le40000,1,agentic_trivial;float_objective;reference_not_record;tao_constants +tao_c19a_berry_esseen,optimize,research,probability,TaoOptimizationConstants/19a,Apache-2.0,berry_esseen_lower_bound_lattice_n_le10000,1,agentic_trivial;best_known_asymptotic;float_objective;reference_not_record;tao_constants +tao_c24a_komlos_discrepancy,optimize,research,combinatorics,TaoOptimizationConstants/24a,Apache-2.0,komlos_discrepancy_lower_bound_m_le40_n_le20,1,exact_check;exact_integer;np_search;reference_not_record;tao_constants +tao_c26a_boolean_bohnenblust_hille,optimize,research,analysis,TaoOptimizationConstants/26a,Apache-2.0,boolean_bohnenblust_hille_ratio_n_le20,1,best_known_asymptotic;exact_integer;float_objective;reference_not_record;tao_constants +tao_c27b_biplanar_chromatic,optimize,research,graph_theory,TaoOptimizationConstants/27b,Apache-2.0,biplanar_max_chromatic_number_n_le32,1,exact_check;exact_integer;known_record_small;tao_constants +tao_c37a_degree_sensitivity,optimize,research,combinatorics,TaoOptimizationConstants/37a,Apache-2.0,degree_sensitivity_exponent_n_le16,1,exact_check;float_objective;tao_constants +tao_c40a_lehmer_mahler,optimize,research,number_theory,TaoOptimizationConstants/40a,Apache-2.0,lehmer_min_mahler_measure_gt1_deg_le64,1,agentic_trivial;exact_check;float_objective;tao_constants +tao_c49a_sunflower_free,optimize,research,combinatorics,Tao-Davis-Ivanisvili Optimization Constants/49a (sunflower-free capacity),Apache-2.0,sperner_sunflower_free_family_max_size,2,best_known_uncertain;exact_integer;np_search;tao_constants +tao_c71a_fei_ratio,optimize,research,combinatorics,Tao-Davis-Ivanisvili Optimization Constants/71a (Fourier Entropy-Influence),Apache-2.0,fei_constant_lower_bound_balanced_amplification,1,exact_check;float_objective;np_search;tao_constants +tao_c73a_hollow_lattice_width,optimize,research,discrete_geometry,Tao-Davis-Ivanisvili Optimization Constants/73a (flatness constant in dimension 3),Apache-2.0,hollow_convex_body_max_lattice_width_d3,1,exact_check;exact_rational;tao_constants +tao_c88a_admissible_tuple,optimize,research,number_theory,Tao-Davis-Ivanisvili Optimization Constants/88a (bounded prime gaps),Apache-2.0,narrowest_admissible_k_tuple,4,agentic_trivial;best_known_uncertain;exact_integer;known_optimum;np_search;tao_constants +tao_c90a_covering_min_modulus,optimize,research,number_theory,Tao-Davis-Ivanisvili Optimization Constants/90a (covering systems),Apache-2.0,distinct_covering_system_min_modulus_lcm_le_1e8,1,exact_integer;np_search;record_outside_answer_class;tao_constants diff --git a/graders/ae_p14_hausdorff_young/check.py b/graders/ae_p14_hausdorff_young/check.py new file mode 100644 index 0000000000000000000000000000000000000000..ff48c8b48fa76abc393ff6ab319f9c8dfbd6c609 --- /dev/null +++ b/graders/ae_p14_hausdorff_young/check.py @@ -0,0 +1,42 @@ +"""Hausdorff-Young quotient ||f^||_{p'} / ||f||_p for real step functions, p' = 2k an even integer. + +f = sum_i h_i 1_[i, i+1) (unit steps, real heights), Fourier transform f^(xi) = int f(x) e^{-2 pi i x xi} dx. +For p' = 2k, (f^)^k is the transform of the k-fold self-convolution f^{*k}, so by Plancherel + ||f^||_{2k}^{2k} = ||f^{*k}||_2^2, +and f^{*k} = sum_j c_j B_k(x - j) with c = h^{*k} (discrete convolution) and B_k the order-k cardinal B-spline +(the k-fold convolution of 1_[0,1)). Hence ||f^{*k}||_2^2 = sum_d M_k(d) sum_j c_j c_{j+d} with +M_k(d) = int B_k(x) B_k(x + d) dx = (centred order-2k B-spline at d): k=2 -> 2/3, 1/6; k=3 -> 11/20, 13/60, 1/120. +Everything is a finite sum (float64). Upstream (classical_inequalities.ipynb, p = 3/2) truncated the +Fourier integral to [-R2, R2] and integrated it by Gaussian quadrature on a fixed 200-point grid; for even p' +the closed form above replaces that. +""" +import numpy as np + +from run import Invalid, float_list + +M = {2: (2.0 / 3.0, 1.0 / 6.0), 3: (11.0 / 20.0, 13.0 / 60.0, 1.0 / 120.0)} + + +def check(inst, ans): + k, p = inst["k"], inst["p"] + h = ans.get("heights") + if not isinstance(h, list) or not 1 <= len(h) <= inst["max_len"]: + raise Invalid(f"heights must be a list of 1..{inst['max_len']} numbers") + h = np.array(float_list(h, None, "heights")) + a = np.abs(h) + if a.max() > 1e6: + raise Invalid("entries must lie in [-1e6, 1e6]") + if a.max() == 0: + raise Invalid("f must not be identically zero") + h = h / a.max() + c = h + for _ in range(k - 1): + c = np.convolve(c, h) + w = M[k] + l2 = w[0] * float(np.dot(c, c)) + 2 * sum(w[d] * float(np.dot(c[:-d], c[d:])) for d in range(1, k) + if d < len(c)) + if not l2 > 0: + raise Invalid("degenerate function") + lp = float(np.sum(np.abs(h) ** p)) + q = l2 ** (1.0 / (2 * k)) / lp ** (1.0 / p) + return q, {"fhat_norm": l2 ** (1.0 / (2 * k)), "f_norm": lp ** (1.0 / p)} diff --git a/graders/ae_p1_ff_nikodym_2d/check.py b/graders/ae_p1_ff_nikodym_2d/check.py new file mode 100644 index 0000000000000000000000000000000000000000..ce4b75fb4c4e00e31e40d7ffbb44a372dffeb64b --- /dev/null +++ b/graders/ae_p1_ff_nikodym_2d/check.py @@ -0,0 +1,57 @@ +"""Finite-field Nikodym set N in F_q^2, q = p^2, submitted as its complement. Score = |N| (minimize). + +F_q = F_p(w) with w^2 = k (k = inst["nonresidue"], the least quadratic non-residue mod p); the element a + b w +is written [a, b]. A point is [[x_a, x_b], [y_a, y_b]]. Every point P of F_q^2 needs a direction v != 0 such +that P + t v lies in N for all t in F_q, t != 0 (P itself may lie outside N). All q + 1 directions +(1, m), m in F_q, and (0, 1) are checked, vectorised over all q^2 points: a line {P + t v} is labelled by +the invariant v_y * x - v_x * y in F_q. Upstream (finite_field_nikodym.ipynb, 2D experiments) returned N +itself as an array; here the complement list must be duplicate-free and in range. +""" +import numpy as np + +from run import Invalid, int_list + + +def check(inst, ans): + p, k = inst["p"], inst["nonresidue"] + q = p * p + rem = ans.get("removed") + if not isinstance(rem, list): + raise Invalid("removed must be a list") + if len(rem) >= q * q: + raise Invalid("cannot remove every point") + codes = [] + for pt in rem: + if not isinstance(pt, list) or len(pt) != 2: + raise Invalid("each point must be [[x_a, x_b], [y_a, y_b]]") + (xa, xb), (ya, yb) = int_list(pt[0], 2, 0, p - 1, "x"), int_list(pt[1], 2, 0, p - 1, "y") + codes.append(((xa * p + xb) * p + ya) * p + yb) + codes = np.array(codes, dtype=np.int64) + if len(np.unique(codes)) != len(codes): + raise Invalid("duplicate removed points") + in_n = np.ones(q * q, dtype=bool) + in_n[codes] = False + idx = np.arange(q * q) + xa, xb, ya, yb = idx // (p ** 3), (idx // (p * p)) % p, (idx // p) % p, idx % p + need = q - 1 + in_n.astype(np.int64) # points of N on the line through P, other than P + good = np.zeros(q * q, dtype=bool) + # direction (0, 1): invariant = x + dirs = [None] + [(ma, mb) for ma in range(p) for mb in range(p)] + for d in dirs: + if d is None: + lid = xa * p + xb + else: # direction (1, m): invariant = m*x - y + ma, mb = d + ra = (ma * xa + k * mb * xb - ya) % p + rb = (ma * xb + mb * xa - yb) % p + lid = ra * p + rb + cnt = np.bincount(lid[in_n], minlength=q) + good |= cnt[lid] == need + if good.all(): + break + if not good.all(): + i = int(np.flatnonzero(~good)[0]) + raise Invalid(f"point {[[int(xa[i]), int(xb[i])], [int(ya[i]), int(yb[i])]]} lies on no punctured " + f"line inside N") + size = q * q - len(rem) + return size, {"size": size} diff --git a/graders/ae_p33_thomson/check.py b/graders/ae_p33_thomson/check.py new file mode 100644 index 0000000000000000000000000000000000000000..13750d85bc9d6a136ce6b3ed19077c848b04c243 --- /dev/null +++ b/graders/ae_p33_thomson/check.py @@ -0,0 +1,25 @@ +"""Thomson problem (AlphaEvolve problem 33): minimize the Coulomb energy of n points on the unit sphere S^2. + +Same objective as the upstream get_score (thomson_problem.ipynb): vectors are projected onto the sphere and +E = sum_{i 1e9): + raise Invalid("each vector must have norm in [1e-9, 1e9]") + v = v / nr + d = np.sqrt(((v[:, None, :] - v[None, :, :]) ** 2).sum(-1))[np.triu_indices(n, 1)] + if d.min() < 1e-12: + raise Invalid("two points coincide") + e = float(np.sum(1.0 / d)) + if not np.isfinite(e): + raise Invalid("non-finite energy") + return e, {"min_distance": float(d.min())} diff --git a/graders/ae_p35_hexagons_in_hexagon/check.py b/graders/ae_p35_hexagons_in_hexagon/check.py new file mode 100644 index 0000000000000000000000000000000000000000..00278fcd2625ea675291f908419fd9374453f30b --- /dev/null +++ b/graders/ae_p35_hexagons_in_hexagon/check.py @@ -0,0 +1,43 @@ +"""Packing n unit regular hexagons in the smallest regular hexagon (AlphaEvolve problem 35, P = hexagon). + +Inner hexagon i: centre (x_i, y_i), rotation a_i (degrees), vertices (x_i + cos(a_i + 60k), y_i + sin(a_i + 60k)), +k = 0..5 (side length 1). Disjoint interiors are checked with the separating-axis theorem over the 6 edge +normals of the two hexagons; the projections may overlap by at most inst["tol"] (floating-point slack, also +stated in the prompt). The outer hexagon has a given centre c and rotation b (degrees); the score is the +SMALLEST side s for which it contains every inner vertex, s = max_v max_k / (sqrt(3)/2) with +u_k = (cos(b + 30 + 60k), sin(b + 30 + 60k)) the outer edge normals (exact containment, no tolerance). +Upstream (alphaevolve_results B.7) took the outer side as an input and checked containment with a +cross-product sign test; here it is computed, so a too-small claimed side cannot be submitted. +""" +import math + +import numpy as np + +from run import Invalid, float_list, float_matrix + +ANG = np.deg2rad(60.0 * np.arange(6)) + + +def check(inst, ans): + n, tol = inst["n"], inst["tol"] + H = np.array(float_matrix(ans.get("hexagons"), n, 3, "hexagons")) + o = float_list(ans.get("outer"), 3, "outer") + if np.abs(H).max() > 1e4 or max(abs(t) for t in o) > 1e4: + raise Invalid("coordinates and angles must lie in [-1e4, 1e4]") + a = np.deg2rad(H[:, 2])[:, None] + ANG[None, :] + V = np.stack([H[:, 0:1] + np.cos(a), H[:, 1:2] + np.sin(a)], axis=-1) # (n, 6, 2) + nrm = np.stack([np.cos(a[:, :3] + math.pi / 6), np.sin(a[:, :3] + math.pi / 6)], axis=-1) # (n, 3, 2) + for i in range(n): + for j in range(i + 1, n): + if np.hypot(*(H[i, :2] - H[j, :2])) >= 2.0 + 1e-9: # circumcircles disjoint + continue + axes = np.concatenate([nrm[i], nrm[j]]) # (6, 2) + pi_, pj = V[i] @ axes.T, V[j] @ axes.T # (6, 6): vertex x axis + ov = np.minimum(pi_.max(0), pj.max(0)) - np.maximum(pi_.min(0), pj.min(0)) + if ov.min() > tol: + raise Invalid(f"hexagons {i} and {j} overlap") + b = math.radians(o[2]) + u = np.stack([np.cos(b + math.pi / 6 + ANG), np.sin(b + math.pi / 6 + ANG)], axis=-1) # (6, 2) + P = V.reshape(-1, 2) - np.array(o[:2]) + s = float((P @ u.T).max() / (math.sqrt(3) / 2)) + return s, {"outer_side": s} diff --git a/graders/ae_p40_erdos_discrepancy_c3/check.py b/graders/ae_p40_erdos_discrepancy_c3/check.py new file mode 100644 index 0000000000000000000000000000000000000000..f8944501a4c3a9dba741dbfa5d496f7c3528bf5d --- /dev/null +++ b/graders/ae_p40_erdos_discrepancy_c3/check.py @@ -0,0 +1,27 @@ +"""Erdos discrepancy problem, C = 3 (AlphaEvolve problem 40, new parameter): longest +-1 sequence of +discrepancy <= 3. Exact integer check of every homogeneous progression d, 2d, ..., kd <= n. + +Upstream (erdos_discrepancy_problem.ipynb, C = 2) scored the longest good prefix plus a fractional bonus +1/(violations + 1); here the whole submitted sequence must have discrepancy <= C and the score is its length. +""" +import numpy as np + +from run import Invalid, int_list + + +def check(inst, ans): + x = ans.get("sequence") + if not isinstance(x, list) or not (1 <= len(x) <= inst["max_length"]): + raise Invalid(f"sequence must be a list of 1..{inst['max_length']} entries") + int_list(x, None, -1, 1, "sequence") + if 0 in x: + raise Invalid("entries must be +1 or -1") + a = np.array(x, dtype=np.int64) + n, c = len(x), inst["C"] + for d in range(1, n // (c + 1) + 1): # progressions with fewer than c+1 terms cannot exceed c + ps = np.cumsum(a[d - 1::d]) + m = int(np.abs(ps).max()) + if m > c: + k = int(np.argmax(np.abs(ps) > c)) + 1 + raise Invalid(f"|x_{d} + x_{2 * d} + ... + x_{k * d}| = {abs(int(ps[k - 1]))} > {c}") + return float(n), {"length": n} diff --git a/graders/ae_p56_szemeredi_trotter/check.py b/graders/ae_p56_szemeredi_trotter/check.py new file mode 100644 index 0000000000000000000000000000000000000000..f009ce28305b001a100a39b3c99d9434c3457278 --- /dev/null +++ b/graders/ae_p56_szemeredi_trotter/check.py @@ -0,0 +1,45 @@ +"""Point-line incidences (AlphaEvolve problem 56, Szemeredi-Trotter constructions), integer version. + +n distinct lattice points (x, y) and m distinct lines a x + b y = c with integer a, b, c ((a, b) != (0, 0)); +lines are compared after dividing by gcd(a, b, c) and fixing the sign, so duplicates in disguise are caught. +Score = number of pairs (point, line) with a x + b y = c, counted exactly in int64 (all bounds below keep +|a x + b y - c| < 2^62). Upstream (szemeredi_trotter_constructions.ipynb) silently dropped duplicate lines and +padded the point set from a grid height H; here both sets are explicit and duplicates are rejected. +""" +import math + +import numpy as np + +from run import Invalid, int_list + + +def check(inst, ans): + n, m, R, RC = inst["n"], inst["m"], inst["max_coord"], inst["max_coef"] + pts, lines = ans.get("points"), ans.get("lines") + if not isinstance(pts, list) or len(pts) != n: + raise Invalid(f"points must be a list of exactly {n} pairs") + if not isinstance(lines, list) or len(lines) != m: + raise Invalid(f"lines must be a list of exactly {m} triples") + P = np.array([int_list(p, 2, -R, R, "point") for p in pts], dtype=np.int64) + if len({(int(x), int(y)) for x, y in P}) != n: + raise Invalid("points must be distinct") + norm = set() + for ln in lines: + a, b, c = int_list(ln, 3, None, None, "line") + if max(abs(a), abs(b)) > RC or abs(c) > RC * R * 2: + raise Invalid(f"line coefficients out of range: |a|, |b| <= {RC}, |c| <= {2 * RC * R}") + if a == 0 and b == 0: + raise Invalid("a and b cannot both be zero") + g = math.gcd(math.gcd(a, b), c) + a, b, c = a // g, b // g, c // g + if a < 0 or (a == 0 and b < 0): + a, b, c = -a, -b, -c + norm.add((a, b, c)) + if len(norm) != m: + raise Invalid("lines must be distinct") + L = np.array(sorted(norm), dtype=np.int64) + inc = 0 + for s in range(0, m, 256): + blk = L[s:s + 256] + inc += int(np.count_nonzero(blk[:, 0:1] * P[None, :, 0] + blk[:, 1:2] * P[None, :, 1] == blk[:, 2:3])) + return float(inc), {"incidences": inc} diff --git a/graders/ae_p57_rudin_l4/check.py b/graders/ae_p57_rudin_l4/check.py new file mode 100644 index 0000000000000000000000000000000000000000..1341644d41d88888f7065750b6d65553bc0725b7 --- /dev/null +++ b/graders/ae_p57_rudin_l4/check.py @@ -0,0 +1,46 @@ +"""Rudin-type flatness of spherical harmonics on S^2 (AlphaEvolve problem 57, p = 4): minimize ||u||_4 / ||u||_2. + +u = sum_{m=-D..D} c_m Y_D^m with the real orthonormal basis (normalized surface measure, total mass 1) + Y_D^0 = N_{D,0} P_D(cos t), Y_D^m = sqrt(2) N_{D,m} P_D^m(cos t) cos(m f), Y_D^-m = sqrt(2) N_{D,m} P_D^m(cos t) sin(m f), +P_D^m(x) = (1 - x^2)^{m/2} d^m/dx^m P_D(x) (no Condon-Shortley phase), N_{D,m} = sqrt((2D+1)(D-m)!/(D+m)!). +Then ||u||_2^2 = sum c_m^2, and ||u||_4^4 = int u^4 dsigma is integrated EXACTLY (up to float64 rounding) by a +product rule: (2D+1)-point Gauss-Legendre in cos t (exact for polynomials of degree <= 4D+1) times 4D+1 equally +spaced azimuths (exact for trigonometric polynomials of degree <= 4D); u^4 is in that class. +Upstream (rudin_problem.ipynb) evaluated the same ratio through Gaunt coefficients with np.isclose()-based +pruning of "small" coefficients (|c| < 1e-8 silently dropped); the exact quadrature replaces it. +""" +import math + +import numpy as np +from scipy.special import lpmv + +from run import Invalid, float_list + + +def basis(D): + t, w = np.polynomial.legendre.leggauss(2 * D + 1) + M = 4 * D + 1 + phi = 2 * np.pi * np.arange(M) / M + rows = [] + for m in range(-D, D + 1): + a = abs(m) + nrm = math.sqrt((2 * D + 1) * math.exp(math.lgamma(D - a + 1) - math.lgamma(D + a + 1))) + P = (-1) ** a * lpmv(a, D, t) * nrm + ang = math.sqrt(2) * (np.cos(a * phi) if m > 0 else np.sin(a * phi)) if m else np.ones(M) + rows.append(np.outer(P, ang).ravel()) + return np.array(rows), np.outer(w / 2, np.full(M, 1.0 / M)).ravel() + + +def check(inst, ans): + D = inst["D"] + c = np.array(float_list(ans.get("coeffs"), 2 * D + 1, "coeffs")) + a = np.abs(c).max() + if a > 1e6: + raise Invalid("coefficients must lie in [-1e6, 1e6]") + if a < 1e-6: + raise Invalid("u must not be (nearly) zero: need max |c_m| >= 1e-6") + c = c / a + Y, W = basis(D) + u = c @ Y + r = float(np.sum(W * u ** 4)) ** 0.25 / math.sqrt(float(c @ c)) + return r, {"l4_over_l2": r} diff --git a/graders/ale_ahc002/check.py b/graders/ale_ahc002/check.py new file mode 100644 index 0000000000000000000000000000000000000000..5c7e7768d5bc206a0128405add93d634b289857f --- /dev/null +++ b/graders/ale_ahc002/check.py @@ -0,0 +1,57 @@ +"""ALE-Bench ahc002 (AtCoder Heuristic Contest 002 "Walking on Tiles"): Python port of the official +tools/src/lib.rs (read_input / read_output / compute_score_detail). Answer = the contestant's stdout text. +Score = sum of p over visited squares (incl. start); any rule violation = WA -> Invalid.""" +from run import Invalid + +N = 50 +MAX_LEN = 100_000 +# Rust str::trim() strips Unicode White_Space (Python's str.strip also strips \x1c-\x1f, so do it by hand) +_WS = set("\t\n\x0b\x0c\r \x85\xa0            " + "

   ") + + +def rust_trim(s): + a, b = 0, len(s) + while a < b and s[a] in _WS: + a += 1 + while b > a and s[b - 1] in _WS: + b -= 1 + return s[a:b] + + +def parse_input(text): + t = [int(x) for x in text.split()] + si, sj = t[0], t[1] + tiles = [t[2 + i * N: 2 + (i + 1) * N] for i in range(N)] + o = 2 + N * N + ps = [t[o + i * N: o + (i + 1) * N] for i in range(N)] + return (si, sj), tiles, ps + + +def check(inst, ans): + out = ans.get("output") + if not isinstance(out, str): + raise Invalid("output must be a string") + if len(out) > MAX_LEN: + raise Invalid(f"output longer than {MAX_LEN} characters") + if not out.isascii(): + raise Invalid("output must be ASCII") + (i, j), tiles, ps = parse_input(inst["input"]) + out = rust_trim(out) + used = set([tiles[i][j]]) + score = ps[i][j] + D = {"L": (0, -1), "R": (0, 1), "U": (-1, 0), "D": (1, 0)} + for c in out: + if c not in D: + raise Invalid("Illegal output") + di, dj = D[c] + i += di + j += dj + if not (0 <= i < N and 0 <= j < N): + raise Invalid("Out of range") + tl = tiles[i][j] + if tl in used: + raise Invalid("Stepped on the same tile twice") + used.add(tl) + score += ps[i][j] + return float(score), {"moves": len(out)} diff --git a/graders/ale_ahc004/check.py b/graders/ale_ahc004/check.py new file mode 100644 index 0000000000000000000000000000000000000000..b877c1deb3820df57d607e7809b1843b0033e50a --- /dev/null +++ b/graders/ale_ahc004/check.py @@ -0,0 +1,61 @@ +"""ALE-Bench ahc004 (AHC 004 "Alien's Genome Assembly"): Python port of the official tools/src/lib.rs +(parse_output + compute_score_detail). Answer = the contestant's stdout text (N lines of length N).""" +import math +import re + +from run import Invalid + +N = 20 +MAX_LEN = 100_000 +# Rust split_whitespace() splits on Unicode White_Space (Python's str.split also splits on \x1c-\x1f) +_WS_RE = re.compile("[\t\n\x0b\x0c\r \x85\xa0  - 

   ]+") + + +def rust_split_ws(s): + return [t for t in _WS_RE.split(s) if t] + + +def rust_round(x): # f64::round (half away from zero), x >= 0 + r = math.floor(x) + return r + 1 if x - r >= 0.5 else r + + +def check(inst, ans): + out = ans.get("output") + if not isinstance(out, str): + raise Invalid("output must be a string") + if len(out) > MAX_LEN: + raise Invalid(f"output longer than {MAX_LEN} characters") + if not out.isascii(): + raise Invalid("output must be ASCII") + tok = inst["input"].split() + M = int(tok[1]) + S = tok[2:2 + M] + rows = rust_split_ws(out) + if len(rows) < N: + raise Invalid("Unexpected EOF") + if len(rows) > N: + raise Invalid("Too many lines") + d = 0 + for r in rows: + if len(r) != N: + raise Invalid(f"illegal length: {len(r)}") + for ch in r: + if not ("A" <= ch <= "H") and ch != ".": + raise Invalid(f"illegal char: {ch}") + if ch == ".": + d += 1 + present = set() + for i in range(N): + for j in range(N): + for di, dj in ((0, 1), (1, 0)): + s = [] + for k in range(12): + s.append(rows[(i + di * k) % N][(j + dj * k) % N]) + present.add("".join(s)) + c = sum(1 for s in S if s in present) + if c < M: + score = rust_round(1e8 * c / M) + else: + score = rust_round(1e8 * (2 * N * N) / (2 * N * N - d)) + return float(score), {"c": c, "M": M, "dots": d} diff --git a/graders/ale_ahc009/check.py b/graders/ale_ahc009/check.py new file mode 100644 index 0000000000000000000000000000000000000000..74141c8c909bda774105817e50a8414ce2a59ff3 --- /dev/null +++ b/graders/ale_ahc009/check.py @@ -0,0 +1,82 @@ +"""ALE-Bench ahc009 (AHC 009 "Robust Memory of Commuting Routes"): Python port of the official +tools/src/lib.rs (parse_output + compute_score), replicating the f64 operation order exactly. +Answer = the contestant's stdout text (a U/D/L/R string of length <= 200).""" +import math + +from run import Invalid + +N = 20 +L = 200 +DIJ = [(-1, 0), (0, -1), (1, 0), (0, 1)] +DIR = "ULDR" +_WS = set("\t\n\x0b\x0c\r \x85\xa0            " + "

   ") + + +def rust_trim(s): + a, b = 0, len(s) + while a < b and s[a] in _WS: + a += 1 + while b > a and s[b - 1] in _WS: + b -= 1 + return s[a:b] + + +def rust_round(x): # f64::round, half away from zero + r = math.floor(abs(x)) + r = r + 1 if abs(x) - r >= 0.5 else r + return r if x >= 0 else -r + + +def check(inst, ans): + out = ans.get("output") + if not isinstance(out, str): + raise Invalid("output must be a string") + if len(out) > 10_000: + raise Invalid("too long output") + if not out.isascii(): + raise Invalid("output must be ASCII") + tok = inst["input"].split() + si, sj, ti, tj = (int(x) for x in tok[:4]) + p = float(tok[4]) + hs = [[c == "1" for c in tok[5 + i]] for i in range(N)] + vs = [[c == "1" for c in tok[5 + N + i]] for i in range(N - 1)] + + def can_move(i, j, d): + if d == 0: + return i > 0 and not vs[i - 1][j] + if d == 1: + return j > 0 and not hs[i][j - 1] + if d == 2: + return i < N - 1 and not vs[i][j] + return j < N - 1 and not hs[i][j] + + out = rust_trim(out) + crt = [[0.0] * N for _ in range(N)] + crt[si][sj] = 1.0 + s = 0.0 + goal = 0.0 + q = 1.0 - p + for t, ch in enumerate(out): + if t >= L: + raise Invalid("too long output") + d = DIR.find(ch) + if d < 0: + raise Invalid(f"illegal char: {ch}") + nxt = [[0.0] * N for _ in range(N)] + di, dj = DIJ[d] + for i in range(N): + row = crt[i] + for j in range(N): + c = row[j] + if c > 0.0: + if can_move(i, j, d): + nxt[i + di][j + dj] += c * q + nxt[i][j] += c * p + else: + nxt[i][j] += c + crt = nxt + s += crt[ti][tj] * (2 * L - t) + goal += crt[ti][tj] + crt[ti][tj] = 0.0 + return float(rust_round(1e8 * s / (2 * L))), {"length": len(out), "p_reach": goal} diff --git a/graders/ale_ahc010/check.py b/graders/ale_ahc010/check.py new file mode 100644 index 0000000000000000000000000000000000000000..c6949b02bf33a7cbb224eacfb3ffd7689d1878a4 --- /dev/null +++ b/graders/ale_ahc010/check.py @@ -0,0 +1,86 @@ +"""ALE-Bench ahc010 (AHC 010 "Loop Lines"): Python port of the official tools/src/lib.rs (parse_output + +compute_score; the tester scores the LAST output line). Answer = the contestant's stdout text.""" +from run import Invalid + +N = 30 +MAX_LEN = 200_000 +ROTATE = [1, 2, 3, 0, 5, 4, 7, 6] +X = -1 +TO = [[1, 0, X, X], [3, X, X, 0], [X, X, 3, 2], [X, 2, 1, X], [1, 0, 3, 2], [3, 2, 1, 0], [2, X, 0, X], [X, 3, X, 1]] +DIJ = [(0, -1), (-1, 0), (0, 1), (1, 0)] +_WS = set("\t\n\x0b\x0c\r ") # output is required to be ASCII, so Rust's trim() reduces to these + + +def rust_lines(s): + parts = s.split("\n") + if parts and parts[-1] == "": + parts.pop() + return [p[:-1] if p.endswith("\r") else p for p in parts] + + +def rust_trim(s): + a, b = 0, len(s) + while a < b and s[a] in _WS: + a += 1 + while b > a and s[b - 1] in _WS: + b -= 1 + return s[a:b] + + +def check(inst, ans): + out = ans.get("output") + if not isinstance(out, str): + raise Invalid("output must be a string") + if len(out) > MAX_LEN: + raise Invalid(f"output longer than {MAX_LEN} characters") + if not out.isascii(): + raise Invalid("output must be ASCII") + rows = inst["input"].split() + tiles0 = [[ord(c) - 48 for c in rows[i]] for i in range(N)] + outs = [] + for line in rust_lines(out): + line = rust_trim(line) + tmp = [] + for c in line: + if c < "0" or "3" < c: + raise Invalid(f"Illegal output: {c}") + tmp.append(ord(c) - 48) + if len(tmp) != N * N: + raise Invalid(f"Illegal output length: {len(line)}") + outs.append(tmp) + if not outs: + raise Invalid("empty output") + r = outs[-1] + tiles = [row[:] for row in tiles0] + for i in range(N): + for j in range(N): + for _ in range(r[i * N + j]): + tiles[i][j] = ROTATE[tiles[i][j]] + used = [[[False] * 4 for _ in range(N)] for _ in range(N)] + ls = [] + for i in range(N): + for j in range(N): + for d in range(4): + if TO[tiles[i][j]][d] != X and not used[i][j][d]: + i2, j2, d2 = i, j, d + length = 0 + while not used[i2][j2][d2]: + if TO[tiles[i2][j2]][d2] == X: + break + length += 1 + used[i2][j2][d2] = True + d2 = TO[tiles[i2][j2]][d2] + used[i2][j2][d2] = True + i2 += DIJ[d2][0] + j2 += DIJ[d2][1] + if not (0 <= i2 < N and 0 <= j2 < N): + break + d2 = (d2 + 2) % 4 + if (i, j, d) == (i2, j2, d2): + ls.append(length) + if len(ls) <= 1: + score = 0 + else: + ls.sort() + score = ls[-1] * ls[-2] + return float(score), {"loops": len(ls), "L1": ls[-1] if ls else 0, "L2": ls[-2] if len(ls) > 1 else 0} diff --git a/graders/ale_ahc011/check.py b/graders/ale_ahc011/check.py new file mode 100644 index 0000000000000000000000000000000000000000..c655db82073877ae598887c8b07fe13fb7406ffd --- /dev/null +++ b/graders/ale_ahc011/check.py @@ -0,0 +1,96 @@ +"""ALE-Bench ahc011 (AHC 011 "Sliding Tree Puzzle"): Python port of the official tools/src/lib.rs +(parse_output, Sim::apply, Sim::compute_score). Answer = the contestant's stdout text (a L/U/R/D string).""" +import math + +from run import Invalid + +DIJ = [(0, -1), (-1, 0), (0, 1), (1, 0)] +DIR = "LURD" +_WS = set("\t\n\x0b\x0c\r ") # output must be ASCII; Rust trim() then strips exactly these + + +def rust_trim(s): + a, b = 0, len(s) + while a < b and s[a] in _WS: + a += 1 + while b > a and s[b - 1] in _WS: + b -= 1 + return s[a:b] + + +def rust_round(x): # f64::round for x >= 0 + r = math.floor(x) + return r + 1 if x - r >= 0.5 else r + + +def check(inst, ans): + out = ans.get("output") + if not isinstance(out, str): + raise Invalid("output must be a string") + tok = inst["input"].split() + n, T = int(tok[0]), int(tok[1]) + if len(out) > 4 * T + 1000: + raise Invalid("output too long") + if not out.isascii(): + raise Invalid("output must be ASCII") + tiles0 = [[int(c, 16) for c in tok[2 + i]] for i in range(n)] + ei = ej = None + for x in range(n): + for y in range(n): + if tiles0[x][y] == 0: + ei, ej = x, y + frm = [[(x, y) for y in range(n)] for x in range(n)] + turn = 0 + for c in rust_trim(out): + d = DIR.find(c) + if d < 0: + raise Invalid(f"illegal move: {c} (turn {turn})") + i2, j2 = ei + DIJ[d][0], ej + DIJ[d][1] + if not (0 <= i2 < n and 0 <= j2 < n): + raise Invalid(f"illegal move: {c} (turn {turn})") + frm[i2][j2], frm[ei][ej] = frm[ei][ej], frm[i2][j2] + ei, ej = i2, j2 + turn += 1 + tiles = [[tiles0[frm[i][j][0]][frm[i][j][1]] for j in range(n)] for i in range(n)] + par = list(range(n * n)) + size = [1] * (n * n) + tree = [True] * (n * n) + + def find(x): + while par[x] != x: + par[x] = par[par[x]] + x = par[x] + return x + + def join(a, b): + a, b = find(a), find(b) + if a == b: + tree[a] = False + return + t = tree[a] and tree[b] + if size[a] < size[b]: + a, b = b, a + par[b] = a + size[a] += size[b] + tree[a] = t + + for i in range(n): + for j in range(n): + if i + 1 < n and tiles[i][j] & 8 and tiles[i + 1][j] & 2: + join(i * n + j, (i + 1) * n + j) + if j + 1 < n and tiles[i][j] & 4 and tiles[i][j + 1] & 1: + join(i * n + j, i * n + j + 1) + best = 0 + for i in range(n): + for j in range(n): + if tiles[i][j] != 0: + r = find(i * n + j) + if tree[r]: + best = max(best, size[r]) + if turn > T: + raise Invalid("too many moves") + if best == n * n - 1: + score = rust_round(500000.0 * (1.0 + (T - turn) / T)) + else: + score = rust_round(500000.0 * best / (n * n - 1)) + return float(score), {"K": turn, "S": best, "N": n} diff --git a/graders/ale_ahc014/check.py b/graders/ale_ahc014/check.py new file mode 100644 index 0000000000000000000000000000000000000000..fc15081d2a481c12664f1a9c322b70ed1e2312a3 --- /dev/null +++ b/graders/ale_ahc014/check.py @@ -0,0 +1,127 @@ +"""ALE-Bench ahc014 (AHC 014 "RectJoin"): Python port of the official tools/src/lib.rs (parse_output, +State::check_move / apply_move, compute_score). Answer = the contestant's stdout text.""" +import math +import re + +from run import Invalid + +DXY = [(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)] +DIRI = {v: k for k, v in enumerate(DXY)} +_INT = re.compile(r"[+-]?[0-9]+\Z") +_WS = re.compile(r"[\t\n\x0b\x0c\r ]+") # output must be ASCII; Rust split_whitespace on ASCII = these +MAX_LEN = 2_000_000 + + +def rust_round(x): + r = math.floor(x) + return r + 1 if x - r >= 0.5 else r + + +def read(tokens, pos, lb, ub): + if pos >= len(tokens): + raise Invalid("Unexpected EOF") + t = tokens[pos] + if not _INT.match(t): + raise Invalid(f"Parse error: {t[:20]}") + v = int(t) + if not (-2 ** 31 <= v < 2 ** 31): + raise Invalid(f"Parse error: {t[:20]}") + if v < lb or ub < v: + raise Invalid(f"Out of range: {v}") + return v + + +def weight(p, N): + dx = p[0] - N // 2 + dy = p[1] - N // 2 + return dx * dx + dy * dy + 1 + + +def sgn(v): + return (v > 0) - (v < 0) + + +def check(inst, ans): + out = ans.get("output") + if not isinstance(out, str): + raise Invalid("output must be a string") + if len(out) > MAX_LEN: + raise Invalid(f"output longer than {MAX_LEN} characters") + if not out.isascii(): + raise Invalid("output must be ASCII") + tok = inst["input"].split() + N, M = int(tok[0]), int(tok[1]) + ps = [(int(tok[2 + 2 * i]), int(tok[3 + 2 * i])) for i in range(M)] + tokens = [t for t in _WS.split(out) if t] + K = read(tokens, 0, 0, 1000000000) + if K == 0: + raise Invalid("K = 0 is not accepted in this conversion (perform at least one operation)") + pos = 1 + rects = [] + for _ in range(K): + r = [] + for i in range(4): + x = read(tokens, pos, 0, N - 1) + y = read(tokens, pos + 1, 0, N - 1) + pos += 2 + r.append((x, y)) + rects.append(r) + has = [[False] * N for _ in range(N)] + used = [[[False] * 8 for _ in range(N)] for _ in range(N)] + for (x, y) in ps: + has[x][y] = True + for t, rect in enumerate(rects): + err = None + bad = [i for i in (1, 2, 3) if not has[rect[i][0]][rect[i][1]]] + if bad: + err = f"{rect[bad[0]]} does not contain a dot" + elif has[rect[0][0]][rect[0][1]]: + err = f"{rect[0]} already contains a dot" + else: + dx01 = rect[1][0] - rect[0][0] + dy01 = rect[1][1] - rect[0][1] + dx03 = rect[3][0] - rect[0][0] + dy03 = rect[3][1] - rect[0][1] + if dx01 * dx03 + dy01 * dy03 != 0: + err = "Illegal rectangle" + elif dx01 != 0 and dy01 != 0 and abs(dx01) != abs(dy01): + err = "Illegal rectangle" + elif (rect[1][0] + dx03, rect[1][1] + dy03) != rect[2]: + err = "Illegal rectangle" + else: + for i in range(4): + x, y = rect[i] + tx, ty = rect[(i + 1) % 4] + dx, dy = sgn(tx - x), sgn(ty - y) + d = DIRI[(dx, dy)] + while (x, y) != (tx, ty): + if (x, y) != rect[i] and has[x][y]: + err = f"There is an obstacle at ({x}, {y})" + break + if used[x][y][d]: + err = "Overlapped rectangles" + break + x += dx + y += dy + if used[x][y][d ^ 4]: + err = "Overlapped rectangles" + break + if err: + break + if err: + raise Invalid(f"{err} (turn: {t})") + has[rect[0][0]][rect[0][1]] = True + for i in range(4): + x, y = rect[i] + tx, ty = rect[(i + 1) % 4] + dx, dy = sgn(tx - x), sgn(ty - y) + d = DIRI[(dx, dy)] + while (x, y) != (tx, ty): + used[x][y][d] = True + x += dx + y += dy + used[x][y][d ^ 4] = True + num = sum(weight(p, N) for p in ps) + sum(weight(r[0], N) for r in rects) + den = sum(weight((i, j), N) for i in range(N) for j in range(N)) + score = rust_round(1e6 * (N * N) / M * num / den) + return float(score), {"K": K} diff --git a/graders/ale_ahc017/check.py b/graders/ale_ahc017/check.py new file mode 100644 index 0000000000000000000000000000000000000000..dfe386ce38d7fd278f199fce646619751a3fd08b --- /dev/null +++ b/graders/ale_ahc017/check.py @@ -0,0 +1,89 @@ +"""ALE-Bench ahc017 (AHC 017 "Road Repair"): Python port of the official tools/src/lib.rs (parse_output + +compute_score). All-pairs shortest paths per day via scipy's Dijkstra (float64 holds the integer path lengths, +all <= 1e9 < 2^53, exactly); unreachable pairs count as 1e9 as in the tool. The final division replicates +Rust's `num as f64 / den as f64 * 1000.0` and f64::round. Answer = the contestant's stdout text.""" +import math +import re + +import numpy as np +from scipy.sparse import csr_matrix +from scipy.sparse.csgraph import dijkstra + +from run import Invalid + +INF = 1_000_000_000 +_UINT = re.compile(r"\+?[0-9]+\Z") # Rust usize::from_str: optional '+', ASCII digits +_WS = re.compile(r"[\t\n\x0b\x0c\r ]+") +MAX_LEN = 200_000 + + +def rust_round(x): + r = math.floor(x) + return r + 1 if x - r >= 0.5 else r + + +def parse_input(text): + t = [int(x) for x in text.split()] + N, M, D, K = t[:4] + es = [(t[4 + 3 * i] - 1, t[5 + 3 * i] - 1, t[6 + 3 * i]) for i in range(M)] + return N, M, D, K, es + + +def apsp(N, es, mask): + best = {} + for (u, v, w), keep in zip(es, mask): + if keep: + a, b = (u, v) if u < v else (v, u) + if (a, b) not in best or w < best[(a, b)]: + best[(a, b)] = w + if best: + rows, cols, ws = zip(*[(a, b, w) for (a, b), w in best.items()]) + else: + rows, cols, ws = (), (), () + g = csr_matrix((np.array(ws, dtype=np.float64), (np.array(rows, dtype=np.int64), np.array(cols, dtype=np.int64))), + shape=(N, N)) + d = dijkstra(g, directed=False) + d[~np.isfinite(d)] = INF + return d.astype(np.int64) + + +def check(inst, ans): + out = ans.get("output") + if not isinstance(out, str): + raise Invalid("output must be a string") + if len(out) > MAX_LEN: + raise Invalid(f"output longer than {MAX_LEN} characters") + if not out.isascii(): + raise Invalid("output must be ASCII") + N, M, D, K, es = parse_input(inst["input"]) + tokens = [t for t in _WS.split(out) if t] + r = [] + for k in range(M): + if k >= len(tokens): + raise Invalid("Unexpected EOF") + tk = tokens[k] + if not _UINT.match(tk) or len(tk) > 25: + raise Invalid(f"Parse error: {tk[:20]}") + v = int(tk) + if v >= 2 ** 64: + raise Invalid(f"Parse error: {tk[:20]}") + if v < 1 or D < v: + raise Invalid(f"Out of range: {v}") + r.append(v) + if len(tokens) > M: + raise Invalid("Too many outputs") + count = [0] * (D + 1) + for x in r: + count[x] += 1 + for i in range(1, D + 1): + if count[i] > K: + raise Invalid(f"The number of edges to be repaired on day {i} has exceeded the limit. ({count[i]} > {K})") + iu = np.triu_indices(N, 1) + d0 = apsp(N, es, [True] * M)[iu] + num = 0 + for day in range(1, D + 1): + dk = apsp(N, es, [x != day for x in r])[iu] + num += int((dk - d0).sum()) + den = D * N * (N - 1) // 2 + avg = float(num) / float(den) * 1000.0 + return float(rust_round(avg)), {"num": num} diff --git a/graders/ale_ahc019/check.py b/graders/ale_ahc019/check.py new file mode 100644 index 0000000000000000000000000000000000000000..c4a1acaaa28d9a1560cd1d03bc54ff2f531ceefd --- /dev/null +++ b/graders/ale_ahc019/check.py @@ -0,0 +1,143 @@ +"""ALE-Bench ahc019 (AHC 019 "Silhouette Block Puzzle Creation"): Python port of the official +tools/src/lib.rs (parse_output, compute_score, is_same with the tool's own rotation enumeration). +Answer = the contestant's stdout text. Lower is better.""" +import re + +from run import Invalid + +_UINT = re.compile(r"\+?[0-9]+\Z") # Rust usize::from_str: optional '+', ASCII digits +_WS = re.compile(r"[\t\n\x0b\x0c\r ]+") +MAX_LEN = 1_000_000 +D3 = [(0, 0, -1), (0, 0, 1), (0, -1, 0), (0, 1, 0), (-1, 0, 0), (1, 0, 0)] + + +def read(tokens, pos, lb, ub): + if pos >= len(tokens): + raise Invalid("Unexpected EOF") + t = tokens[pos] + if not _UINT.match(t) or len(t) > 25 or int(t) >= 2 ** 64: + raise Invalid(f"Parse error: {t[:20]}") + v = int(t) + if v < lb or ub < v: + raise Invalid(f"Out of range: {v}") + return v + + +def parse_input(text): + tok = text.split() + D = int(tok[0]) + k = 1 + f, r = [], [] + for _ in range(2): + f.append([[int(c) for c in tok[k + z]] for z in range(D)]) + k += D + r.append([[int(c) for c in tok[k + z]] for z in range(D)]) + k += D + return D, f, r + + +def normalize(b): + mx = min(p[0] for p in b) + my = min(p[1] for p in b) + mz = min(p[2] for p in b) + return [(x - mx, y - my, z - mz) for (x, y, z) in b] + + +def is_same(b1, b2): + if len(b1) != len(b2): + return False + b1 = sorted(normalize(b1)) + b2 = normalize(b2) + max_x = max(p[0] for p in b2) + max_y = max(p[1] for p in b2) + max_z = max(p[2] for p in b2) + for i in range(6): + for _ in range(4): + b2.sort() + if b1 == b2: + return True + b2 = [(max_y - y, x, z) for (x, y, z) in b2] + max_x, max_y = max_y, max_x + if i & 1: + b2 = [(x, max_z - z, y) for (x, y, z) in b2] + max_y, max_z = max_z, max_y + else: + b2 = [(z, y, max_x - x) for (x, y, z) in b2] + max_x, max_z = max_z, max_x + return False + + +def check(inst, ans): + out = ans.get("output") + if not isinstance(out, str): + raise Invalid("output must be a string") + if len(out) > MAX_LEN: + raise Invalid(f"output longer than {MAX_LEN} characters") + if not out.isascii(): + raise Invalid("output must be ASCII") + D, F, R = parse_input(inst["input"]) + tokens = [t for t in _WS.split(out) if t] + n = read(tokens, 0, 0, 1000000) + b = [] + p = 1 + for i in range(2): + bi = [[[0] * D for _ in range(D)] for _ in range(D)] + for x in range(D): + for y in range(D): + for z in range(D): + bi[x][y][z] = read(tokens, p, 0, n) + p += 1 + b.append(bi) + if len(tokens) > p: + raise Invalid("Too many outputs") + pos = [dict(), dict()] + for i in range(2): + bi = b[i] + f = [[0] * D for _ in range(D)] + r = [[0] * D for _ in range(D)] + visited = [[[False] * D for _ in range(D)] for _ in range(D)] + for x in range(D): + for y in range(D): + for z in range(D): + bid = bi[x][y][z] + if bid != 0: + f[z][x] = 1 + r[z][y] = 1 + lst = pos[i].setdefault(bid, []) + lst.append((x, y, z)) + if len(lst) == 1: + visited[x][y][z] = True + stack = [(x, y, z)] + while stack: + cx, cy, cz = stack.pop() + for dx, dy, dz in D3: + x2, y2, z2 = cx + dx, cy + dy, cz + dz + if 0 <= x2 < D and 0 <= y2 < D and 0 <= z2 < D and bi[x2][y2][z2] == bid \ + and not visited[x2][y2][z2]: + visited[x2][y2][z2] = True + stack.append((x2, y2, z2)) + elif not visited[x][y][z]: + raise Invalid(f"block {bid} is not connected in the object {i + 1}") + if f != F[i]: + raise Invalid(f"The front silhouette for object {i + 1} does not match.") + if r != R[i]: + raise Invalid(f"The right silhouette for object {i + 1} does not match.") + used = set(pos[0]) | set(pos[1]) + if len(used) != n: + raise Invalid("some block is not used") + s = 0.0 + for bid in range(1, n + 1): + p0, p1 = pos[0].get(bid, []), pos[1].get(bid, []) + if not p0 or not p1: + s += float(len(p0) + len(p1)) + elif is_same(p0, p1): + s += 1.0 / len(p0) + else: + raise Invalid(f"The shape of block {bid} differs between objects 1 and 2.") + return float(round_half_away(1e9 * s)), {"n": n} + + +def round_half_away(x): + import math + r = math.floor(x) + return r + 1 if x - r >= 0.5 else r diff --git a/graders/ale_ahc021/check.py b/graders/ale_ahc021/check.py new file mode 100644 index 0000000000000000000000000000000000000000..cd66e8c63ec15c29564eb9a08c8277843dadcfae --- /dev/null +++ b/graders/ale_ahc021/check.py @@ -0,0 +1,76 @@ +"""ALE-Bench ahc021 (AHC 021 "Pyramid Sorting"): Python port of the official tools/src/lib.rs +(parse_output + compute_score + is_adj). Answer = the contestant's stdout text.""" +import re + +from run import Invalid + +N = 30 +_UINT = re.compile(r"\+?[0-9]+\Z") # Rust usize::from_str: optional '+', ASCII digits +_WS = re.compile(r"[\t\n\x0b\x0c\r ]+") +MAX_LEN = 1_000_000 + + +def read(tokens, pos, lb, ub): + if pos >= len(tokens): + raise Invalid("Unexpected EOF") + t = tokens[pos] + if not _UINT.match(t) or len(t) > 25 or int(t) >= 2 ** 64: + raise Invalid(f"Parse error: {t[:20]}") + v = int(t) + if v < lb or ub < v: + raise Invalid(f"Out of range: {v}") + return v + + +def is_adj(p, q): + (x1, y1), (x2, y2) = p, q + if x1 == x2: + return y1 == y2 + 1 or y1 + 1 == y2 + if x1 + 1 == x2: + return y1 == y2 or y1 + 1 == y2 + if x1 == x2 + 1: + return y1 == y2 or y1 == y2 + 1 + return False + + +def check(inst, ans): + out = ans.get("output") + if not isinstance(out, str): + raise Invalid("output must be a string") + if len(out) > MAX_LEN: + raise Invalid(f"output longer than {MAX_LEN} characters") + if not out.isascii(): + raise Invalid("output must be ASCII") + vals = [int(t) for t in inst["input"].split()] + bs, k = [], 0 + for i in range(N): + bs.append(vals[k:k + i + 1]) + k += i + 1 + tokens = [t for t in _WS.split(out) if t] + K = read(tokens, 0, 0, 10000) + if K == 0: + raise Invalid("K = 0 is not accepted in this conversion (perform at least one operation)") + p = 1 + ops = [] + for _ in range(K): + x1 = read(tokens, p, 0, N - 1) + y1 = read(tokens, p + 1, 0, x1) + x2 = read(tokens, p + 2, 0, N - 1) + y2 = read(tokens, p + 3, 0, x2) + p += 4 + ops.append(((x1, y1), (x2, y2))) + if len(tokens) > p: + raise Invalid("Too many output") + for t, (a, b) in enumerate(ops): + if not is_adj(a, b): + raise Invalid(f"{a} and {b} are not adjacent (turn {t})") + bs[a[0]][a[1]], bs[b[0]][b[1]] = bs[b[0]][b[1]], bs[a[0]][a[1]] + num = 0 + for x in range(N - 1): + for y in range(x + 1): + if bs[x][y] > bs[x + 1][y]: + num += 1 + if bs[x][y] > bs[x + 1][y + 1]: + num += 1 + score = (10000 - K) * 5 + 50000 if num == 0 else 50000 - num * 50 + return float(score), {"K": K, "E": num} diff --git a/graders/ale_ahc024/check.py b/graders/ale_ahc024/check.py new file mode 100644 index 0000000000000000000000000000000000000000..b57766ff2356dba76c49257fd9da5dbbe7506996 --- /dev/null +++ b/graders/ale_ahc024/check.py @@ -0,0 +1,106 @@ +"""ALE-Bench ahc024 (Topological Map): exact Python port of the official tools/src/lib.rs +(parse_output + compute_score). Score = 1 + #squares of colour 0 in the LAST map output; WA -> Invalid.""" +import re + +from run import Invalid + +MAX_CHARS = 2_000_000 +_UINT = re.compile(r"\+?[0-9]+\Z") + + +def _text(ans): + s = ans.get("output") + if not isinstance(s, str): + raise Invalid("output must be a string") + if len(s) > MAX_CHARS: + raise Invalid(f"output longer than {MAX_CHARS} characters") + if any(not (" " <= ch <= "~" or ch in "\t\n\r") for ch in s): + raise Invalid("output may contain printable ASCII, spaces, tabs and newlines only") + return s + + +def _read(tok, lb, ub): + if tok is None: + raise Invalid("Unexpected EOF") + if not _UINT.match(tok): + raise Invalid(f"Parse error: {tok}") + v = int(tok) + if v < lb or v > ub: + raise Invalid(f"Out of range: {v}") + return v + + +def parse_input(text): + t = text.split() + n, m = int(t[0]), int(t[1]) + cs = [[int(t[2 + i * n + j]) for j in range(n)] for i in range(n)] + return n, m, cs + + +def _adj(cs, n, m): + adj = set() + for i in range(n): + for j in range(n): + c = cs[i][j] + if c != 0 and (i == 0 or j == 0 or i + 1 == n or j + 1 == n): + adj.add((0, c)) + if i + 1 < n and c != cs[i + 1][j]: + d = cs[i + 1][j] + adj.add((min(c, d), max(c, d))) + if j + 1 < n and c != cs[i][j + 1]: + d = cs[i][j + 1] + adj.add((min(c, d), max(c, d))) + return adj + + +def check(inst, ans): + s = _text(ans) + n, m, cs = parse_input(inst["input"]) + outs, out = [], [] + for line in s.split("\n"): + line = line.strip() + if not line: + continue + toks = line.split() + row = [_read(toks[k] if k < len(toks) else None, 0, m) for k in range(n)] + if len(toks) > n: + raise Invalid("illegal output format") + out.append(row) + if len(out) == n: + outs.append(out) + out = [] + if out: + raise Invalid("illegal output format") + if not outs: + raise Invalid("empty output") + d = outs[-1] + a0, a1 = _adj(cs, n, m), _adj(d, n, m) + if a0 != a1: + raise Invalid("adjacency differs from the original map") + done = [False] * (m + 1) + vis = [[False] * n for _ in range(n)] + for i in range(n): + for j in range(n): + if vis[i][j]: + continue + c = d[i][j] + if c > 0: + if done[c]: + raise Invalid(f"Squares of color {c} are not connected.") + done[c] = True + stack = [(i, j)] + vis[i][j] = True + outer = False + while stack: + x, y = stack.pop() + for dx, dy in ((0, 1), (1, 0), (0, -1), (-1, 0)): + x2, y2 = x + dx, y + dy + if not (0 <= x2 < n and 0 <= y2 < n): + outer = True + elif d[x][y] == d[x2][y2] and not vis[x2][y2]: + vis[x2][y2] = True + stack.append((x2, y2)) + if c == 0 and not outer: + raise Invalid("Squares of color 0 are not connected.") + zeros = sum(row.count(0) for row in d) + return float(1 + zeros), {"zeros": zeros, "maps_output": len(outs)} diff --git a/graders/ale_ahc026/check.py b/graders/ale_ahc026/check.py new file mode 100644 index 0000000000000000000000000000000000000000..94937d917de5c448d8fb62de98a8cd51c75141a1 --- /dev/null +++ b/graders/ale_ahc026/check.py @@ -0,0 +1,80 @@ +"""ALE-Bench ahc026 (Stack of Boxes): exact Python port of the official tools/src/lib.rs +(parse_output + compute_score_details). Score = max(1, 10000 - V); WA (illegal op / unfinished) -> Invalid.""" +import re + +from run import Invalid + +MAX_CHARS = 200_000 +_UINT = re.compile(r"\+?[0-9]+\Z") + + +def _tokens(ans): + s = ans.get("output") + if not isinstance(s, str): + raise Invalid("output must be a string") + if len(s) > MAX_CHARS: + raise Invalid(f"output longer than {MAX_CHARS} characters") + if any(not (" " <= ch <= "~" or ch in "\t\n\r") for ch in s): + raise Invalid("output may contain printable ASCII, spaces, tabs and newlines only") + return s.split() + + +def _read(toks, k, lb, ub): + if k >= len(toks): + raise Invalid("Unexpected EOF") + tok = toks[k] + if not _UINT.match(tok): + raise Invalid(f"Parse error: {tok}") + v = int(tok) + if v < lb or v > ub: + raise Invalid(f"Out of range: {v}") + return v + + +def parse_input(text): + t = list(map(int, text.split())) + n, m = t[0], t[1] + h = n // m + return n, m, [t[2 + i * h: 2 + (i + 1) * h] for i in range(m)] + + +def check(inst, ans): + toks = _tokens(ans) + n, m, bs = parse_input(inst["input"]) + ops, k = [], 0 + while k < len(toks): + ops.append((_read(toks, k, 1, n), _read(toks, k + 1, 0, m))) + k += 2 + if len(ops) > 5000: + raise Invalid("Too many output") + where = {} + for i, st in enumerate(bs): + for b in st: + where[b] = i + cost, t = 0, 0 + for v, to in ops: + if v not in where: + raise Invalid(f"Box {v} has already been taken out.") + i = where[v] + j = bs[i].index(v) + if to == 0: + if j + 1 != len(bs[i]): + raise Invalid(f"Box {v} is not at the top of the stack.") + if v != t + 1: + raise Invalid(f"Before carrying out box {v}, all boxes less than {v} must be carried out.") + bs[i].pop() + del where[v] + t += 1 + else: + cost += len(bs[i]) - j + 1 + to -= 1 + if i != to: + moved = bs[i][j:] + bs[to].extend(moved) + del bs[i][j:] + for b in moved: + where[b] = to + if t < n: + raise Invalid(f"Not finished ({t} / {n})") + score = max(1, 10000 - cost) + return float(score), {"energy": cost, "operations": len(ops)} diff --git a/graders/ale_ahc032/check.py b/graders/ale_ahc032/check.py new file mode 100644 index 0000000000000000000000000000000000000000..8f92a7222a3d06475f33d0efb731039b957239d5 --- /dev/null +++ b/graders/ale_ahc032/check.py @@ -0,0 +1,71 @@ +"""ALE-Bench ahc032 (Mod Stamp): exact Python port of the official tools/src/lib.rs +(parse_output + compute_score_details). Score = sum of (b_ij mod 998244353); WA -> Invalid. +Only deviation: L = 0 (the do-nothing output) is rejected.""" +import re + +from run import Invalid + +MOD = 998244353 +MAX_CHARS = 100_000 +_UINT = re.compile(r"\+?[0-9]+\Z") + + +def _tokens(ans): + s = ans.get("output") + if not isinstance(s, str): + raise Invalid("output must be a string") + if len(s) > MAX_CHARS: + raise Invalid(f"output longer than {MAX_CHARS} characters") + if any(not (" " <= ch <= "~" or ch in "\t\n\r") for ch in s): + raise Invalid("output may contain printable ASCII, spaces, tabs and newlines only") + return s.split() + + +def _read(toks, k, lb, ub): + if k >= len(toks): + raise Invalid("Unexpected EOF") + tok = toks[k] + if not _UINT.match(tok): + raise Invalid(f"Parse error: {tok}") + v = int(tok) + if v < lb or v > ub: + raise Invalid(f"Out of range: {v}") + return v + + +def parse_input(text): + t = list(map(int, text.split())) + N, M, K = t[0], t[1], t[2] + p = 3 + a = [t[p + i * N: p + (i + 1) * N] for i in range(N)] + p += N * N + s = [] + for _ in range(M): + s.append([t[p + 3 * x: p + 3 * x + 3] for x in range(3)]) + p += 9 + return N, M, K, a, s + + +def check(inst, ans): + toks = _tokens(ans) + N, M, K, a, s = parse_input(inst["input"]) + L = _read(toks, 0, 0, K) + if L == 0: + # conversion deviation (stricter than the tool): the empty plan L = 0 is not accepted + raise Invalid("this conversion requires at least one operation (L >= 1)") + ops, k = [], 1 + for _ in range(L): + m = _read(toks, k, 0, M - 1) + i = _read(toks, k + 1, 0, N - 3) + j = _read(toks, k + 2, 0, N - 3) + ops.append((m, i, j)) + k += 3 + if k < len(toks): + raise Invalid("Too many outputs") + b = [list(r) for r in a] + for m, i, j in ops: + for x in range(3): + for y in range(3): + b[i + x][j + y] = (b[i + x][j + y] + s[m][x][y]) % MOD + score = sum(map(sum, b)) + return float(score), {"operations": L} diff --git a/graders/ale_ahc038/check.py b/graders/ale_ahc038/check.py new file mode 100644 index 0000000000000000000000000000000000000000..d39bef98e7feb69c1b538beeff9ea3fc222b3869 --- /dev/null +++ b/graders/ale_ahc038/check.py @@ -0,0 +1,140 @@ +"""ALE-Bench ahc038 (Tree Robot Arm): exact Python port of the official tools/src/lib.rs +(parse_output + State::apply + compute_score_details). Absolute score (minimize) = number of turns K if every +target holds a takoyaki at the end, else 10^5 + 1000 (M - M'). Any tool error -> Invalid.""" +import re + +from run import Invalid + +MAX_CHARS = 3_500_000 +_UINT = re.compile(r"\+?[0-9]+\Z") +_INT = re.compile(r"[+-]?[0-9]+\Z") +DIJ = ((0, 1), (1, 0), (0, -1), (-1, 0)) + + +def _tokens(ans): + s = ans.get("output") + if not isinstance(s, str): + raise Invalid("output must be a string") + if len(s) > MAX_CHARS: + raise Invalid(f"output longer than {MAX_CHARS} characters") + if any(not (" " <= ch <= "~" or ch in "\t\n\r") for ch in s): + raise Invalid("output may contain printable ASCII, spaces, tabs and newlines only") + return s.split() + + +def _read(toks, k, lb, ub, signed=False): + if k >= len(toks): + raise Invalid("Unexpected EOF") + tok = toks[k] + if not (_INT if signed else _UINT).match(tok): + raise Invalid(f"Parse error: {tok}") + v = int(tok) + if signed and not (-2 ** 31 <= v < 2 ** 31): + raise Invalid(f"Parse error: {tok}") + if v < lb or v > ub: + raise Invalid(f"Out of range: {v}") + return v + + +def parse_input(text): + t = text.split() + N, M, V = int(t[0]), int(t[1]), int(t[2]) + s = [[c == "1" for c in t[3 + i]] for i in range(N)] + tt = [[c == "1" for c in t[3 + N + i]] for i in range(N)] + return N, M, V, s, tt + + +def check(inst, ans): + toks = _tokens(ans) + N, M, Vmax, s, tgt = parse_input(inst["input"]) + V = _read(toks, 0, 1, Vmax) + k = 1 + pL = [] + for u in range(1, V): + p = _read(toks, k, 0, u - 1) + L = _read(toks, k + 1, 1, N - 1) + pL.append((p, L)) + k += 2 + rx = _read(toks, k, 0, N - 1, signed=True) + ry = _read(toks, k + 1, 0, N - 1, signed=True) + k += 2 + S = toks[k:] + for st in S: + if len(st) != 2 * V: + raise Invalid("Invalid operation length") + if len(S) > 100000: + raise Invalid("Too many output") + is_leaf = [True] * V + for p, _ in pL: + is_leaf[p] = False + dirs = [0] * V + has = [False] * V + board = [list(r) for r in s] + chain = [] # path root->u as list of vertices (excluding root) + for u in range(V): + c, w = [], u + while w > 0: + c.append(w) + w = pL[w - 1][0] + chain.append(c[::-1]) + + def get(u): + x, y, d = rx, ry, 0 + for w in chain[u]: + d = (d + dirs[w]) % 4 + L = pL[w - 1][1] + x += L * DIJ[d][0] + y += L * DIJ[d][1] + return x, y + + for st in S: + c0 = st[0] + if c0 == "U": + rx -= 1 + if rx < 0: + raise Invalid("The root coordinate is out of range.") + elif c0 == "D": + rx += 1 + if rx == N: + raise Invalid("The root coordinate is out of range.") + elif c0 == "L": + ry -= 1 + if ry < 0: + raise Invalid("The root coordinate is out of range.") + elif c0 == "R": + ry += 1 + if ry == N: + raise Invalid("The root coordinate is out of range.") + elif c0 != ".": + raise Invalid(f"Invalid operation: {c0}") + for i in range(1, V): + c = st[i] + if c == "L": + dirs[i] = (dirs[i] + 3) % 4 + elif c == "R": + dirs[i] = (dirs[i] + 1) % 4 + elif c != ".": + raise Invalid(f"Invalid operation: {c}") + for i in range(V): + c = st[V + i] + if c == "P": + if not is_leaf[i]: + raise Invalid(f"The vertex {i} is not a leaf.") + x, y = get(i) + if x < 0 or y < 0 or x >= N or y >= N: + raise Invalid("The leaf coordinate is out of range.") + if has[i]: + if board[x][y]: + raise Invalid("You cannot put multiple takoyaki on the same square.") + has[i] = False + board[x][y] = True + else: + if not board[x][y]: + raise Invalid(f"({x}, {y}) does not contain takoyaki.") + has[i] = True + board[x][y] = False + elif c != ".": + raise Invalid(f"Invalid operation: {c}") + M2 = sum(1 for i in range(N) for j in range(N) if tgt[i][j] and board[i][j]) + score = len(S) if M2 == M else 100000 + 1000 * (M - M2) + return float(score), {"turns": len(S), "on_target": M2} diff --git a/graders/ale_ahc039/check.py b/graders/ale_ahc039/check.py new file mode 100644 index 0000000000000000000000000000000000000000..fe484655ad4413533c0ea05a25b620d159f8d9ce --- /dev/null +++ b/graders/ale_ahc039/check.py @@ -0,0 +1,102 @@ +"""ALE-Bench ahc039 (Purse Seine Fishing): exact Python port of the official tools/src/lib.rs +(parse_output + compute_score_details), vectorised with numpy (integer arithmetic only). +Score = max(0, a - b + 1) for the LAST polygon output; tool errors -> Invalid.""" +import re + +import numpy as np + +from run import Invalid + +D = 100000 +MAX_CHARS = 2_000_000 +_INT = re.compile(r"[+-]?[0-9]+\Z") + + +def _tokens(ans): + s = ans.get("output") + if not isinstance(s, str): + raise Invalid("output must be a string") + if len(s) > MAX_CHARS: + raise Invalid(f"output longer than {MAX_CHARS} characters") + if any(not (" " <= ch <= "~" or ch in "\t\n\r") for ch in s): + raise Invalid("output may contain printable ASCII, spaces, tabs and newlines only") + return s.split() + + +def _read(toks, k, lb, ub): + if k >= len(toks): + raise Invalid("Unexpected EOF") + tok = toks[k] + if not _INT.match(tok) or not (-2 ** 63 <= int(tok) < 2 ** 63): # Rust i64 / usize parse + raise Invalid(f"Parse error: {tok}") + v = int(tok) + if v < lb or v > ub: + raise Invalid(f"Out of range: {v}") + return v + + +def parse_input(text): + t = list(map(int, text.split())) + N = t[0] + ps = np.array(t[1:1 + 4 * N], dtype=np.int64).reshape(2 * N, 2) + return N, ps + + +def check(inst, ans): + toks = _tokens(ans) + N, ps = parse_input(inst["input"]) + polys, k = [], 0 + while k < len(toks): + tok = toks[k] + if tok.startswith("-"): # m is read as usize: a sign '-' is a parse error + raise Invalid(f"Parse error: {tok}") + m = _read(toks, k, 4, 1000) + k += 1 + poly = [] + for _ in range(m): + poly.append((_read(toks, k, 0, D), _read(toks, k + 1, 0, D))) + k += 2 + polys.append(poly) + out = polys[-1] if polys else [] + m = len(out) + if m == 0: + return 1.0, {"mackerels": 0, "sardines": 0, "vertices": 0, "length": 0} + length = 0 + for i in range(m): + p, q, r = out[i], out[(i + 1) % m], out[(i + 2) % m] + if p == q: + raise Invalid("Two consecutive vertices share the same coordinates.") + elif p[0] == q[0]: + length += abs(p[1] - q[1]) + if q[0] == r[0] and (p[1] - q[1]) * (r[1] - q[1]) > 0: + raise Invalid("The polygon is self-intersecting.") + elif p[1] == q[1]: + length += abs(p[0] - q[0]) + if q[1] == r[1] and (p[0] - q[0]) * (r[0] - q[0]) > 0: + raise Invalid("The polygon is self-intersecting.") + else: + raise Invalid(f"The {i}-th edge is not parallel to the axes.") + P = np.array(out, dtype=np.int64) + Q = np.roll(P, -1, axis=0) + xlo, xhi = np.minimum(P[:, 0], Q[:, 0]), np.maximum(P[:, 0], Q[:, 0]) + ylo, yhi = np.minimum(P[:, 1], Q[:, 1]), np.maximum(P[:, 1], Q[:, 1]) + idx = np.arange(m) + for off in range(2, m - 1): # non-adjacent edge pairs (i, i+off), as in the Rust loop + j = (idx + off) % m + hit = (np.maximum(xlo, xlo[j]) <= np.minimum(xhi, xhi[j])) & \ + (np.maximum(ylo, ylo[j]) <= np.minimum(yhi, yhi[j])) + if hit.any(): + raise Invalid("The polygon is self-intersecting.") + if length > 4 * D: + raise Invalid(f"The length is too long: {length}.") + rx, ry = ps[:, 0], ps[:, 1] + on_edge = np.zeros(len(ps), dtype=bool) + parity = np.zeros(len(ps), dtype=bool) + for e in range(m): + on_edge |= (xlo[e] <= rx) & (rx <= xhi[e]) & (ylo[e] <= ry) & (ry <= yhi[e]) + if P[e, 1] == Q[e, 1]: + parity ^= (P[e, 1] > ry) & (xlo[e] <= rx) & (rx < xhi[e]) + inside = on_edge | parity + a = int(inside[:N].sum()) + b = int(inside[N:].sum()) + return float(max(0, 1 + a - b)), {"mackerels": a, "sardines": b, "vertices": m, "length": length} diff --git a/graders/ale_ahc041/check.py b/graders/ale_ahc041/check.py new file mode 100644 index 0000000000000000000000000000000000000000..524d209d5eaa630da405d9a73553f87d21eca721 --- /dev/null +++ b/graders/ale_ahc041/check.py @@ -0,0 +1,80 @@ +"""ALE-Bench ahc041 (Christmas Tree Cutting): exact Python port of the official tools/src/lib.rs +(parse_output + to_tree_nodes + compute_score_details). Score = 1 + sum_v A_v (h_v + 1) for the LAST +parent vector output; tool errors -> Invalid.""" +import re + +from run import Invalid + +MAX_CHARS = 2_000_000 +_INT = re.compile(r"[+-]?[0-9]+\Z") + + +def _tokens(ans): + s = ans.get("output") + if not isinstance(s, str): + raise Invalid("output must be a string") + if len(s) > MAX_CHARS: + raise Invalid(f"output longer than {MAX_CHARS} characters") + if any(not (" " <= ch <= "~" or ch in "\t\n\r") for ch in s): + raise Invalid("output may contain printable ASCII, spaces, tabs and newlines only") + return s.split() + + +def parse_input(text): + t = list(map(int, text.split())) + N, M, H = t[0], t[1], t[2] + A = t[3:3 + N] + p = 3 + N + edges = set() + for i in range(M): + edges.add((t[p + 2 * i], t[p + 2 * i + 1])) + return N, M, H, A, edges + + +def check(inst, ans): + toks = _tokens(ans) + N, M, H, A, edges = parse_input(inst["input"]) + outs, k = [], 0 + while k < len(toks): + par = [] + for _ in range(N): + if k >= len(toks): + raise Invalid("Unexpected EOF") + tok = toks[k] + if not _INT.match(tok) or not (-2 ** 31 <= int(tok) < 2 ** 31): # Rust i32 parse + raise Invalid(f"Parse error: {tok}") + v = int(tok) + if not (-1 <= v < N): + raise Invalid(f"Out of range: {v}") + par.append(v) + k += 1 + outs.append(par) + if not outs: + raise Invalid("empty output") + par = outs[-1] + children = [[] for _ in range(N)] + indeg = [0] * N + for v, p in enumerate(par): + if p == -1: + continue + if (min(v, p), max(v, p)) not in edges: + raise Invalid(f"Edge ({v}, {p}) is not included in the original graph.") + indeg[v] += 1 + children[p].append(v) + h = [None] * N + for r in range(N): + if indeg[r] == 0: + stack = [(r, 0)] + while stack: + v, d = stack.pop() + h[v] = d + for c in children[v]: + stack.append((c, d + 1)) + for v in range(N): + if h[v] is None: + raise Invalid(f"The connected component that contains vertex {v} is not a rooted tree.") + for v in range(N): + if h[v] > H: + raise Invalid(f"Vertex {v} is too high (h = {h[v]}).") + score = 1 + sum(A[v] * (h[v] + 1) for v in range(N)) + return float(score), {"roots": sum(1 for p in par if p == -1), "max_height": max(h)} diff --git a/graders/ale_ahc042/check.py b/graders/ale_ahc042/check.py new file mode 100644 index 0000000000000000000000000000000000000000..df7e46982a53cf86287fa0a91307bd2ab8fc1156 --- /dev/null +++ b/graders/ale_ahc042/check.py @@ -0,0 +1,72 @@ +"""ALE-Bench ahc042 (Oni wa Soto, Fuku wa Uchi): exact Python port of the official tools/src/lib.rs +(parse_output + compute_score_details). Score = 8N^2 - T if all Oni removed and no Fukunokami removed, +else 4N^2 - N(X + Y); tool errors -> Invalid.""" +import re + +from run import Invalid + +MAX_CHARS = 100_000 +_UINT = re.compile(r"\+?[0-9]+\Z") + + +def _tokens(ans): + s = ans.get("output") + if not isinstance(s, str): + raise Invalid("output must be a string") + if len(s) > MAX_CHARS: + raise Invalid(f"output longer than {MAX_CHARS} characters") + if any(not (" " <= ch <= "~" or ch in "\t\n\r") for ch in s): + raise Invalid("output may contain printable ASCII, spaces, tabs and newlines only") + return s.split() + + +def parse_input(text): + t = text.split() + n = int(t[0]) + return n, [list(t[1 + i]) for i in range(n)] + + +def check(inst, ans): + toks = _tokens(ans) + n, cs = parse_input(inst["input"]) + out, k = [], 0 + while k < len(toks): + d = toks[k] + if len(d) != 1: + raise Invalid(f"Parse error: {d}") + if not ("A" <= d <= "Z"): + raise Invalid(f"Out of range: {d}") + if k + 1 >= len(toks): + raise Invalid("Unexpected EOF") + tok = toks[k + 1] + if not _UINT.match(tok): + raise Invalid(f"Parse error: {tok}") + p = int(tok) + if p >= n: + raise Invalid(f"Out of range: {p}") + out.append((d, p)) + k += 2 + if len(out) > 4 * n * n: + raise Invalid("Too many operations") + for d, p in out: + if d == "L": + row = cs[p] + cs[p] = row[1:] + ["."] + elif d == "R": + row = cs[p] + cs[p] = ["."] + row[:-1] + elif d == "U": + for i in range(n - 1): + cs[i][p] = cs[i + 1][p] + cs[n - 1][p] = "." + elif d == "D": + for i in range(n - 1, 0, -1): + cs[i][p] = cs[i - 1][p] + cs[0][p] = "." + else: + raise Invalid(f"Invalid direction: {d}") + X = sum(r.count("x") for r in cs) + Y = 2 * n - sum(r.count("o") for r in cs) + T = len(out) + score = 8 * n * n - T if X == 0 and Y == 0 else 4 * n * n - n * (X + Y) + return float(score), {"T": T, "oni_left": X, "fuku_removed": Y} diff --git a/graders/ale_ahc044/check.py b/graders/ale_ahc044/check.py new file mode 100644 index 0000000000000000000000000000000000000000..2d7f7c39a119c89a21aa9e911a57a256631390ba --- /dev/null +++ b/graders/ale_ahc044/check.py @@ -0,0 +1,60 @@ +"""ALE-Bench ahc044 (Cleaning Up): exact Python port of the official tools/src/lib.rs +(parse_output + compute_score_details: a 500,000-week simulation). Score = 10^6 - E; tool errors -> Invalid.""" +import re + +from run import Invalid + +MAX_CHARS = 100_000 +_UINT = re.compile(r"\+?[0-9]+\Z") + + +def _tokens(ans): + s = ans.get("output") + if not isinstance(s, str): + raise Invalid("output must be a string") + if len(s) > MAX_CHARS: + raise Invalid(f"output longer than {MAX_CHARS} characters") + if any(not (" " <= ch <= "~" or ch in "\t\n\r") for ch in s): + raise Invalid("output may contain printable ASCII, spaces, tabs and newlines only") + return s.split() + + +def _read(toks, k, lb, ub): + if k >= len(toks): + raise Invalid("Unexpected EOF") + tok = toks[k] + if not _UINT.match(tok): + raise Invalid(f"Parse error: {tok}") + v = int(tok) + if v < lb or v > ub: + raise Invalid(f"Out of range: {v}") + return v + + +def parse_input(text): + t = list(map(int, text.split())) + n, L = t[0], t[1] + return n, L, t[2:2 + n] + + +def check(inst, ans): + toks = _tokens(ans) + n, L, T = parse_input(inst["input"]) + out, k = [], 0 + while k < len(toks): + out.append((_read(toks, k, 0, n - 1), _read(toks, k + 1, 0, n - 1))) + k += 2 + if len(out) > n: + raise Invalid("Number of lines in output is not N") + if len(out) != n: + raise Invalid("Number of lines in output is not N") + A = [a for a, _ in out] + B = [b for _, b in out] + counts = [0] * n + pos = 0 + for _ in range(L): + c = counts[pos] + 1 + counts[pos] = c + pos = A[pos] if c & 1 else B[pos] + E = sum(abs(counts[i] - T[i]) for i in range(n)) + return float(2 * L - E), {"error": E} diff --git a/graders/ale_ahc046/check.py b/graders/ale_ahc046/check.py new file mode 100644 index 0000000000000000000000000000000000000000..4f9869fbdf91ca63f6a555e7983ba84b1453ed22 --- /dev/null +++ b/graders/ale_ahc046/check.py @@ -0,0 +1,83 @@ +"""ALE-Bench ahc046 (Skating with Blocks): exact Python port of the official tools/src/lib.rs +(parse_output + compute_score_details). Score = M + 2NM - T if every target is visited in order, else the +number of visited squares (initial square included); tool errors -> Invalid.""" +from run import Invalid + +MAX_CHARS = 100_000 +DIR = "UDLR" +DIJ = ((-1, 0), (1, 0), (0, -1), (0, 1)) + + +def _tokens(ans): + s = ans.get("output") + if not isinstance(s, str): + raise Invalid("output must be a string") + if len(s) > MAX_CHARS: + raise Invalid(f"output longer than {MAX_CHARS} characters") + if any(not (" " <= ch <= "~" or ch in "\t\n\r") for ch in s): + raise Invalid("output may contain printable ASCII, spaces, tabs and newlines only") + return s.split() + + +def _char(toks, k): + if k >= len(toks): + raise Invalid("Unexpected EOF") + c = toks[k] + if len(c) != 1: + raise Invalid(f"Parse error: {c}") + if not ("A" <= c <= "Z"): + raise Invalid(f"Out of range: {c}") + return c + + +def parse_input(text): + t = list(map(int, text.split())) + N, M = t[0], t[1] + return N, [(t[2 + 2 * k], t[3 + 2 * k]) for k in range(M)] + + +def check(inst, ans): + toks = _tokens(ans) + N, ps = parse_input(inst["input"]) + out, k = [], 0 + while k < len(toks): + a = _char(toks, k) + d = _char(toks, k + 1) + k += 2 + if d not in DIR: + raise Invalid(f"Invalid direction: {d}") + if a not in "MSA": + raise Invalid(f"Invalid action: {a}") + out.append((a, DIR.index(d))) + if len(out) > 2 * N * len(ps): + raise Invalid(f"Too many actions: {len(out)}") + pi, pj = ps[0] + done = 1 + block = [[False] * N for _ in range(N)] + for a, d in out: + di, dj = DIJ[d] + if a == "M": + ni, nj = pi + di, pj + dj + if not (0 <= ni < N and 0 <= nj < N): + raise Invalid(f"Out of range (M {DIR[d]})") + if block[ni][nj]: + raise Invalid(f"Blocked (M {DIR[d]})") + pi, pj = ni, nj + elif a == "S": + while True: + ni, nj = pi + di, pj + dj + if not (0 <= ni < N and 0 <= nj < N) or block[ni][nj]: + break + pi, pj = ni, nj + else: + ni, nj = pi + di, pj + dj + if not (0 <= ni < N and 0 <= nj < N): + raise Invalid(f"Out of range (A {DIR[d]})") + block[ni][nj] = not block[ni][nj] + if done < len(ps) and ps[done] == (pi, pj): + done += 1 + if done < len(ps): + score = done + else: + score = len(ps) + 2 * N * len(ps) - len(out) + return float(score), {"visited": done, "T": len(out)} diff --git a/graders/edge_apple_incremental/check.py b/graders/edge_apple_incremental/check.py new file mode 100644 index 0000000000000000000000000000000000000000..ece79572094118385e246c3f69912d497bfc2456 --- /dev/null +++ b/graders/edge_apple_incremental/check.py @@ -0,0 +1,67 @@ +"""EdgeBench apple_incremental_game (AHC058 "Apple Incremental Game", EdgeBench CC-BY-4.0 adaptation). + +Exact port of the task's official scorer tools/bin/tester (a Python script): parse the action lines +(strip; skip blank lines and lines starting with '#'), need >= T actions (extra ones are ignored), each +action is "-1" or "i j" with 0 <= i < L, 0 <= j < N and enough apples; then simulate T turns in exact +integer arithmetic. Score = round(1e5 * log2(S)) (0 if S <= 0). Only deviations: the output must be ASCII +and at most 200,000 characters (upstream int() would also accept e.g. non-ASCII digits). +""" +import math + +from run import Invalid + +MAX_CHARS = 200_000 + + +def parse_input(txt): + lines = txt.strip().split("\n") + N, L, T, K = map(int, lines[0].split()) + A = list(map(int, lines[1].split())) + C = [list(map(int, lines[2 + i].split())) for i in range(L)] + return N, L, T, K, A, C + + +def check(inst, ans): + out = ans.get("output") + if not isinstance(out, str): + raise Invalid("output must be a string") + if len(out) > MAX_CHARS: + raise Invalid(f"output longer than {MAX_CHARS} characters") + if not out.isascii(): + raise Invalid("output must be ASCII") + N, L, T, K, A, C = parse_input(inst["input"]) + actions = [] + for line in out.strip().split("\n"): + line = line.strip() + if not line or line.startswith("#"): + continue + actions.append(line) + if len(actions) < T: + raise Invalid(f"expected {T} actions, got {len(actions)}") + B = [[1] * N for _ in range(L)] + P = [[0] * N for _ in range(L)] + apples = K + for t in range(T): + action = actions[t].strip() + if action != "-1": + parts = action.split() + if len(parts) != 2: + raise Invalid(f"invalid action format at turn {t}: {action[:50]}") + try: + i, j = int(parts[0]), int(parts[1]) + except ValueError: + raise Invalid(f"invalid action at turn {t}: {action[:50]}") + if not (0 <= i < L and 0 <= j < N): + raise Invalid(f"invalid machine at turn {t}: ({i}, {j})") + cost = C[i][j] * (P[i][j] + 1) + if apples < cost: + raise Invalid(f"not enough apples at turn {t}: have {apples}, need {cost}") + apples -= cost + P[i][j] += 1 + for j in range(N): + apples += A[j] * B[0][j] * P[0][j] + for i in range(1, L): + for j in range(N): + B[i - 1][j] += B[i][j] * P[i][j] + score = 0 if apples <= 0 else round(1e5 * math.log2(apples)) + return float(score), {"apples_log2": math.log2(apples) if apples > 0 else None} diff --git a/graders/edge_grid_turing_robot/check.py b/graders/edge_grid_turing_robot/check.py new file mode 100644 index 0000000000000000000000000000000000000000..21908eef25c9dfb31a8c13493d3007676b154e8e --- /dev/null +++ b/graders/edge_grid_turing_robot/check.py @@ -0,0 +1,114 @@ +"""EdgeBench grid_turing_robot (AHC056 "Grid Turing Robot", EdgeBench CC-BY-4.0 adaptation). + +Exact port of the task's official scorer (tools/bin/tester -> tools/src/verifier.py, Python): parse +"C Q M", N rows of initial colours, M rules "c q A S D" (extra tokens on a line are ignored, as upstream), +range/duplicate checks, then simulate at most T steps (stop when no rule exists for the current (colour, +state)); V = destinations reached in order. Score = C + Q if V = K, else 2 N^4 + (K - V) N^2 (lower is +better; a valid answer that misses destinations is still valid, with the penalty score). +Deviations: output must be ASCII and at most 1,000,000 characters. +""" +from run import Invalid + +MAX_CHARS = 1_000_000 + + +def parse_input(txt): + lines = txt.split("\n") + N, K, T = map(int, lines[0].split()) + v = [lines[1 + i].strip() for i in range(N)] + h = [lines[1 + N + i].strip() for i in range(N - 1)] + tg = [tuple(map(int, lines[2 * N + i].split())) for i in range(K)] + return N, K, T, v, h, tg + + +def check(inst, ans): + out = ans.get("output") + if not isinstance(out, str): + raise Invalid("output must be a string") + if len(out) > MAX_CHARS: + raise Invalid(f"output longer than {MAX_CHARS} characters") + if not out.isascii(): + raise Invalid("output must be ASCII") + N, K, T, v, h, targets = parse_input(inst["input"]) + s = out.replace("\r\n", "\n").replace("\r", "\n") # text-mode universal newlines, as upstream open() + lines = s.split("\n") + if s.endswith("\n"): + lines = lines[:-1] + if not lines: + raise Invalid("Empty output") + idx = 0 + try: + parts = lines[idx].split() + C, Q, M = int(parts[0]), int(parts[1]), int(parts[2]) + idx += 1 + if not (1 <= C <= N ** 4): + raise Invalid(f"C={C} out of range [1, {N ** 4}]") + if not (1 <= Q <= N ** 4): + raise Invalid(f"Q={Q} out of range [1, {N ** 4}]") + if not (0 <= M <= T): + raise Invalid(f"M={M} out of range [0, {T}]") + grid = [] + for i in range(N): + row = list(map(int, lines[idx + i].split())) + if len(row) != N: + raise Invalid(f"Row {i}: expected {N} colors, got {len(row)}") + for c in row: + if not (0 <= c < C): + raise Invalid(f"Color {c} out of range [0, {C - 1}]") + grid.append(row) + idx += N + rules = {} + for i in range(M): + parts = lines[idx + i].split() + c, q, a, st, d = int(parts[0]), int(parts[1]), int(parts[2]), int(parts[3]), parts[4] + if (c, q) in rules: + raise Invalid(f"Duplicate rule for (c={c}, q={q})") + if not (0 <= c < C): + raise Invalid(f"Rule color {c} out of range") + if not (0 <= q < Q): + raise Invalid(f"Rule state {q} out of range") + if not (0 <= a < C): + raise Invalid(f"Rule repaint {a} out of range") + if not (0 <= st < Q): + raise Invalid(f"Rule new state {st} out of range") + if d not in ("U", "D", "L", "R", "S"): + raise Invalid(f"Invalid direction: {d}") + rules[(c, q)] = (a, st, d) + except Invalid: + raise + except Exception as e: + raise Invalid(f"Output format error: {type(e).__name__}") + + def can_move(i, j, d): + if d == "U": + return i > 0 and h[i - 1][j] == "0" + if d == "D": + return i < N - 1 and h[i][j] == "0" + if d == "L": + return j > 0 and v[i][j - 1] == "0" + if d == "R": + return j < N - 1 and v[i][j] == "0" + return False + + step = {"U": (-1, 0), "D": (1, 0), "L": (0, -1), "R": (0, 1)} + ci, cj = targets[0] + cq = 0 + visited, nxt = 1, 1 + for _ in range(T): + key = (grid[ci][cj], cq) + if key not in rules: + break + a, st, d = rules[key] + grid[ci][cj] = a + cq = st + if d != "S" and can_move(ci, cj, d): + ci += step[d][0] + cj += step[d][1] + if nxt < K and (ci, cj) == targets[nxt]: + visited += 1 + nxt += 1 + if visited == K: + score = C + Q + else: + score = 2 * N ** 4 + (K - visited) * N ** 2 + return float(score), {"C": C, "Q": Q, "visited": visited, "K": K} diff --git a/graders/fco_mds/check.py b/graders/fco_mds/check.py new file mode 100644 index 0000000000000000000000000000000000000000..53697ef66e12dbb381f746356614b7c7d20c14eb --- /dev/null +++ b/graders/fco_mds/check.py @@ -0,0 +1,31 @@ +"""FrontierCO MDS: minimum dominating set of a fixed graph (vertices 1..n). Score = |D| (minimize). + +Port of FrontierCO MDS/config.py eval_func: D must be a list of distinct existing vertices and every +vertex must be in D or adjacent to a vertex of D. Stricter than upstream: entries must be JSON integers +(upstream accepted any hashable equal to a node id, e.g. 3.0 or True for vertex 1). +""" +from run import Invalid, int_list + + +def check(inst, ans): + n = inst["n"] + D = ans.get("dominating_set") + if not isinstance(D, list) or not D or len(D) > n: + raise Invalid(f"dominating_set must be a non-empty list of at most {n} vertices") + D = int_list(D, None, 1, n, "dominating_set") + if len(set(D)) != len(D): + raise Invalid("duplicate vertices in dominating_set") + dom = bytearray(n + 1) + for v in D: + dom[v] = 1 + inD = bytes(dom) + for u, v in inst["edges"]: + if inD[u]: + dom[v] = 1 + if inD[v]: + dom[u] = 1 + missing = dom.count(0, 1) + if missing: + first = dom.index(0, 1) + raise Invalid(f"{missing} vertices are not dominated (e.g. vertex {first})") + return float(len(D)), {"size": len(D)} diff --git a/graders/fcs_beacon/check.py b/graders/fcs_beacon/check.py new file mode 100644 index 0000000000000000000000000000000000000000..83c44b2ac1d48913794675011102fb81d4d70dcd --- /dev/null +++ b/graders/fcs_beacon/check.py @@ -0,0 +1,48 @@ +"""FrontierCS algorithmic/302 (Spectrum-Friendly Beacon String). Answer {"s": ""}: length n, letters among the +first k, letter i used exactly c_i times. Objective (minimize) = sum of W[s_t][s_t+1] over adjacent pairs + sum over +motifs of w * (#occurrences, overlaps counted; duplicate motifs add up), exact integers (port of chk.cc).""" +from run import Invalid + + +def _parse(text): + t = text.split() + n, k = int(t[0]), int(t[1]) + cnt = list(map(int, t[2:2 + k])) + p = 2 + k + W = [list(map(int, t[p + i * k:p + (i + 1) * k])) for i in range(k)] + p += k * k + m = int(t[p]); p += 1 + mot = {} + for i in range(m): + s, w = t[p + 2 * i], int(t[p + 2 * i + 1]) + mot[s] = mot.get(s, 0) + w + return n, k, cnt, W, mot + + +def penalty(s, k, W, mot): + a = [ord(ch) - 97 for ch in s] + tot = sum(W[a[i]][a[i + 1]] for i in range(len(a) - 1)) + lens = sorted({len(x) for x in mot}) + for L in lens: + for i in range(len(s) - L + 1): + w = mot.get(s[i:i + L]) + if w: + tot += w + return tot + + +def check(inst, ans): + n, k, cnt, W, mot = _parse(inst["input"]) + s = ans.get("s") + if not isinstance(s, str) or len(s) != n: + raise Invalid(f"s must be a string of length {n}") + got = [0] * k + for ch in s: + i = ord(ch) - 97 + if not 0 <= i < k: + raise Invalid("character outside the alphabet") + got[i] += 1 + if got != cnt: + raise Invalid("wrong letter counts") + X = penalty(s, k, W, mot) + return float(X), {"penalty": X} diff --git a/graders/fcs_digit_grid/check.py b/graders/fcs_digit_grid/check.py new file mode 100644 index 0000000000000000000000000000000000000000..283af481afc18c0bbb1b8097a565d185fa231ffa --- /dev/null +++ b/graders/fcs_digit_grid/check.py @@ -0,0 +1,68 @@ +"""FrontierCS algorithmic/110: 8 x 14 digit grid; X = largest integer such that every number 1..X can be +read along a king-move walk (8 directions, revisits allowed, no stay moves, no jumps). Maximize X. + +Port of upstream chk.cc: exactly 8 whitespace-separated tokens of exactly 14 digits each, nothing after. +canRead(s) = frontier propagation over cells, as upstream. Exact (integers only). +""" +from run import Invalid + +H, W = 8, 14 +MAX_CHARS = 10_000 +X_CAP = 10 ** 7 # cannot be reached: an 8x14 grid has < 112 * 8^6 readable 7-digit walks + + +def _neighbors(): + nb = [] + for y in range(H): + for x in range(W): + m = 0 + for dy in (-1, 0, 1): + for dx in (-1, 0, 1): + if (dy or dx) and 0 <= y + dy < H and 0 <= x + dx < W: + m |= 1 << ((y + dy) * W + x + dx) + nb.append(m) + return nb + + +NB = _neighbors() + + +def prefix_score(rows): + flat = "".join(rows) + by_digit = [0] * 10 + for i, ch in enumerate(flat): + by_digit[ord(ch) - 48] |= 1 << i + # expand(mask) = union of neighbourhoods of the cells in mask + def can_read(s): + fr = by_digit[ord(s[0]) - 48] + for ch in s[1:]: + if not fr: + return False + nxt = 0 + m = fr + while m: + low = m & -m + nxt |= NB[low.bit_length() - 1] + m ^= low + fr = nxt & by_digit[ord(ch) - 48] + return fr != 0 + X = 0 + while X < X_CAP and can_read(str(X + 1)): + X += 1 + return X + + +def check(inst, ans): + s = ans.get("output") + if not isinstance(s, str): + raise Invalid("output must be a string") + if len(s) > MAX_CHARS or not s.isascii(): + raise Invalid("output too long or not ASCII") + t = s.split() + if len(t) != H: + raise Invalid(f"expected exactly {H} rows (whitespace-separated tokens), got {len(t)}") + for r, row in enumerate(t): + if len(row) != W or any(not ("0" <= ch <= "9") for ch in row): + raise Invalid(f"row {r + 1} must be exactly {W} digits") + X = prefix_score(t) + return float(X), {"X": X} diff --git a/graders/fcs_gcd_chain/check.py b/graders/fcs_gcd_chain/check.py new file mode 100644 index 0000000000000000000000000000000000000000..1c9d2bf73cb4c24564de8710c55fac2802b5e589 --- /dev/null +++ b/graders/fcs_gcd_chain/check.py @@ -0,0 +1,50 @@ +"""FrontierCS algorithmic/41 (Brilliant Sequence of Umbrellas): a_1 < ... < a_k in [1, n] with +gcd(a_i, a_{i-1}) > gcd(a_{i-1}, a_{i-2}) for all i >= 3. Maximize V = k * (a_1 + ... + a_k). + +Port of upstream chk.cc: k in [1, 10^6], k integers in [1, n], strictly increasing, strictly increasing +consecutive gcds; nothing after the sequence. V is computed exactly (upstream: long double). +""" +import re +from math import gcd + +from run import Invalid + +_INT = re.compile(r"(0|-?[1-9][0-9]*)\Z") +MAX_CHARS = 2_000_000 + + +def _int(tok, lo, hi, name): + if not _INT.match(tok): + raise Invalid(f"{name}: expected an integer, got {tok[:20]!r}") + v = int(tok) + if v < lo or v > hi: + raise Invalid(f"{name} = {v} out of range [{lo}, {hi}]") + return v + + +def check(inst, ans): + n = inst["n"] + s = ans.get("output") + if not isinstance(s, str): + raise Invalid("output must be a string") + if len(s) > MAX_CHARS or not s.isascii(): + raise Invalid("output too long or not ASCII") + t = s.split() + if not t: + raise Invalid("empty output") + k = _int(t[0], 1, 10 ** 6, "k") + if len(t) != 1 + k: + raise Invalid(f"expected exactly {k} numbers after k, got {len(t) - 1}") + a = [_int(x, 1, n, "a_i") for x in t[1:]] + for i in range(1, k): + if a[i] <= a[i - 1]: + raise Invalid("sequence is not strictly increasing") + if k >= 3: + g = gcd(a[1], a[0]) + for i in range(2, k): + h = gcd(a[i], a[i - 1]) + if h <= g: + raise Invalid(f"gcds are not strictly increasing at position {i + 1}") + g = h + V = k * sum(a) + return float(V), {"k": k, "V": V} diff --git a/graders/fcs_inc_subseq_perm/check.py b/graders/fcs_inc_subseq_perm/check.py new file mode 100644 index 0000000000000000000000000000000000000000..aab61bcf114d80f324c0a475b79a23b8fa47d8db --- /dev/null +++ b/graders/fcs_inc_subseq_perm/check.py @@ -0,0 +1,70 @@ +"""FrontierCS algorithmic/33 (Permutation, modified): for each k_i, a permutation of {0..n-1} with exactly k_i +increasing subsequences (the empty one included). Objective = max over i of n_i (minimize). + +Port of upstream checker.cpp: per k, n then n integers in [0, n-1], all distinct, exact count == k (upstream +uses a Fenwick tree saturating at 1e18 + 1, equivalent since k <= 1e18); nothing after the last permutation. +Deviation: n <= 1000 per permutation (upstream: 5000) to bound grading time; any n > 116 is already worse than +the trivial baseline of every task. +""" +import re + +from run import Invalid + +_INT = re.compile(r"(0|-?[1-9][0-9]*)\Z") +NMAX = 1000 +MAX_CHARS = 600_000 + + +def _int(tok, lo, hi, name): + if not _INT.match(tok): + raise Invalid(f"{name}: expected an integer, got {tok[:20]!r}") + v = int(tok) + if v < lo or v > hi: + raise Invalid(f"{name} = {v} out of range [{lo}, {hi}]") + return v + + +def count_inc(p): + n = len(p) + bit = [0] * (n + 2) + total = 1 # the empty subsequence + for v in p: + i, s = v + 1, 0 # sum over values < v (Fenwick over 1..n) + while i > 0: + s += bit[i] + i -= i & -i + me = s + 1 # subsequences ending at v + total += me + i = v + 1 + 1 + while i <= n + 1: + bit[i] += me + i += i & -i + return total + + +def check(inst, ans): + ks = inst["ks"] + s = ans.get("output") + if not isinstance(s, str): + raise Invalid("output must be a string") + if len(s) > MAX_CHARS or not s.isascii(): + raise Invalid("output too long or not ASCII") + t = s.split() + pos, mx = 0, 0 + for idx, k in enumerate(ks): + if pos >= len(t): + raise Invalid(f"output ended before permutation {idx + 1}") + n = _int(t[pos], 1, NMAX, "n") + pos += 1 + if pos + n > len(t): + raise Invalid(f"output ended inside permutation {idx + 1}") + p = [_int(x, 0, n - 1, "perm[i]") for x in t[pos:pos + n]] + pos += n + if len(set(p)) != n: + raise Invalid(f"permutation {idx + 1} contains duplicates") + if count_inc(p) != k: + raise Invalid(f"permutation {idx + 1} does not have exactly {k} increasing subsequences") + mx = max(mx, n) + if pos != len(t): + raise Invalid("extra tokens after the last permutation") + return float(mx), {"max_n": mx} diff --git a/graders/fcs_inverse_paths/check.py b/graders/fcs_inverse_paths/check.py new file mode 100644 index 0000000000000000000000000000000000000000..2ae750dee798c738c91a3ef924a755fec1d1f142 --- /dev/null +++ b/graders/fcs_inverse_paths/check.py @@ -0,0 +1,50 @@ +"""FrontierCS algorithmic/58 (Inverse Counting Path): an n x n 0/1 grid (n <= 300) whose number of monotone +(right/down) paths from (1,1) to (n,n) through 1-cells is exactly x. Minimize n. + +Port of upstream chk.cc validation (n in [1, 300], n*n entries each 0 or 1, nothing after), with one fix: +upstream compares the path count with x only modulo 998244353 and modulo 1e9+7 (a hash; a grid with a +different, colliding count would pass). We compare the exact big-integer count. +""" +import re + +from run import Invalid + +_INT = re.compile(r"(0|-?[1-9][0-9]*)\Z") +MAX_CHARS = 400_000 + + +def check(inst, ans): + x = inst["x"] + s = ans.get("output") + if not isinstance(s, str): + raise Invalid("output must be a string") + if len(s) > MAX_CHARS or not s.isascii(): + raise Invalid("output too long or not ASCII") + t = s.split() + if not t or not _INT.match(t[0]): + raise Invalid("first token must be the integer n") + n = int(t[0]) + if n < 1 or n > 300: + raise Invalid(f"n = {n} out of range [1, 300]") + if len(t) != 1 + n * n: + raise Invalid(f"expected exactly {n * n} grid entries after n, got {len(t) - 1}") + cells = t[1:] + if any(v not in ("0", "1") for v in cells): + bad = next(v for v in cells if v not in ("0", "1")) + raise Invalid(f"grid entries must be 0 or 1 (got {bad[:20]!r})") + g = [[cells[i * n + j] == "1" for j in range(n)] for i in range(n)] + prev = [0] * n + for i in range(n): + cur = [0] * n + row = g[i] + for j in range(n): + if row[j]: + if i == 0 and j == 0: + cur[j] = 1 + else: + cur[j] = prev[j] + (cur[j - 1] if j else 0) + prev = cur + cnt = prev[n - 1] + if cnt != x: + raise Invalid(f"the grid has {cnt if cnt < 10 ** 30 else 'more than 1e30'} paths, not {x}") + return float(n), {"n": n} diff --git a/graders/fcs_lis_lds_split/check.py b/graders/fcs_lis_lds_split/check.py new file mode 100644 index 0000000000000000000000000000000000000000..9d13e95c62aaa8a926347a9cb5780256bc97ff86 --- /dev/null +++ b/graders/fcs_lis_lds_split/check.py @@ -0,0 +1,44 @@ +"""FrontierCS algorithmic/227: split a permutation p of 1..n into four disjoint subsequences a, b, c, d (every +element used exactly once, each list in the order the values appear in p). Objective (maximize) += LIS(a) + LDS(b) + LIS(c) + LDS(d) (strict, exact integers). Answer {"a": [...], "b": [...], "c": [...], "d": [...]}, +lists of VALUES of p. chk.cc does not range-check the values (out-of-range values are undefined behaviour); we do.""" +from bisect import bisect_left + +from run import Invalid, int_list + + +def _lis(v): + dp = [] + for x in v: + i = bisect_left(dp, x) + if i == len(dp): + dp.append(x) + else: + dp[i] = x + return len(dp) + + +def check(inst, ans): + t = inst["input"].split() + n = int(t[0]) + p = list(map(int, t[1:1 + n])) + loc = [0] * (n + 1) + for i, x in enumerate(p): + loc[x] = i + seen = [False] * (n + 1) + lists = {} + for k in "abcd": + v = int_list(ans.get(k), None, 1, n, k) + for i, x in enumerate(v): + if seen[x]: + raise Invalid(f"element {x} appears twice") + seen[x] = True + if i and loc[v[i - 1]] > loc[x]: + raise Invalid(f"list {k} is not in the order of p at element {x}") + lists[k] = v + if sum(len(v) for v in lists.values()) != n: + raise Invalid("a, b, c, d must partition all n elements") + la, lc = _lis(lists["a"]), _lis(lists["c"]) + lb, ld = _lis(lists["b"][::-1]), _lis(lists["d"][::-1]) + tot = la + lb + lc + ld + return float(tot), {"lis_a": la, "lds_b": lb, "lis_c": lc, "lds_d": ld} diff --git a/graders/fcs_max3sat/check.py b/graders/fcs_max3sat/check.py new file mode 100644 index 0000000000000000000000000000000000000000..b9d42efb6101522eb279f14d5e7592cc177dbff5 --- /dev/null +++ b/graders/fcs_max3sat/check.py @@ -0,0 +1,25 @@ +"""FrontierCS algorithmic/176 Max-3-SAT on a fixed CNF. Answer: {"assignment": [x_1..x_n]}, x_i in {0,1} (1 = TRUE). +Objective (maximize) = number of satisfied clauses (exact integer). Port of chk.cc; the official checker +ignores trailing tokens, we require exactly n values.""" +from run import Invalid, int_list + +K = 3 + + +def _parse(text): + t = text.split() + n, m = int(t[0]), int(t[1]) + v = list(map(int, t[2:2 + K * m])) + return n, m, [v[K * i:K * i + K] for i in range(m)] + + +def check(inst, ans): + n, m, clauses = _parse(inst["input"]) + x = int_list(ans.get("assignment"), n, 0, 1, "assignment") + sat = 0 + for c in clauses: + for lit in c: + if (x[lit - 1] == 1) if lit > 0 else (x[-lit - 1] == 0): + sat += 1 + break + return float(sat), {"satisfied": sat, "m": m} diff --git a/graders/fcs_maxcut/check.py b/graders/fcs_maxcut/check.py new file mode 100644 index 0000000000000000000000000000000000000000..7f78c06af3e192041f0fc7927119ae9b2b02ced3 --- /dev/null +++ b/graders/fcs_maxcut/check.py @@ -0,0 +1,18 @@ +"""FrontierCS algorithmic/192 Max-Cut on a fixed graph. Answer: {"side": [s_1..s_n]}, s_i in {0,1}. +Objective (maximize) = number of edges whose endpoints get different sides (exact integer). +Port of chk.cc; the official checker reads n integers and ignores trailing tokens, we require exactly n.""" +from run import Invalid, int_list + + +def _parse(text): + t = text.split() + n, m = int(t[0]), int(t[1]) + e = [(int(t[2 + 2 * i]), int(t[3 + 2 * i])) for i in range(m)] + return n, m, e + + +def check(inst, ans): + n, m, edges = _parse(inst["input"]) + s = int_list(ans.get("side"), n, 0, 1, "side") + cut = sum(1 for u, v in edges if s[u - 1] != s[v - 1]) + return float(cut), {"cut": cut, "m": m} diff --git a/graders/fcs_mult_partial_sums/check.py b/graders/fcs_mult_partial_sums/check.py new file mode 100644 index 0000000000000000000000000000000000000000..5926f213e9655d37cf50dad25baf8315b5eda6e9 --- /dev/null +++ b/graders/fcs_mult_partial_sums/check.py @@ -0,0 +1,51 @@ +"""FrontierCS algorithmic/83: completely multiplicative f: {1..n} -> {+1,-1} minimizing max_k |sum_{i<=k} f(i)|. + +Port of upstream check.cpp: exactly n integers, each of absolute value 1, nothing after them; +f(xy) = f(x) f(y) whenever xy <= n. Upstream enumerates all pairs (x, y); we check the equivalent +f(1) = 1 and f(i) = f(p) f(i / p) for p = smallest prime factor of i (induction gives full complete +multiplicativity, and the converse is immediate). Objective M = max prefix |sum| (minimize), exact integers. +""" +import re + +import numpy as np + +from run import Invalid + +_INT = re.compile(r"(0|-?[1-9][0-9]*)\Z") +MAX_CHARS = 4_000_000 + + +def check(inst, ans): + n = inst["n"] + s = ans.get("output") + if not isinstance(s, str): + raise Invalid("output must be a string") + if len(s) > MAX_CHARS: + raise Invalid("output too long") + if not s.isascii(): + raise Invalid("output must be ASCII") + t = s.split() + if len(t) != n: + raise Invalid(f"expected exactly {n} integers, got {len(t)}") + bad = [x for x in set(t) if x not in ("1", "-1")] + if bad: + b = bad[0] + raise Invalid(f"|f(i)| must be 1 (token {b[:20]!r})" if _INT.match(b) else f"expected an integer, got {b[:20]!r}") + f = np.empty(n + 1, dtype=np.int64) + f[0] = 0 + f[1:] = np.where(np.array(t) == "1", 1, -1) + if f[1] != 1: + raise Invalid("f(1) must be 1 (f(1) = f(1*1) = f(1)^2)") + spf = np.arange(n + 1, dtype=np.int64) + for p in range(2, int(n ** 0.5) + 1): + if spf[p] == p: + seg = spf[p * p::p] + np.copyto(seg, p, where=(seg == np.arange(p * p, n + 1, p))) + i = np.arange(2, n + 1) + p = spf[2:] + ok = f[2:] == f[p] * f[i // p] + if not ok.all(): + j = int(i[np.argmin(ok)]) + raise Invalid(f"not completely multiplicative: f({j}) != f({int(spf[j])}) * f({j // int(spf[j])})") + M = int(np.abs(np.cumsum(f[1:])).max()) + return float(M), {"M": M} diff --git a/graders/fcs_no_rectangle/check.py b/graders/fcs_no_rectangle/check.py new file mode 100644 index 0000000000000000000000000000000000000000..d88f254729adbcb759c1ba72ff03416032ef1111 --- /dev/null +++ b/graders/fcs_no_rectangle/check.py @@ -0,0 +1,61 @@ +"""FrontierCS algorithmic/27: rectangle-free point set in an n x m grid (Zarankiewicz z(n,m;2,2)). + +Port of the upstream testlib checker chk.cc (validation part): k in [0, n*m], k points (r, c) with +1 <= r <= n, 1 <= c <= m, no duplicates, no two rows sharing two columns. Objective = k (maximize). +Output is parsed like testlib: whitespace-separated tokens, integers in canonical form. +Unlike upstream (which comments out readEof) trailing tokens are rejected. +""" +import re + +import numpy as np + +from run import Invalid + +_INT = re.compile(r"(0|-?[1-9][0-9]*)\Z") +MAX_CHARS = 3_000_000 + + +def _tokens(ans): + s = ans.get("output") + if not isinstance(s, str): + raise Invalid("output must be a string") + if len(s) > MAX_CHARS: + raise Invalid("output too long") + if any(not (32 <= ord(ch) < 127 or ch in "\t\r\n") for ch in s): + raise Invalid("output must be printable ASCII") + return s.split() + + +def _int(tok, lo, hi, name): + if not _INT.match(tok): + raise Invalid(f"{name}: expected an integer, got {tok[:20]!r}") + v = int(tok) + if v < lo or v > hi: + raise Invalid(f"{name} = {v} out of range [{lo}, {hi}]") + return v + + +def check(inst, ans): + n, m = inst["n"], inst["m"] + t = _tokens(ans) + if not t: + raise Invalid("empty output") + k = _int(t[0], 1, n * m, "k") # upstream allows k = 0 (0 points); we require k >= 1 + if len(t) != 1 + 2 * k: + raise Invalid(f"expected exactly {2 * k} integers after k, got {len(t) - 1}") + M = np.zeros((n, m), dtype=np.int8) + for i in range(k): + r = _int(t[1 + 2 * i], 1, n, "r") + c = _int(t[2 + 2 * i], 1, m, "c") + if M[r - 1, c - 1]: + raise Invalid(f"duplicate point ({r}, {c})") + M[r - 1, c - 1] = 1 + if k and n > 1 and m > 1: + A = M if n <= m else M.T + A = A.astype(np.float64) + G = A @ A.T # exact: entries <= max(n, m) <= 1e5 + np.fill_diagonal(G, 0) + if G.max() >= 2: + i, j = np.unravel_index(int(np.argmax(G)), G.shape) + raise Invalid(f"rectangle: two {'rows' if n <= m else 'columns'} ({i + 1}, {j + 1}) share >= 2 points") + return float(k), {"k": k} diff --git a/graders/fcs_prime_retune/check.py b/graders/fcs_prime_retune/check.py new file mode 100644 index 0000000000000000000000000000000000000000..fdfd7374c3b2b77f4578415551f223984cc0d204 --- /dev/null +++ b/graders/fcs_prime_retune/check.py @@ -0,0 +1,92 @@ +"""FrontierCS algorithmic/314 (Prime Resonance Retuning). Answer {"retuners": [[v, d], ...]}: at most k distinct +nodes v in 1..n with shifts 1 <= d < m. A retuner adds d (mod m) to every node of the subtree of v. Objective +(minimize) F = sum_j w_j * (|P| - C_j) + sum of c_v over retuners, where P = primes < m and C_j = number of primes +of P occurring among the final residues in the subtree of s_j (exact integers; port of chk.cc).""" +import numpy as np + +from run import Invalid, int_list + + +def _parse(text): + t = text.split() + n, m, T, k = map(int, t[:4]) + p = 4 + a = [int(x) % m for x in t[p:p + n]]; p += n + c = list(map(int, t[p:p + n])); p += n + adj = [[] for _ in range(n + 1)] + for i in range(n - 1): + u, v = int(t[p + 2 * i]), int(t[p + 2 * i + 1]) + adj[u].append(v) + adj[v].append(u) + p += 2 * (n - 1) + obs = [(int(t[p + 2 * j]), int(t[p + 2 * j + 1])) for j in range(T)] + return n, m, k, a, c, adj, obs + + +def check(inst, ans): + n, m, k, a, c, adj, obs = _parse(inst["input"]) + R = ans.get("retuners") + if not isinstance(R, list) or len(R) > k: + raise Invalid(f"retuners must be a list of at most k = {k} pairs") + x = [0] * (n + 1) + cost = 0 + for r in R: + v, d = int_list(r, 2, None, None, "retuner") + if not (1 <= v <= n) or not (1 <= d <= m - 1): + raise Invalid(f"retuner {r} out of range (1 <= v <= {n}, 1 <= d <= {m - 1})") + if x[v]: + raise Invalid(f"node {v} used twice") + x[v] = d + cost += c[v - 1] + # root at 1: BFS order / parents, then preorder positions for subtrees + par = [0] * (n + 1) + order = [1] + seen = [False] * (n + 1) + seen[1] = True + for u in order: + for w in adj[u]: + if not seen[w]: + seen[w] = True + par[w] = u + order.append(w) + cs = [0] * (n + 1) + for u in order: + cs[u] = ((cs[par[u]] if par[u] else 0) + x[u]) % m + children = [[] for _ in range(n + 1)] + for u in order[1:]: + children[par[u]].append(u) + tin, tout, euler = [0] * (n + 1), [0] * (n + 1), [] + st = [(1, False)] + while st: + u, leave = st.pop() + if leave: + tout[u] = len(euler) - 1 + else: + tin[u] = len(euler) + euler.append(u) + st.append((u, True)) + for w in reversed(children[u]): + st.append((w, False)) + sieve = [True] * max(m, 2) + primes = [] + for q in range(2, m): + if sieve[q]: + primes.append(q) + for z in range(2 * q, m, q): + sieve[z] = False + pid = {q: i for i, q in enumerate(primes)} + P = len(primes) + if P == 0: + return float(cost), {"F": cost} + M = np.zeros((n + 1, P), dtype=np.int32) # prefix counts over Euler positions + for pos, u in enumerate(euler): + M[pos + 1] = M[pos] + i = pid.get((a[u - 1] + cs[u]) % m) + if i is not None: + M[pos + 1, i] += 1 + pen = 0 + for s, w in obs: + cov = int(np.count_nonzero(M[tout[s] + 1] - M[tin[s]])) + pen += w * (P - cov) + F = pen + cost + return float(F), {"F": F, "penalty": pen, "retuner_cost": cost} diff --git a/graders/fcs_shortcut3hop/check.py b/graders/fcs_shortcut3hop/check.py new file mode 100644 index 0000000000000000000000000000000000000000..3851c181f25c1c44b28685612dce1bc3797000ff --- /dev/null +++ b/graders/fcs_shortcut3hop/check.py @@ -0,0 +1,33 @@ +"""FrontierCS algorithmic/239: shortcut edges so that a path 0->1->...->n has hop-diameter <= 3. +Answer {"triples": [[a, b, c], ...]}: in order, each triple adds edge a->c and requires edges a->b and b->c to +exist at that moment (chain edges i->i+1 exist initially). Afterwards every pair v < u must be joined by a +directed path of at most 3 edges. Objective (minimize) = number of triples (as in chk.cc, a triple whose edge +a->c already exists is legal and still counts). Reachability is checked exactly with 0/1 matrix products.""" +import numpy as np + +from run import Invalid, int_list + +MAX_TRIPLES = 300000 + + +def check(inst, ans): + n = int(inst["input"].split()[0]) + tr = ans.get("triples") + if not isinstance(tr, list) or len(tr) > MAX_TRIPLES: + raise Invalid(f"triples must be a list of at most {MAX_TRIPLES} triples") + N = n + 1 + G = np.zeros((N, N), dtype=bool) + idx = np.arange(n) + G[idx, idx + 1] = True + for t in tr: + a, b, c = int_list(t, 3, 0, n, "triple") + if not (G[a, b] and G[b, c]): + raise Invalid(f"cannot add {a}->{c}: edges {a}->{b} and {b}->{c} must both exist") + G[a, c] = True + R1 = (G | np.eye(N, dtype=bool)).astype(np.float32) + R2 = (R1 @ R1) > 0.5 + R3 = (R2.astype(np.float32) @ R1) > 0.5 + if not np.triu(R3, 1).sum() == N * (N - 1) // 2: + bad = np.argwhere(np.triu(~R3, 1))[0] + raise Invalid(f"vertex {bad[1]} is not reachable from {bad[0]} within 3 edges") + return float(len(tr)), {"m": len(tr)} diff --git a/graders/fcs_swap_shift/check.py b/graders/fcs_swap_shift/check.py new file mode 100644 index 0000000000000000000000000000000000000000..2946c4dda9b3c08a115a82647fecba22d17901fe --- /dev/null +++ b/graders/fcs_swap_shift/check.py @@ -0,0 +1,24 @@ +"""FrontierCS algorithmic/247: transform A into B with operations (i, j), i < j: A_i <- A_j - 1, A_j <- A_i + 1. +Answer {"ops": [[i, j], ...]} (1-based, at most 100000 ops); must end exactly at B. Objective (minimize) = number +of operations. Port of chk.cc's simulation (only "Yes" instances are used, so the Yes/No token is implicit).""" +from run import Invalid, int_list + +MAX_OPS = 100000 + + +def check(inst, ans): + t = inst["input"].split() + n = int(t[0]) + A = list(map(int, t[1:1 + n])) + B = list(map(int, t[1 + n:1 + 2 * n])) + ops = ans.get("ops") + if not isinstance(ops, list) or len(ops) > MAX_OPS: + raise Invalid(f"ops must be a list of at most {MAX_OPS} pairs") + for op in ops: + i, j = int_list(op, 2, 1, n, "op") + if i >= j: + raise Invalid(f"operation ({i}, {j}) needs i < j") + A[i - 1], A[j - 1] = A[j - 1] - 1, A[i - 1] + 1 + if A != B: + raise Invalid("final sequence does not equal B") + return float(len(ops)), {"m": len(ops)} diff --git a/graders/fcs_xor_sidon/check.py b/graders/fcs_xor_sidon/check.py new file mode 100644 index 0000000000000000000000000000000000000000..6ba950f1d6d1e2949a511104e67d76ebd3048fef --- /dev/null +++ b/graders/fcs_xor_sidon/check.py @@ -0,0 +1,52 @@ +"""FrontierCS algorithmic/111: S subset of {1..n} with all pairwise XORs a^b (a < b) distinct (a Sidon set +in the group (Z/2)^K restricted to 1..n). Maximize |S|. + +Port of upstream chk.cc: m, then m distinct integers in [1, n]; reject if m(m-1)/2 > 2^K (K = bit width +with 2^K > n), then all pairwise XORs must be distinct. Upstream allows m = 0 (0 points); we require m >= 1. +Upstream comments say extra tokens are ignored, but testlib rejects them at exit; so do we. +""" +import re + +import numpy as np + +from run import Invalid + +_INT = re.compile(r"(0|-?[1-9][0-9]*)\Z") +MAX_CHARS = 200_000 + + +def _int(tok, lo, hi, name): + if not _INT.match(tok): + raise Invalid(f"{name}: expected an integer, got {tok[:20]!r}") + v = int(tok) + if v < lo or v > hi: + raise Invalid(f"{name} = {v} out of range [{lo}, {hi}]") + return v + + +def check(inst, ans): + n = inst["n"] + s = ans.get("output") + if not isinstance(s, str): + raise Invalid("output must be a string") + if len(s) > MAX_CHARS or not s.isascii(): + raise Invalid("output too long or not ASCII") + t = s.split() + if not t: + raise Invalid("empty output") + m = _int(t[0], 1, n, "m") + if len(t) != 1 + m: + raise Invalid(f"expected exactly {m} numbers after m, got {len(t) - 1}") + a = [_int(x, 1, n, "element") for x in t[1:]] + if len(set(a)) != m: + raise Invalid("duplicate numbers") + K = max(1, n.bit_length()) + if m * (m - 1) // 2 > (1 << K): + raise Invalid(f"impossible: {m} elements give more pairs than the {1 << K} available XOR values") + if m > 1: + A = np.array(a, dtype=np.int64) + x = np.concatenate([A[i] ^ A[i + 1:] for i in range(m - 1)]) + x.sort() + if (x[1:] == x[:-1]).any(): + raise Invalid("two different pairs have the same XOR") + return float(m), {"m": m} diff --git a/graders/fsh_abc_quality/check.py b/graders/fsh_abc_quality/check.py new file mode 100644 index 0000000000000000000000000000000000000000..88a8bf826d868eaf0f5f87032ed53e1b27a93e8d --- /dev/null +++ b/graders/fsh_abc_quality/check.py @@ -0,0 +1,57 @@ +"""abc-triple quality (FrontierShift fs-0375). + +Answer: factorizations of a, b, c as lists of [p, e] pairs. The checker multiplies them out (exact ints), +requires a, b >= 1, a + b = c, gcd(a, b) = 1, each claimed prime p to pass sympy.isprime (deterministic below +2^64, BPSW above) and p distinct within each list. Score q = log(c) / log(R) with R the product of the distinct +claimed primes over a, b, c. Since every true prime of abc divides some claimed factor, R >= rad(abc) holds even if +a claimed "prime" were composite, so the score never overstates the true quality. +""" +import math + +import sympy + +from run import Invalid, int_list + +MAX_DIGITS = 400 +MAX_FACTORS = 200 +MAX_BITS = 1330 # > log2(10^400) + + +def _fac(v, name): + if not isinstance(v, list) or len(v) > MAX_FACTORS: + raise Invalid(f"{name} must be a list of at most {MAX_FACTORS} [prime, exponent] pairs") + val, primes = 1, [] + for pe in v: + int_list(pe, 2, None, None, f"{name} factor") + p, e = pe + if p < 2 or e < 1 or e > 10000: + raise Invalid(f"{name}: need prime >= 2 and exponent in 1..10000") + if (p.bit_length() - 1) * e > MAX_BITS: + raise Invalid(f"{name} exceeds {MAX_DIGITS} digits") + if p in primes: + raise Invalid(f"{name}: repeated prime {p}") + primes.append(p) + val *= p ** e + if val >= 10 ** MAX_DIGITS: + raise Invalid(f"{name} exceeds {MAX_DIGITS} digits") + for p in primes: + if not sympy.isprime(p): + raise Invalid(f"{name}: {p} is not prime") + return val, primes + + +def check(inst, ans): + a, pa = _fac(ans.get("a"), "a") + b, pb = _fac(ans.get("b"), "b") + c, pc = _fac(ans.get("c"), "c") + if a + b != c: + raise Invalid("a + b != c") + if math.gcd(a, b) != 1: + raise Invalid("a and b are not coprime") + R = 1 + for p in set(pa) | set(pb) | set(pc): + R *= p + if R < 2: + raise Invalid("degenerate triple") + q = math.log(c) / math.log(R) + return q, {"a": str(a), "b": str(b), "c": str(c), "rad": str(R)} diff --git a/graders/fsh_boolean_nonlinearity_9/check.py b/graders/fsh_boolean_nonlinearity_9/check.py new file mode 100644 index 0000000000000000000000000000000000000000..1665503b668c01f43eb97e7f806ec13c0207b5ec --- /dev/null +++ b/graders/fsh_boolean_nonlinearity_9/check.py @@ -0,0 +1,25 @@ +"""Nonlinearity of a 9-variable Boolean function (FrontierShift fs-0243). + +nl(f) = 2^(n-1) - max_w |W_f(w)| / 2, W_f the Walsh-Hadamard transform of (-1)^f; exact integer arithmetic +(in-place fast WHT on Python ints). Score = nl(f), maximize. +""" +from run import Invalid, int_list + + +def nonlinearity(tt, n): + w = [1 - 2 * b for b in tt] + h = 1 + while h < len(w): + for i in range(0, len(w), 2 * h): + for j in range(i, i + h): + x, y = w[j], w[j + h] + w[j], w[j + h] = x + y, x - y + h *= 2 + return (1 << (n - 1)) - max(abs(v) for v in w) // 2 + + +def check(inst, ans): + n = inst["n"] + tt = int_list(ans.get("truth_table"), 1 << n, 0, 1, "truth_table") + nl = nonlinearity(tt, n) + return nl, {"nonlinearity": nl} diff --git a/graders/fsh_cramer_gap_ratio/check.py b/graders/fsh_cramer_gap_ratio/check.py new file mode 100644 index 0000000000000000000000000000000000000000..2395b362a29dff93840a3efa740bc26e21b23fef --- /dev/null +++ b/graders/fsh_cramer_gap_ratio/check.py @@ -0,0 +1,31 @@ +"""Prime gap with large Cramer-Shanks-Granville ratio g / ln(p)^2 (FrontierShift fs-0377), restricted to +10^9 < p and p + g < 2^64 so that sympy.isprime is a deterministic (proven) primality test. + +Checks: p prime, p + g prime, every integer strictly between them composite (i.e. they are consecutive primes). +Score = g / ln(p)^2 (maximize). +""" +import math + +import sympy + +from run import Invalid, as_int + +LO = 10 ** 9 +HI = 2 ** 64 +MAX_GAP = 4000 + + +def check(inst, ans): + p = as_int(ans.get("p"), "p", LO + 1, HI - 1) + g = as_int(ans.get("g"), "g", 1, MAX_GAP) + q = p + g + if q >= HI: + raise Invalid("p + g must be below 2^64") + if not sympy.isprime(p): + raise Invalid("p is not prime") + if not sympy.isprime(q): + raise Invalid("p + g is not prime") + for x in range(p + 1, q): + if sympy.isprime(x): + raise Invalid(f"{x} is prime: p and p + g are not consecutive primes") + return g / math.log(p) ** 2, {"p": p, "g": g} diff --git a/graders/fsh_lwc_1280/check.py b/graders/fsh_lwc_1280/check.py new file mode 100644 index 0000000000000000000000000000000000000000..228594453df058e695cbd4942d703f74e9cc7857 --- /dev/null +++ b/graders/fsh_lwc_1280/check.py @@ -0,0 +1,30 @@ +"""Low-weight codeword in the n=1280, k=640 binary decoding-challenge code, seed 0 (FrontierShift fs-0364). + +Parity check H = [I_640 | M^T]: c in F_2^1280 is a codeword iff for every j in 0..639 + c_j + sum_i c_{640+i} * M[i][j] = 0 (mod 2). +Answer: the support of c (sorted, distinct indices in 0..1279, non-empty). Score = |support| (minimize). +Exact GF(2) arithmetic on Python ints. +""" +from run import Invalid, int_list + + +def check(inst, ans): + n, k = inst["n"], inst["k"] + sup = ans.get("support") + if not isinstance(sup, list) or not sup: + raise Invalid("support must be a non-empty list of indices") + int_list(sup, None, 0, n - 1, "support") + if len(sup) > n: + raise Invalid("support too long") + if any(sup[i] >= sup[i + 1] for i in range(len(sup) - 1)): + raise Invalid("support must be strictly increasing (sorted, no duplicates)") + rows = inst["M"] + syn = 0 + for i in sup: + if i < n - k: + syn ^= 1 << i + else: + syn ^= int(rows[i - (n - k)][::-1], 2) + if syn != 0: + raise Invalid(f"not a codeword: syndrome weight {bin(syn).count('1')}") + return len(sup), {"weight": len(sup)} diff --git a/graders/fsh_matmul_rank/check.py b/graders/fsh_matmul_rank/check.py new file mode 100644 index 0000000000000000000000000000000000000000..f308bf3d9621fb1aaee9b5fa5eaca9510cd9ace0 --- /dev/null +++ b/graders/fsh_matmul_rank/check.py @@ -0,0 +1,79 @@ +"""Exact rank-r decompositions of the n x n matrix multiplication tensor over Q (FrontierShift fs-0034 / fs-0035). + +Answer: U, V, W, each a list of r rows of n^2 exact rational coefficients (JSON integers or strings "p" / "p/q"). +Row t gives the bilinear product m_t = (sum_ij U[t][i*n+j] a_ij) * (sum_jk V[t][j*n+k] b_jk) and +c_ik = sum_t W[t][i*n+k] m_t must equal (AB)_ik identically, i.e. for all index pairs + sum_t U[t][(i,j)] V[t][(j',k)] W[t][(i',k')] = [i=i'][j=j'][k=k']. +The identity is checked entry by entry in exact rational arithmetic (fractions.Fraction); no floats are accepted, +so a floating-point "almost decomposition" cannot pass. Score = r (minimize). Because no commutativity of the +entries is used, any valid answer is a recursively applicable (non-commutative) bilinear algorithm. +""" +import re +from fractions import Fraction + +from run import Invalid + +_TOK = re.compile(r"-?(0|[1-9][0-9]*)(/[1-9][0-9]*)?") +MAX_TOKEN = 40 + + +def _coef(x): + if isinstance(x, bool): + raise Invalid("booleans are not coefficients") + if isinstance(x, int): + if abs(x) > 10 ** MAX_TOKEN: + raise Invalid("coefficient too large") + return Fraction(x) + if isinstance(x, str): + if len(x) > MAX_TOKEN or not _TOK.fullmatch(x): + raise Invalid(f"bad rational coefficient {x[:50]!r}: use an integer or 'p/q'") + return Fraction(x) + raise Invalid("coefficients must be JSON integers or strings 'p/q' (no floats)") + + +def _factor(rows, r, n, name): + if not isinstance(rows, list) or len(rows) != r: + raise Invalid(f"{name} must be a list of r = {r} rows") + out = [] + for row in rows: + if not isinstance(row, list) or len(row) != n * n: + raise Invalid(f"each row of {name} must have {n * n} coefficients") + out.append([_coef(x) for x in row]) + return out + + +def check(inst, ans): + n = inst["n"] + U = ans.get("U") + if not isinstance(U, list): + raise Invalid("U must be a list") + r = len(U) + if r < 1 or r > inst["max_rank"]: + raise Invalid(f"rank must be between 1 and {inst['max_rank']}") + U = _factor(U, r, n, "U") + V = _factor(ans.get("V"), r, n, "V") + W = _factor(ans.get("W"), r, n, "W") + T = {} + for t in range(r): + us = [(i, x) for i, x in enumerate(U[t]) if x] + vs = [(i, x) for i, x in enumerate(V[t]) if x] + ws = [(i, x) for i, x in enumerate(W[t]) if x] + for a, x in us: + for b, y in vs: + xy = x * y + for c, z in ws: + k = (a, b, c) + T[k] = T.get(k, 0) + xy * z + target = set() + for i in range(n): + for j in range(n): + for k in range(n): + target.add((i * n + j, j * n + k, i * n + k)) + for key, val in T.items(): + want = 1 if key in target else 0 + if val != want: + raise Invalid(f"tensor entry {key} is {val}, expected {want}") + for key in target: + if key not in T: + raise Invalid(f"tensor entry {key} is 0, expected 1") + return r, {"rank": r} diff --git a/graders/fsh_maxdet_23/check.py b/graders/fsh_maxdet_23/check.py new file mode 100644 index 0000000000000000000000000000000000000000..09b19964b33f1bad2d950fea586a13cd7bc1b108 --- /dev/null +++ b/graders/fsh_maxdet_23/check.py @@ -0,0 +1,48 @@ +"""Hadamard maximal determinant problem at order 23 (FrontierShift fs-0164). + +Score = log10 |det A| for A in {-1,+1}^{23x23}, from the exact integer determinant (fraction-free Bareiss, +no floating point in the determinant). A singular matrix is invalid. Every such determinant is divisible by 2^22. +""" +import math + +from run import Invalid, int_list + + +def _det_bareiss(m): + a = [row[:] for row in m] + n = len(a) + sign, prev = 1, 1 + for k in range(n - 1): + if a[k][k] == 0: + for r in range(k + 1, n): + if a[r][k] != 0: + a[k], a[r] = a[r], a[k] + sign = -sign + break + else: + return 0 + akk, rowk = a[k][k], a[k] + for i in range(k + 1, n): + aik, rowi = a[i][k], a[i] + a[i] = rowi[:k + 1] + [(rowi[j] * akk - aik * rowk[j]) // prev for j in range(k + 1, n)] + prev = akk + return sign * a[n - 1][n - 1] + + +def check(inst, ans): + n = inst["n"] + m = ans.get("matrix") + if not isinstance(m, list) or len(m) != n: + raise Invalid(f"matrix must be a list of {n} rows") + rows = [] + for r in m: + int_list(r, n, -1, 1, "matrix row") + if any(x == 0 for x in r): + raise Invalid("entries must be exactly 1 or -1") + rows.append(list(r)) + d = abs(_det_bareiss(rows)) + if d == 0: + raise Invalid("matrix is singular") + e = len(str(d)) - 1 + q, rem = divmod(d, 1 << (n - 1)) + return e + math.log10(d / 10 ** e), {"det": str(d), "det_over_2^22": str(q) if rem == 0 else None} diff --git a/graders/fsh_rational_diophantine_7/check.py b/graders/fsh_rational_diophantine_7/check.py new file mode 100644 index 0000000000000000000000000000000000000000..961230473b20351e8f2e5b98445277b4024a6968 --- /dev/null +++ b/graders/fsh_rational_diophantine_7/check.py @@ -0,0 +1,48 @@ +"""Almost rational Diophantine septuples (FrontierShift fs-0395). + +Answer: 7 pairwise distinct nonzero rationals (JSON integers or strings "p" / "p/q", reduced by the checker). +Score = number of pairs i < j for which a_i * a_j + 1 is the square of a rational (exact: reduced numerator and +denominator are both perfect squares, via math.isqrt). 21 = a rational Diophantine septuple (none known). +""" +import re +from fractions import Fraction +from math import isqrt + +from run import Invalid + +_TOK = re.compile(r"-?(0|[1-9][0-9]*)(/[1-9][0-9]*)?") +MAX_TOKEN = 2000 + + +def _rat(x): + if isinstance(x, bool): + raise Invalid("booleans are not rationals") + if isinstance(x, int): + if abs(x).bit_length() > 4 * MAX_TOKEN: + raise Invalid("number too large") + return Fraction(x) + if isinstance(x, str) and len(x) <= MAX_TOKEN and _TOK.fullmatch(x): + return Fraction(x) + raise Invalid("each element must be a JSON integer or a string 'p/q' (at most 2000 characters)") + + +def _is_rational_square(x): + if x < 0: + return False + n, d = x.numerator, x.denominator + return isqrt(n) ** 2 == n and isqrt(d) ** 2 == d + + +def check(inst, ans): + m = inst["m"] + a = ans.get("a") + if not isinstance(a, list) or len(a) != m: + raise Invalid(f"a must be a list of exactly {m} rationals") + A = [_rat(x) for x in a] + if any(x == 0 for x in A): + raise Invalid("elements must be nonzero") + if len(set(A)) != m: + raise Invalid("elements must be pairwise distinct (after reduction to lowest terms)") + good = [(i, j) for i in range(m) for j in range(i + 1, m) if _is_rational_square(A[i] * A[j] + 1)] + return len(good), {"square_pairs": len(good), "missing": [[i, j] for i in range(m) for j in range(i + 1, m) + if (i, j) not in set(good)]} diff --git a/graders/fsh_tetrahedra_packing/check.py b/graders/fsh_tetrahedra_packing/check.py new file mode 100644 index 0000000000000000000000000000000000000000..933e7cdfb93a1ae1a2e952702a428f61724f8a8f --- /dev/null +++ b/graders/fsh_tetrahedra_packing/check.py @@ -0,0 +1,151 @@ +"""Periodic packings of congruent regular tetrahedra (FrontierShift fs-0247). + +Answer: a lattice basis (3 rational row vectors) and k tetrahedra (4 rational vertices each) in one cell. +Every tetrahedron must be regular with all six squared edge lengths exactly 2 (edge sqrt(2), volume 1/3). +The packing is { T_i + t : i, t in L }. Interiors must be pairwise disjoint; this is decided exactly with the +separating-axis theorem (4 + 4 face normals and the 6 x 6 edge cross products; touching is allowed), after scaling +all coordinates to integers by a common denominator. Pairs whose centroids are farther apart than twice the +circumradius (sqrt(3)) cannot overlap and are skipped (float pruning with a safety margin only). Lattice +translates are enumerated around each pair's centroid offset from B^{-1} (float, with +-1 margin); a basis so +skewed that this enumeration exceeds the cap is rejected (reduce the basis). +Score = density = k * (1/3) / |det L| (exact Fraction, reported as float), maximize. +""" +import itertools +import math +import re +from fractions import Fraction + +import numpy as np + +from run import Invalid + +_TOK = re.compile(r"-?(0|[1-9][0-9]*)(/[1-9][0-9]*)?") +MAX_TOKEN = 60 +MAX_K = 16 +MAX_TRANSLATES = 400000 +MAX_DEN = 10 ** 400 +RAD2 = math.sqrt(3.0) # twice the circumradius sqrt(3)/2 of the edge-sqrt(2) tetrahedron +FACES = [(0, 1, 2, 3), (0, 1, 3, 2), (0, 2, 3, 1), (1, 2, 3, 0)] +EDGES = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] + + +def _rat(x): + if isinstance(x, bool): + raise Invalid("booleans are not coordinates") + if isinstance(x, int): + if abs(x) > 10 ** 30: + raise Invalid("coordinate too large") + return Fraction(x) + if isinstance(x, str) and len(x) <= MAX_TOKEN and _TOK.fullmatch(x): + return Fraction(x) + raise Invalid("coordinates must be JSON integers or strings 'p/q' (at most 60 characters; no floats)") + + +def _vec(v, name): + if not isinstance(v, list) or len(v) != 3: + raise Invalid(f"{name} must be a list of 3 coordinates") + return [_rat(x) for x in v] + + +def _sub(a, b): + return (a[0] - b[0], a[1] - b[1], a[2] - b[2]) + + +def _cross(a, b): + return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]) + + +def _dot(a, b): + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + + +def _axes(P): + out = [] + for a, b, c, _ in FACES: + out.append(_cross(_sub(P[b], P[a]), _sub(P[c], P[a]))) + return out + + +def _separated(P, Q, axP, axQ, edP, edQ): + """True iff int(P) and int(Q) are disjoint (P, Q: 4 integer vertices each).""" + for ax in itertools.chain(axP, axQ, (_cross(e, f) for e in edP for f in edQ)): + if ax == (0, 0, 0): + continue + p = [_dot(ax, v) for v in P] + q = [_dot(ax, v) for v in Q] + if max(p) <= min(q) or max(q) <= min(p): + return True + return False + + +def check(inst, ans): + lat = ans.get("lattice") + tets = ans.get("tetrahedra") + if not isinstance(lat, list) or len(lat) != 3: + raise Invalid("lattice must be a list of 3 basis vectors") + if not isinstance(tets, list) or not 1 <= len(tets) <= MAX_K: + raise Invalid(f"tetrahedra must be a list of 1..{MAX_K} tetrahedra") + B = [_vec(v, "lattice vector") for v in lat] + T = [] + for t in tets: + if not isinstance(t, list) or len(t) != 4: + raise Invalid("each tetrahedron must be a list of 4 vertices") + T.append([_vec(v, "vertex") for v in t]) + for t in T: + for a, b in EDGES: + d = _sub(t[a], t[b]) + if _dot(d, d) != 2: + raise Invalid("every tetrahedron must be regular with squared edge length exactly 2") + den = 1 + for x in itertools.chain((c for v in B for c in v), (c for t in T for v in t for c in v)): + den = den * x.denominator // math.gcd(den, x.denominator) + if den > MAX_DEN: + raise Invalid("common denominator of all coordinates exceeds 10^400; use simpler rationals") + Bi = [tuple(int(c * den) for c in v) for v in B] + Ti = [[tuple(int(c * den) for c in v) for v in t] for t in T] + det = (Bi[0][0] * (Bi[1][1] * Bi[2][2] - Bi[1][2] * Bi[2][1]) + - Bi[0][1] * (Bi[1][0] * Bi[2][2] - Bi[1][2] * Bi[2][0]) + + Bi[0][2] * (Bi[1][0] * Bi[2][1] - Bi[1][1] * Bi[2][0])) + if det == 0: + raise Invalid("lattice basis is singular") + vol = Fraction(abs(det), den ** 3) + k = len(T) + dens = Fraction(k, 3) / vol + if dens > 1: + raise Invalid("density > 1: the tetrahedra must overlap") + Bf = np.array([[float(c) for c in v] for v in B]) + try: + Binv = np.linalg.inv(Bf) + except np.linalg.LinAlgError: + raise Invalid("lattice basis numerically singular") + if not np.all(np.isfinite(Binv)): + raise Invalid("lattice basis numerically singular") + colnorm = np.linalg.norm(Binv, axis=0) # n = y @ Binv -> |n_k - n0_k| <= |y| * ||Binv[:, k]|| + cen = [np.array([float(sum(v[c] for v in t)) / 4 for c in range(3)]) for t in T] + ax = [_axes(P) for P in Ti] + ed = [[_sub(P[b], P[a]) for a, b in EDGES] for P in Ti] + reach = RAD2 * (1 + 1e-9) + 1e-9 + budget = MAX_TRANSLATES + pairs = 0 + for i in range(k): + for j in range(i, k): + d = cen[j] - cen[i] + n0 = -d @ Binv + rng = [range(math.floor(n0[c] - reach * colnorm[c]) - 1, math.ceil(n0[c] + reach * colnorm[c]) + 2) + for c in range(3)] + cnt = len(rng[0]) * len(rng[1]) * len(rng[2]) + budget -= cnt + if budget < 0: + raise Invalid("lattice basis too skewed (translate enumeration cap exceeded); use a reduced basis") + for n in itertools.product(*rng): + if i == j and n == (0, 0, 0): + continue + tf = n[0] * Bf[0] + n[1] * Bf[1] + n[2] * Bf[2] + if np.linalg.norm(d + tf) > reach: + continue + ti = tuple(n[0] * Bi[0][c] + n[1] * Bi[1][c] + n[2] * Bi[2][c] for c in range(3)) + Q = [(v[0] + ti[0], v[1] + ti[1], v[2] + ti[2]) for v in Ti[j]] + pairs += 1 + if not _separated(Ti[i], Q, ax[i], ax[j], ed[i], ed[j]): + raise Invalid(f"tetrahedron {i} overlaps tetrahedron {j} translated by lattice vector {list(n)}") + return float(dens), {"density": str(dens), "k": k, "pairs_checked": pairs} diff --git a/graders/lib_cage/check.py b/graders/lib_cage/check.py new file mode 100644 index 0000000000000000000000000000000000000000..dfcc40749ca3e3a528c7445291ee10e119aeb313 --- /dev/null +++ b/graders/lib_cage/check.py @@ -0,0 +1,95 @@ +"""Leaps in Bounds `cage-{k}-{g}` (MIT): a k-regular simple graph of girth >= g on as few vertices as possible. + +The answer is an explicit graph: {"n": N, "edges": [[u, v], ...]} on vertices 0..N-1. +Valid iff simple (no loops / repeated edges), every vertex has degree exactly k, and girth >= g. +Objective N (minimize). Exact integer check. + +Girth >= g instead of upstream's girth == g: n(k, g) is strictly increasing in g (Fu-Huang-Rodger 1997), so a +k-regular graph of girth > g on N vertices still certifies n(k, g) < n(k, g+1) <= N. +Girth test: BFS from every vertex, expanding a vertex u only while 2*dist(u)+1 < g; a non-tree edge (u, w) closes +a closed walk of length dist(u)+dist(w)+1 which contains a cycle at most that long, and every shortest cycle is +found from one of its own vertices, so the minimum over all sources is exactly the girth (when < g). +Upstream audit (scripts/certificates/families/cage.py + graphs.girth): sound; nothing to fix beyond the input +format (graph6/sparse6 -> JSON edge list with explicit range/duplicate/bool checks here). +""" +from run import Invalid, as_int + + +def read_graph(ans, nmax, k): + if not isinstance(ans, dict): + raise Invalid("answer must be an object") + n = as_int(ans.get("n"), "n", 1, nmax) + E = ans.get("edges") + if not isinstance(E, list): + raise Invalid("edges must be a list") + if len(E) != k * n // 2 or (k * n) % 2: + raise Invalid(f"a {k}-regular graph on {n} vertices has exactly {k * n // 2} edges (k*n must be even)") + adj = [[] for _ in range(n)] + seen = set() + for e in E: + if not isinstance(e, list) or len(e) != 2: + raise Invalid("each edge must be a list [u, v]") + u, v = e + for x in (u, v): + if isinstance(x, bool) or not isinstance(x, int) or not 0 <= x < n: + raise Invalid(f"edge endpoint {x!r} is not an integer in [0, {n - 1}]") + if u == v: + raise Invalid(f"loop at {u}") + key = (u, v) if u < v else (v, u) + if key in seen: + raise Invalid(f"repeated edge {list(key)}") + seen.add(key) + adj[u].append(v) + adj[v].append(u) + return n, adj + + +def girth_below(adj, g): + """Return the length of some cycle shorter than g (the girth, if it is < g), else None.""" + n = len(adj) + best = None + dist = [-1] * n + par = [-1] * n + for s in range(n): + touched = [s] + dist[s] = 0 + frontier = [s] + found = None + while frontier and found is None: + nxt = [] + for u in frontier: + du = dist[u] + if 2 * du + 1 >= g: + continue + for w in adj[u]: + if w == par[u]: + continue + if dist[w] == -1: + dist[w] = du + 1 + par[w] = u + touched.append(w) + nxt.append(w) + else: + L = du + dist[w] + 1 + if L < g and (found is None or L < found): + found = L + frontier = nxt + for x in touched: + dist[x] = -1 + par[x] = -1 + if found is not None: + best = found if best is None else min(best, found) + return best + return best + + +def check(inst, ans): + k, g = inst["k"], inst["g"] + n, adj = read_graph(ans, inst["max_vertices"], k) + for v in range(n): + if len(adj[v]) != k: + raise Invalid(f"vertex {v} has degree {len(adj[v])}, not {k}") + c = girth_below(adj, g) + if c is not None: + raise Invalid(f"graph has a cycle of length {c} < {g}") + return n, {"vertices": n} diff --git a/graders/lib_circle_in_square/check.py b/graders/lib_circle_in_square/check.py new file mode 100644 index 0000000000000000000000000000000000000000..7768466e6f6c6948a8f26d267270b31bb6f43ee2 --- /dev/null +++ b/graders/lib_circle_in_square/check.py @@ -0,0 +1,46 @@ +"""Leaps in Bounds `circle-in-square-{n}` (MIT): the smallest square side s(n) holding n non-overlapping unit +circles, posed in its equivalent scale-free form: n points in the unit square [0,1]^2 maximizing the minimum +pairwise distance m; then s = 2 + 2/m (scale the points by 2/m, add a margin of 1). + +Answer {"points": [[x, y], ...]}: exactly n points, JSON numbers with 0 <= x, y <= 1 (checked exactly: JSON +floats are binary rationals, read exactly with fractions.Fraction). The minimum squared distance is computed +exactly in rationals; only the final objective s = 2 + 2/sqrt(min d^2) is a float. Coincident points invalid. +No feasibility tolerance is needed: every point set in the square is a valid packing at its own s. +Upstream audit (families/circle_in_square.py): exact radical arithmetic, sound; the port changes the +parametrization (unit square + computed side) so that float answers are exact. +""" +import math +from fractions import Fraction + +from run import Invalid, num + + +def check(inst, ans): + n = inst["n"] + P = ans.get("points") + if not isinstance(P, list) or len(P) != n: + raise Invalid(f"points must be a list of exactly {n} points") + pts = [] + for p in P: + if not isinstance(p, list) or len(p) != 2: + raise Invalid("each point must be [x, y]") + q = [] + for c in p: + num(c, "coordinate") + f = Fraction(c) + if not 0 <= f <= 1: + raise Invalid(f"coordinate {c} outside [0, 1]") + q.append(f) + pts.append(q) + best = None + for i in range(n): + xi, yi = pts[i] + for j in range(i + 1, n): + d = (xi - pts[j][0]) ** 2 + (yi - pts[j][1]) ** 2 + if best is None or d < best: + best = d + if best == 0: + raise Invalid("two points coincide") + m = math.sqrt(best.numerator / best.denominator) if best.denominator < 1 << 1000 else math.sqrt(float(best)) + s = 2 + 2 / m + return s, {"min_distance": m, "side": s} diff --git a/graders/lib_circle_in_triangle/check.py b/graders/lib_circle_in_triangle/check.py new file mode 100644 index 0000000000000000000000000000000000000000..025ab2239ada4d8f75966de18af78226380a3de8 --- /dev/null +++ b/graders/lib_circle_in_triangle/check.py @@ -0,0 +1,42 @@ +"""Leaps in Bounds `circle-in-equilateral-{n}` (MIT): the smallest equilateral triangle (side s) holding n +non-overlapping unit circles, in scale-free form: n points in the unit equilateral triangle T with vertices +(0,0), (1,0), (1/2, sqrt(3)/2) maximizing the minimum pairwise distance m; then s = 2/m + 2*sqrt(3) +(scale by 2/m, then push each side out by distance 1, which adds 2*sqrt(3) to the side). + +Containment is decided exactly for the (binary-rational) JSON floats: y >= 0, x >= 0, 1 - x >= 0, +3x^2 >= y^2 and 3(1-x)^2 >= y^2 (i.e. y <= sqrt(3) x and y <= sqrt(3)(1-x) without irrational arithmetic). +min squared distance exact (Fraction); only s is a float. Coincident points invalid. +Upstream audit (families/circle_in_triangle.py): exact radicals, sound; port re-parametrized as above. +""" +import math +from fractions import Fraction + +from run import Invalid, num + + +def check(inst, ans): + n = inst["n"] + P = ans.get("points") + if not isinstance(P, list) or len(P) != n: + raise Invalid(f"points must be a list of exactly {n} points") + pts = [] + for p in P: + if not isinstance(p, list) or len(p) != 2: + raise Invalid("each point must be [x, y]") + for c in p: + num(c, "coordinate") + x, y = Fraction(p[0]), Fraction(p[1]) + if not (y >= 0 and x >= 0 and x <= 1 and 3 * x * x >= y * y and 3 * (1 - x) ** 2 >= y * y): + raise Invalid(f"point {p} is outside the triangle") + pts.append((x, y)) + best = None + for i in range(n): + for j in range(i + 1, n): + d = (pts[i][0] - pts[j][0]) ** 2 + (pts[i][1] - pts[j][1]) ** 2 + if best is None or d < best: + best = d + if best == 0: + raise Invalid("two points coincide") + m = math.sqrt(best.numerator / best.denominator) + s = 2 / m + 2 * math.sqrt(3) + return s, {"min_distance": m, "side": s} diff --git a/graders/lib_coil_in_the_box/check.py b/graders/lib_coil_in_the_box/check.py new file mode 100644 index 0000000000000000000000000000000000000000..2205a0f5d7cf35ba5b7fa705ed13bda707175e72 --- /dev/null +++ b/graders/lib_coil_in_the_box/check.py @@ -0,0 +1,44 @@ +"""Leaps in Bounds `snake-in-the-box-{n}` / `coil-in-the-box-{n}` (MIT): long induced paths (snakes) or induced +cycles (coils) in the hypercube Q_n. + +Answer {"transitions": [c_1, ..., c_L]}: the coordinate (0..n-1) flipped along each edge, starting at vertex 0. +Snake: the L+1 visited vertices are distinct and two of them are adjacent in Q_n only if consecutive. +Coil (inst["coil"]): the walk returns to 0 after L >= 4 steps, the L vertices are distinct and two are adjacent +only if cyclically consecutive. Objective L (maximize). Exact check, O(L n). +Upstream audit (families/snake_in_the_box.py): sound; the port uses a JSON integer list instead of base-36 text. +""" +from run import Invalid + + +def check(inst, ans): + n, coil = inst["n"], inst["coil"] + T = ans.get("transitions") + if not isinstance(T, list) or not T: + raise Invalid("transitions must be a non-empty list") + if len(T) > inst["max_length"]: + raise Invalid(f"at most {inst['max_length']} transitions") + for c in T: + if isinstance(c, bool) or not isinstance(c, int) or not 0 <= c < n: + raise Invalid(f"transition {c!r} is not an integer coordinate in [0, {n - 1}]") + verts = [0] + for c in T: + verts.append(verts[-1] ^ (1 << c)) + if coil: + if len(T) < 4 or verts[-1] != 0: + raise Invalid("a coil must have >= 4 edges and return to vertex 0") + verts.pop() + pos = {} + for i, v in enumerate(verts): + if v in pos: + raise Invalid(f"vertex {v} is visited twice") + pos[v] = i + m = len(verts) + for i, v in enumerate(verts): + for c in range(n): + j = pos.get(v ^ (1 << c)) + if j is None: + continue + gap = abs(i - j) + if gap != 1 and not (coil and gap == m - 1): + raise Invalid(f"vertices at positions {min(i, j)} and {max(i, j)} are adjacent (not induced)") + return len(T), {"length": len(T)} diff --git a/graders/lib_degree_diameter/check.py b/graders/lib_degree_diameter/check.py new file mode 100644 index 0000000000000000000000000000000000000000..ecae368dcaa8d2fb27d77afa69d555d775d5976f --- /dev/null +++ b/graders/lib_degree_diameter/check.py @@ -0,0 +1,54 @@ +"""Leaps in Bounds `degree-diameter-{d}-{k}` (MIT): a graph of maximum degree <= d and diameter <= k with as +many vertices as possible (lower bounds on N(d, k) by construction). + +Answer {"n": N, "edges": [[u, v], ...]} on vertices 0..N-1. Valid iff simple, max degree <= d, connected and +every pair of vertices at distance <= k. Objective N (maximize). Exact integer check: N BFS runs via +scipy.sparse.csgraph (unweighted shortest paths). N is capped at the Moore bound 1 + d * sum_{i d * n // 2: + raise Invalid(f"edges must be a list of at most {d * n // 2} edges") + deg = [0] * n + seen = set() + for e in E: + if not isinstance(e, list) or len(e) != 2: + raise Invalid("each edge must be a list [u, v]") + u, v = e + for x in (u, v): + if isinstance(x, bool) or not isinstance(x, int) or not 0 <= x < n: + raise Invalid(f"edge endpoint {x!r} is not an integer in [0, {n - 1}]") + if u == v: + raise Invalid(f"loop at {u}") + key = (u, v) if u < v else (v, u) + if key in seen: + raise Invalid(f"repeated edge {list(key)}") + seen.add(key) + deg[u] += 1 + deg[v] += 1 + if max(deg) > d: + raise Invalid(f"a vertex has degree {max(deg)} > {d}") + if n > 1: + if not E: + raise Invalid("graph is disconnected") + a = np.array(E, dtype=np.int64) + m = csr_matrix((np.ones(len(a)), (a[:, 0], a[:, 1])), shape=(n, n)) + D = shortest_path(m, method="D", directed=False, unweighted=True) + if not np.all(np.isfinite(D)): + raise Invalid("graph is disconnected") + diam = int(D.max()) + if diam > k: + raise Invalid(f"graph has diameter {diam} > {k}") + else: + diam = 0 + return n, {"vertices": n, "diameter": diam, "max_degree": max(deg)} diff --git a/graders/lib_disk_covering/check.py b/graders/lib_disk_covering/check.py new file mode 100644 index 0000000000000000000000000000000000000000..9f99f3bc55403a5fd05bb4429301796818adb1b7 --- /dev/null +++ b/graders/lib_disk_covering/check.py @@ -0,0 +1,89 @@ +"""Leaps in Bounds `disk-covering-{n}` (MIT): the smallest radius r(n) such that n closed disks of radius r cover +the closed unit disk. + +Answer {"centers": [[x, y], ...], "radius": r}: exactly n centres with |x|, |y| <= 2 and 0 < r <= 1 (JSON +numbers, read as the exact binary rationals they denote). Validity is certified exactly, as upstream does: +the square [-1,1]^2 is split recursively into quadrants; a square is discarded when it misses the closed unit +disk, accepted when it lies entirely in one covering disk (all corners within distance r: disks are convex), and +split otherwise; all comparisons are on integers (everything scaled by the common power-of-two denominator and +2^MAX_DEPTH). Reaching depth MAX_DEPTH or more than max_squares squares -> invalid ("not certified"): a covering +that is tight somewhere (as optimal coverings are at their triple points) cannot be certified, so the radius +must carry a little slack (e.g. round it up in the 6th-7th decimal). Each child square only tests the disks that +meet its parent. Objective: r (minimize). +Upstream audit (families/disk_covering.py): same algorithm (2M-square cap, depth 60), sound; ported with a +smaller cap (sandbox time limit) and candidate-disk pruning. +""" +from fractions import Fraction + +from run import Invalid, num + +MAX_DEPTH = 48 + + +def check(inst, ans): + n = inst["n"] + C = ans.get("centers") + if not isinstance(C, list) or len(C) != n: + raise Invalid(f"centers must be a list of exactly {n} points") + r = ans.get("radius") + num(r, "radius") + r = Fraction(r) + if not 0 < r <= 1: + raise Invalid("radius must be in (0, 1]") + cs = [] + for p in C: + if not isinstance(p, list) or len(p) != 2: + raise Invalid("each centre must be [x, y]") + q = [] + for c in p: + num(c, "coordinate") + f = Fraction(c) + if abs(f) > 2: + raise Invalid("centre coordinates must satisfy |x|, |y| <= 2") + q.append(f) + cs.append(q) + den = max([r.denominator] + [f.denominator for q in cs for f in q]) # all powers of two + if den > 1 << 200: + raise Invalid("coordinates/radius need too many binary digits (avoid tiny non-zero values such as 1e-70; round to ~15 decimals)") + scale = den << MAX_DEPTH + big = [(int(x * scale), int(y * scale)) for x, y in cs] + R2 = int(r * scale) ** 2 + U2 = scale * scale + budget = inst["max_squares"] + stack = [(-scale, -scale, 2 * scale, 0, tuple(range(n)))] + squares = 0 + while stack: + x0, y0, side, depth, cand = stack.pop() + squares += 1 + if squares > budget: + raise Invalid(f"covering not certified within {budget} squares: it misses part of the disk or is too " + "tight (increase the radius slightly)") + x1, y1 = x0 + side, y0 + side + dx = x0 if x0 > 0 else (-x1 if x1 < 0 else 0) + dy = y0 if y0 > 0 else (-y1 if y1 < 0 else 0) + if dx * dx + dy * dy > U2: + continue + keep = [] + covered = False + for i in cand: + cx, cy = big[i] + fx = max(cx - x0, x1 - cx) + fy = max(cy - y0, y1 - cy) + if fx * fx + fy * fy <= R2: + covered = True + break + nx = x0 - cx if cx < x0 else (cx - x1 if cx > x1 else 0) + ny = y0 - cy if cy < y0 else (cy - y1 if cy > y1 else 0) + if nx * nx + ny * ny <= R2: + keep.append(i) + if covered: + continue + if not keep or depth == MAX_DEPTH: + raise Invalid(f"the disks do not cover the unit disk near ({float(Fraction(x0, scale)):.6f}, " + f"{float(Fraction(y0, scale)):.6f}) (or only just: increase the radius slightly)") + half = side // 2 + kt = tuple(keep) + for ox in (0, half): + for oy in (0, half): + stack.append((x0 + ox, y0 + oy, half, depth + 1, kt)) + return float(r), {"radius": float(r), "squares": squares} diff --git a/graders/lib_golomb_ruler/check.py b/graders/lib_golomb_ruler/check.py new file mode 100644 index 0000000000000000000000000000000000000000..eb5ad46cb1fb395bf106e7b32fa464998eb52f7b --- /dev/null +++ b/graders/lib_golomb_ruler/check.py @@ -0,0 +1,25 @@ +"""Leaps in Bounds `golomb-ruler-{n}` (MIT): an n-mark Golomb ruler (all pairwise differences distinct) of +minimum length. + +Answer {"marks": [a_1, ..., a_n]}: n distinct integers in [0, max_length]. Valid iff all n(n-1)/2 differences +are distinct. Objective: max(marks) - min(marks) (minimize). Exact integer check. +Upstream audit (families/golomb.py): sound. (MCO's mc_golomb is a *construct* task for n <= 20 with the +optimal length given; this optimize family uses n >= 24.) +""" +from run import Invalid, int_list + + +def check(inst, ans): + n = inst["n"] + a = int_list(ans.get("marks"), n, 0, inst["max_length"], "marks") + if len(set(a)) != n: + raise Invalid("marks must be distinct") + s = sorted(a) + seen = set() + for i in range(n): + for j in range(i + 1, n): + d = s[j] - s[i] + if d in seen: + raise Invalid(f"difference {d} occurs twice") + seen.add(d) + return s[-1] - s[0], {"length": s[-1] - s[0]} diff --git a/graders/lib_isosceles_set/check.py b/graders/lib_isosceles_set/check.py new file mode 100644 index 0000000000000000000000000000000000000000..d59c79e1ed6b753cbb59324e485b7223d89b7508 --- /dev/null +++ b/graders/lib_isosceles_set/check.py @@ -0,0 +1,64 @@ +"""Leaps in Bounds `isosceles-set-{n}` (MIT): the most points in R^n such that every three form an isosceles +triangle (two equal sides; degenerate collinear triples count as isosceles only if two sides are equal). + +Answer {"points": [[c_1, ..., c_D], ...]}: integer coordinates (D <= max_coords, |c| <= 10^6; any rational set +can be scaled to integers), distinct points, spanning an affine subspace of dimension <= n (exact rank by +Fraction Gaussian elimination). Every triple must have two equal squared distances (exact integers). +Objective: number of points (maximize). Upstream audit (families/isosceles_set.py): same checks, sound. +""" +from fractions import Fraction + +from run import Invalid + + +def affine_rank(pts): + rows = [[Fraction(a - b) for a, b in zip(p, pts[0])] for p in pts[1:]] + rank = 0 + cols = len(pts[0]) + for col in range(cols): + piv = next((r for r in range(rank, len(rows)) if rows[r][col] != 0), None) + if piv is None: + continue + rows[rank], rows[piv] = rows[piv], rows[rank] + pv = rows[rank][col] + for r in range(len(rows)): + if r != rank and rows[r][col] != 0: + f = rows[r][col] / pv + rows[r] = [x - f * y for x, y in zip(rows[r], rows[rank])] + rank += 1 + return rank + + +def check(inst, ans): + n = inst["n"] + P = ans.get("points") + if not isinstance(P, list) or not 1 <= len(P) <= inst["max_points"]: + raise Invalid(f"points must be a list of 1..{inst['max_points']} points") + D = None + for p in P: + if not isinstance(p, list) or not 1 <= len(p) <= inst["max_coords"]: + raise Invalid(f"each point must be a list of 1..{inst['max_coords']} integers") + if D is None: + D = len(p) + if len(p) != D: + raise Invalid("all points must have the same number of coordinates") + for c in p: + if isinstance(c, bool) or not isinstance(c, int) or abs(c) > 10 ** 6: + raise Invalid(f"coordinate {c!r} is not an integer with |c| <= 10^6") + pts = [tuple(p) for p in P] + if len(set(pts)) != len(pts): + raise Invalid("points must be distinct") + if affine_rank(pts) > n: + raise Invalid(f"points span an affine subspace of dimension > {n}") + m = len(pts) + d = [[sum((a - b) ** 2 for a, b in zip(p, q)) for q in pts] for p in pts] + for i in range(m): + di = d[i] + for j in range(i + 1, m): + a = di[j] + dj = d[j] + for k in range(j + 1, m): + b, c = di[k], dj[k] + if a != b and a != c and b != c: + raise Invalid(f"points {i}, {j}, {k} form a scalene triangle") + return m, {"points": m} diff --git a/graders/lib_no_three_in_line/check.py b/graders/lib_no_three_in_line/check.py new file mode 100644 index 0000000000000000000000000000000000000000..96e320d4a81606f8f01a07fb11caf37b4eb92cd9 --- /dev/null +++ b/graders/lib_no_three_in_line/check.py @@ -0,0 +1,41 @@ +"""Leaps in Bounds `no-three-in-line-{n}` (MIT): as many points of the n x n grid as possible, no three on a line. + +Answer {"points": [[x, y], ...]} with integers 0 <= x, y < n, distinct, at most 2n of them (a trivial upper +bound: each row holds <= 2). Valid iff no three points are collinear: every pair spans a line, normalized to +coprime (a, b, c) with a x + b y = c and a sign convention, and no line may be spanned twice (exact integers). +Objective: number of points (maximize). +Upstream audit (geometry.no_three_collinear): sound. MCO already has n = 75 (ea_no_three_in_line_75); not used here. +""" +from math import gcd + +from run import Invalid + + +def check(inst, ans): + n = inst["n"] + P = ans.get("points") + if not isinstance(P, list) or not 1 <= len(P) <= 2 * n: + raise Invalid(f"points must be a list of 1..{2 * n} points") + pts = [] + for p in P: + if not isinstance(p, list) or len(p) != 2: + raise Invalid("each point must be [x, y]") + for c in p: + if isinstance(c, bool) or not isinstance(c, int) or not 0 <= c < n: + raise Invalid(f"coordinate {c!r} is not an integer in [0, {n - 1}]") + pts.append((p[0], p[1])) + if len(set(pts)) != len(pts): + raise Invalid("points must be distinct") + lines = set() + for i, (x1, y1) in enumerate(pts): + for x2, y2 in pts[i + 1:]: + a, b = y2 - y1, x1 - x2 + g = gcd(a, b) + a, b = a // g, b // g + if a < 0 or (a == 0 and b < 0): + a, b = -a, -b + key = (a, b, a * x1 + b * y1) + if key in lines: + raise Invalid(f"three points on the line {key[0]}x + {key[1]}y = {key[2]}") + lines.add(key) + return len(pts), {"points": len(pts)} diff --git a/graders/lib_snake_in_the_box/check.py b/graders/lib_snake_in_the_box/check.py new file mode 100644 index 0000000000000000000000000000000000000000..2205a0f5d7cf35ba5b7fa705ed13bda707175e72 --- /dev/null +++ b/graders/lib_snake_in_the_box/check.py @@ -0,0 +1,44 @@ +"""Leaps in Bounds `snake-in-the-box-{n}` / `coil-in-the-box-{n}` (MIT): long induced paths (snakes) or induced +cycles (coils) in the hypercube Q_n. + +Answer {"transitions": [c_1, ..., c_L]}: the coordinate (0..n-1) flipped along each edge, starting at vertex 0. +Snake: the L+1 visited vertices are distinct and two of them are adjacent in Q_n only if consecutive. +Coil (inst["coil"]): the walk returns to 0 after L >= 4 steps, the L vertices are distinct and two are adjacent +only if cyclically consecutive. Objective L (maximize). Exact check, O(L n). +Upstream audit (families/snake_in_the_box.py): sound; the port uses a JSON integer list instead of base-36 text. +""" +from run import Invalid + + +def check(inst, ans): + n, coil = inst["n"], inst["coil"] + T = ans.get("transitions") + if not isinstance(T, list) or not T: + raise Invalid("transitions must be a non-empty list") + if len(T) > inst["max_length"]: + raise Invalid(f"at most {inst['max_length']} transitions") + for c in T: + if isinstance(c, bool) or not isinstance(c, int) or not 0 <= c < n: + raise Invalid(f"transition {c!r} is not an integer coordinate in [0, {n - 1}]") + verts = [0] + for c in T: + verts.append(verts[-1] ^ (1 << c)) + if coil: + if len(T) < 4 or verts[-1] != 0: + raise Invalid("a coil must have >= 4 edges and return to vertex 0") + verts.pop() + pos = {} + for i, v in enumerate(verts): + if v in pos: + raise Invalid(f"vertex {v} is visited twice") + pos[v] = i + m = len(verts) + for i, v in enumerate(verts): + for c in range(n): + j = pos.get(v ^ (1 << c)) + if j is None: + continue + gap = abs(i - j) + if gap != 1 and not (coil and gap == m - 1): + raise Invalid(f"vertices at positions {min(i, j)} and {max(i, j)} are adjacent (not induced)") + return len(T), {"length": len(T)} diff --git a/graders/lib_sorting_network_depth/check.py b/graders/lib_sorting_network_depth/check.py new file mode 100644 index 0000000000000000000000000000000000000000..18dbadcdbdcfa719d61214395ecb541ecba7ce6f --- /dev/null +++ b/graders/lib_sorting_network_depth/check.py @@ -0,0 +1,74 @@ +"""Leaps in Bounds `sorting-network-size-{n}` / `sorting-network-depth-{n}` (MIT): sorting networks on n wires +with few comparators (size) or few parallel steps (depth). + +Answer {"comparators": [[i, j], ...]} applied in order; comparator [i, j] (i != j, wires 0..n-1) puts the smaller +value on wire min(i, j) and the larger on max(i, j). Valid iff it sorts every input (wire 0 smallest). +Objective: number of comparators (inst["metric"] == "size") or depth (longest chain of comparators each sharing a +wire with the previous one; step(c) = 1 + max(step of the last comparators on its two wires)). Minimize. + +Exact verification by the 0-1 principle: it suffices to sort every 0/1 input; moreover the "leading" +comparators (each the first comparator on both of its wires; they commute with everything before them) map +{0,1}^2 onto {00, 01, 11} on their wire pair, so only 3^p 2^(n-2p) vectors need to be pushed through the rest +of the network (p = number of leading comparators). These are enumerated exhaustively as n-bit integers in numpy. +The count is capped at inst["max_inputs"]: a network whose leading comparators cover too few wires is rejected +as unverifiable (stated in the prompt). Upstream audit (families/sorting_network.py): same method, sound. +""" +import numpy as np + +from run import Invalid + + +def depth(C): + step = {} + for i, j in C: + step[i] = step[j] = max(step.get(i, 0), step.get(j, 0)) + 1 + return max(step.values(), default=0) + + +def check(inst, ans): + n = inst["n"] + C = ans.get("comparators") + if not isinstance(C, list) or len(C) > inst["max_comparators"]: + raise Invalid(f"comparators must be a list of at most {inst['max_comparators']} pairs") + comps = [] + for c in C: + if not isinstance(c, list) or len(c) != 2: + raise Invalid("each comparator must be [i, j]") + for x in c: + if isinstance(x, bool) or not isinstance(x, int) or not 0 <= x < n: + raise Invalid(f"wire {x!r} is not an integer in [0, {n - 1}]") + if c[0] == c[1]: + raise Invalid("a comparator must join two different wires") + comps.append((min(c), max(c))) + used, first, rest = set(), [], [] + for i, j in comps: + (first if i not in used and j not in used else rest).append((i, j)) + used.update((i, j)) + paired = {w for c in first for w in c} + M = 3 ** len(first) * 2 ** (n - len(paired)) + if M > inst["max_inputs"]: + raise Invalid(f"network needs {M} test vectors (> {inst['max_inputs']}); start with a fuller first layer") + X = np.zeros(1, dtype=np.uint32) + for i, j in first: + pats = np.array([0, 1 << j, (1 << i) | (1 << j)], dtype=np.uint32) + X = (X[:, None] | pats[None, :]).ravel() + for k in range(n): + if k not in paired: + X = (X[:, None] | np.array([0, 1 << k], dtype=np.uint32)[None, :]).ravel() + a = np.empty_like(X) + b = np.empty_like(X) + for i, j in rest: + # swap bits i and j where bit i = 1 and bit j = 0 (the 1 moves up to wire j) + np.right_shift(X, i, out=a) + np.right_shift(X, j, out=b) + np.invert(b, out=b) + np.bitwise_and(a, b, out=a) + np.bitwise_and(a, np.uint32(1), out=a) + np.multiply(a, np.uint32((1 << i) | (1 << j)), out=a) + np.bitwise_xor(X, a, out=X) + bad = (X & ~(X >> np.uint32(1))) & np.uint32((1 << (n - 1)) - 1) + if bad.any(): + v = int(X[np.flatnonzero(bad)[0]]) + raise Invalid(f"network leaves an unsorted 0/1 output (bits {format(v, f'0{n}b')[::-1]}, wire 0 first)") + size, dep = len(comps), depth(comps) + return (size if inst["metric"] == "size" else dep), {"size": size, "depth": dep} diff --git a/graders/lib_sorting_network_size/check.py b/graders/lib_sorting_network_size/check.py new file mode 100644 index 0000000000000000000000000000000000000000..18dbadcdbdcfa719d61214395ecb541ecba7ce6f --- /dev/null +++ b/graders/lib_sorting_network_size/check.py @@ -0,0 +1,74 @@ +"""Leaps in Bounds `sorting-network-size-{n}` / `sorting-network-depth-{n}` (MIT): sorting networks on n wires +with few comparators (size) or few parallel steps (depth). + +Answer {"comparators": [[i, j], ...]} applied in order; comparator [i, j] (i != j, wires 0..n-1) puts the smaller +value on wire min(i, j) and the larger on max(i, j). Valid iff it sorts every input (wire 0 smallest). +Objective: number of comparators (inst["metric"] == "size") or depth (longest chain of comparators each sharing a +wire with the previous one; step(c) = 1 + max(step of the last comparators on its two wires)). Minimize. + +Exact verification by the 0-1 principle: it suffices to sort every 0/1 input; moreover the "leading" +comparators (each the first comparator on both of its wires; they commute with everything before them) map +{0,1}^2 onto {00, 01, 11} on their wire pair, so only 3^p 2^(n-2p) vectors need to be pushed through the rest +of the network (p = number of leading comparators). These are enumerated exhaustively as n-bit integers in numpy. +The count is capped at inst["max_inputs"]: a network whose leading comparators cover too few wires is rejected +as unverifiable (stated in the prompt). Upstream audit (families/sorting_network.py): same method, sound. +""" +import numpy as np + +from run import Invalid + + +def depth(C): + step = {} + for i, j in C: + step[i] = step[j] = max(step.get(i, 0), step.get(j, 0)) + 1 + return max(step.values(), default=0) + + +def check(inst, ans): + n = inst["n"] + C = ans.get("comparators") + if not isinstance(C, list) or len(C) > inst["max_comparators"]: + raise Invalid(f"comparators must be a list of at most {inst['max_comparators']} pairs") + comps = [] + for c in C: + if not isinstance(c, list) or len(c) != 2: + raise Invalid("each comparator must be [i, j]") + for x in c: + if isinstance(x, bool) or not isinstance(x, int) or not 0 <= x < n: + raise Invalid(f"wire {x!r} is not an integer in [0, {n - 1}]") + if c[0] == c[1]: + raise Invalid("a comparator must join two different wires") + comps.append((min(c), max(c))) + used, first, rest = set(), [], [] + for i, j in comps: + (first if i not in used and j not in used else rest).append((i, j)) + used.update((i, j)) + paired = {w for c in first for w in c} + M = 3 ** len(first) * 2 ** (n - len(paired)) + if M > inst["max_inputs"]: + raise Invalid(f"network needs {M} test vectors (> {inst['max_inputs']}); start with a fuller first layer") + X = np.zeros(1, dtype=np.uint32) + for i, j in first: + pats = np.array([0, 1 << j, (1 << i) | (1 << j)], dtype=np.uint32) + X = (X[:, None] | pats[None, :]).ravel() + for k in range(n): + if k not in paired: + X = (X[:, None] | np.array([0, 1 << k], dtype=np.uint32)[None, :]).ravel() + a = np.empty_like(X) + b = np.empty_like(X) + for i, j in rest: + # swap bits i and j where bit i = 1 and bit j = 0 (the 1 moves up to wire j) + np.right_shift(X, i, out=a) + np.right_shift(X, j, out=b) + np.invert(b, out=b) + np.bitwise_and(a, b, out=a) + np.bitwise_and(a, np.uint32(1), out=a) + np.multiply(a, np.uint32((1 << i) | (1 << j)), out=a) + np.bitwise_xor(X, a, out=X) + bad = (X & ~(X >> np.uint32(1))) & np.uint32((1 << (n - 1)) - 1) + if bad.any(): + v = int(X[np.flatnonzero(bad)[0]]) + raise Invalid(f"network leaves an unsorted 0/1 output (bits {format(v, f'0{n}b')[::-1]}, wire 0 first)") + size, dep = len(comps), depth(comps) + return (size if inst["metric"] == "size" else dep), {"size": size, "depth": dep} diff --git a/graders/lib_square_packing/check.py b/graders/lib_square_packing/check.py new file mode 100644 index 0000000000000000000000000000000000000000..144df5ac5678f0c98df11b1674999fef13a265f9 --- /dev/null +++ b/graders/lib_square_packing/check.py @@ -0,0 +1,68 @@ +"""Leaps in Bounds `square-packing-in-square-{n}` (MIT): the smallest square side s(n) into which n unit squares +can be packed (pairwise disjoint interiors, any rotations). + +Answer {"denominator": D, "squares": [[X, Y, p, q], ...]}: exactly n unit squares; square k has centre +(X/D, Y/D) and is rotated by the angle t with cos t = (p^2 - q^2)/(p^2 + q^2), sin t = 2pq/(p^2 + q^2) +(a Pythagorean rotation; [p, q] = [1, 0] is axis-parallel). All integers: 1 <= D <= 10^12, |X|, |Y| <= 100 D, +|p|, |q| <= 10^6, (p, q) != (0, 0). Restricting to rational rotations loses nothing in the infimum (rational +angles are dense), so the record values can be approached arbitrarily closely; vertices are then rational and +everything is decided exactly with fractions.Fraction. +Overlap test (separating axis theorem): two convex polygons have disjoint interiors iff for one of the 4 edge +normals of the two squares their projections overlap in at most one point. Pairs with centre distance^2 >= 2 +(> sum of circumradii) are skipped. Objective: side of the bounding square of all vertices, +s = max(x_max - x_min, y_max - y_min) (minimize); the packing fits in [0, s]^2 after translation. +Upstream: only Lean certificates are accepted there for this family; this checker is new. +""" +from fractions import Fraction + +from run import Invalid + + +def _int(x, lo, hi, name): + if isinstance(x, bool) or not isinstance(x, int) or not lo <= x <= hi: + raise Invalid(f"{name} must be an integer in [{lo}, {hi}]") + return x + + +def check(inst, ans): + n = inst["n"] + D = _int(ans.get("denominator"), 1, 10 ** 12, "denominator") + S = ans.get("squares") + if not isinstance(S, list) or len(S) != n: + raise Invalid(f"squares must be a list of exactly {n} entries") + sq = [] + for e in S: + if not isinstance(e, list) or len(e) != 4: + raise Invalid("each square must be [X, Y, p, q]") + X = _int(e[0], -100 * D, 100 * D, "X") + Y = _int(e[1], -100 * D, 100 * D, "Y") + p = _int(e[2], -10 ** 6, 10 ** 6, "p") + q = _int(e[3], -10 ** 6, 10 ** 6, "q") + if p == 0 and q == 0: + raise Invalid("(p, q) must not be (0, 0)") + h = p * p + q * q + c, s = Fraction(p * p - q * q, h), Fraction(2 * p * q, h) + cx, cy = Fraction(X, D), Fraction(Y, D) + u = (c / 2, s / 2) + v = (-s / 2, c / 2) + verts = [(cx + a * u[0] + b * v[0], cy + a * u[1] + b * v[1]) for a, b in ((1, 1), (1, -1), (-1, -1), (-1, 1))] + sq.append((cx, cy, (c, s), (-s, c), verts)) + for i in range(n): + ci = sq[i] + for j in range(i + 1, n): + cj = sq[j] + if (ci[0] - cj[0]) ** 2 + (ci[1] - cj[1]) ** 2 >= 2: + continue + separated = False + for ax in (ci[2], ci[3], cj[2], cj[3]): + pi = [x * ax[0] + y * ax[1] for x, y in ci[4]] + pj = [x * ax[0] + y * ax[1] for x, y in cj[4]] + if max(pi) <= min(pj) or max(pj) <= min(pi): + separated = True + break + if not separated: + raise Invalid(f"squares {i} and {j} overlap") + xs = [x for e in sq for x, _ in e[4]] + ys = [y for e in sq for _, y in e[4]] + side = max(max(xs) - min(xs), max(ys) - min(ys)) + return float(side), {"side": float(side)} diff --git a/graders/lib_superpermutation/check.py b/graders/lib_superpermutation/check.py new file mode 100644 index 0000000000000000000000000000000000000000..5a9c448da63de25e8f2a69daeb91969a7f22c6e4 --- /dev/null +++ b/graders/lib_superpermutation/check.py @@ -0,0 +1,28 @@ +"""Leaps in Bounds `minimal-superpermutation-{n}` (MIT): a shortest string over {1..n} containing every +permutation of 1..n as a contiguous substring. + +Answer {"string": "1234..."} (digits '1'..'n', n <= 9; no separators). Valid iff the length is <= max_length +and all n! permutations occur as length-n windows. Objective: length (minimize). Exact check. +Upstream audit (families/superpermutation.py): sound (counts distinct windows whose symbol set is all n +symbols); the port only fixes the format: no whitespace/case folding, a hard length cap. +""" +import math + +from run import Invalid + + +def check(inst, ans): + n = inst["n"] + s = ans.get("string") + if not isinstance(s, str): + raise Invalid("string must be a JSON string") + if len(s) > inst["max_length"]: + raise Invalid(f"string longer than {inst['max_length']}") + alphabet = set("123456789"[:n]) + if not set(s) <= alphabet: + raise Invalid(f"string may only contain the digits 1..{n}") + perms = {s[i:i + n] for i in range(len(s) - n + 1)} + found = sum(1 for w in perms if len(set(w)) == n) + if found != math.factorial(n): + raise Invalid(f"string contains {found} of the {math.factorial(n)} permutations") + return len(s), {"length": len(s)} diff --git a/graders/tao_c15a_matmul_rank_exponent/check.py b/graders/tao_c15a_matmul_rank_exponent/check.py new file mode 100644 index 0000000000000000000000000000000000000000..e2b92b0dfe858c66d14250c81b7946b917378156 --- /dev/null +++ b/graders/tao_c15a_matmul_rank_exponent/check.py @@ -0,0 +1,49 @@ +"""Tao et al. Optimization Constants C_15a (matrix multiplication exponent omega): minimize the exponent +3 log r / log(nmp) certified by an exact rank-r bilinear algorithm for (n x m times m x p). + +Answer: format n,m,p, a common denominator q and integer matrices U (r x nm), V (r x mp), W (r x np); +the algorithm's coefficients are U/q, V/q, W/q. Exact check in int64 (|entries|, q <= 2^16, r <= nmp <= 216, +so every partial sum is < 2^57): sum_t U[t,(i,j)] V[t,(j',k)] W[t,(i',k')] = q^3 [i=i'][j=j'][k=k']. +A rank-r decomposition of over Q gives omega <= 3 log r / log(nmp) (symmetrization + recursion).""" +import math + +import numpy as np + +from run import Invalid, as_int, int_list + + +def _mat(v, rows, cols, lim, name): + if not isinstance(v, list) or len(v) != rows: + raise Invalid(f"{name} must have exactly r = {rows} rows") + for row in v: + int_list(row, cols, -lim, lim, name) + return np.array(v, dtype=np.int64).reshape(rows, cols) + + +def check(inst, ans): + cap, lim = inst["max_dim"], inst["max_abs_entry"] + n = as_int(ans.get("n"), "n", 1, cap) + m = as_int(ans.get("m"), "m", 1, cap) + p = as_int(ans.get("p"), "p", 1, cap) + if n * m * p < 2: + raise Invalid("need n*m*p >= 2") + q = as_int(ans.get("denominator"), "denominator", 1, lim) + U = ans.get("U") + if not isinstance(U, list) or not 1 <= len(U) <= n * m * p: + raise Invalid(f"U must have 1..n*m*p = {n * m * p} rows (the rank r)") + r = len(U) + U = _mat(U, r, n * m, lim, "U") + V = _mat(ans.get("V"), r, m * p, lim, "V") + W = _mat(ans.get("W"), r, n * p, lim, "W") + UV = U[:, :, None] * V[:, None, :] # (r, nm, mp), |.| <= 2^32 + T = np.einsum("tab,tc->abc", UV, W) # (nm, mp, np), |.| < 2^57 + target = np.zeros((n * m, m * p, n * p), dtype=np.int64) + q3 = q ** 3 + for i in range(n): + for j in range(m): + for k in range(p): + target[i * m + j, j * p + k, i * p + k] = q3 + if not np.array_equal(T, target): + bad = int(np.count_nonzero(T != target)) + raise Invalid(f"not a decomposition of the <{n},{m},{p}> tensor ({bad} wrong entries)") + return 3 * math.log(r) / math.log(n * m * p), {"n": n, "m": m, "p": p, "rank": r} diff --git a/graders/tao_c16a_brezis_gallouet_wainger/check.py b/graders/tao_c16a_brezis_gallouet_wainger/check.py new file mode 100644 index 0000000000000000000000000000000000000000..8f67540b95363ccbe780426b83d8976c0a115fa2 --- /dev/null +++ b/graders/tao_c16a_brezis_gallouet_wainger/check.py @@ -0,0 +1,48 @@ +"""Tao et al. Optimization Constants C_16 (Brezis-Gallouet-Wainger remainder constant L on T^2 = [0,2pi]^2): +maximize the lower bound L >= 4 pi |u(0)|^2/||grad u||^2 - ln delta - ln(1 + ln delta), delta = ||Lap u||^2/||grad u||^2. + +Answer class: radial lattice trigonometric polynomials u(x) = sum_{0 < |k|^2 <= N} g(|k|^2) e^{i k.x}, k in Z^2, +given by the real values g(1..N). Then u is real, zero-mean, and with r2(m) = #{k in Z^2 : |k|^2 = m}: + u(0) = sum r2(m) g(m), ||grad u||^2 = 4 pi^2 sum r2(m) m g(m)^2, ||Lap u||^2 = 4 pi^2 sum r2(m) m^2 g(m)^2. +Finite sums; float objective. delta >= 1 automatically (all |k|^2 >= 1).""" +import math + +import numpy as np + +from run import Invalid, float_list + +_R2 = {} + + +def _r2(N): + if N not in _R2: + R = math.isqrt(N) + k = np.arange(-R, R + 1) + a, b = np.meshgrid(k, k) + m = (a * a + b * b).ravel() + m = m[(m > 0) & (m <= N)] + _R2[N] = np.bincount(m, minlength=N + 1).astype(np.float64) + return _R2[N] + + +def check(inst, ans): + N = inst["max_shell"] + g = ans.get("g") + if not isinstance(g, list) or not 1 <= len(g) <= N: + raise Invalid(f"g must be a list of 1..{N} numbers (g(1), g(2), ...)") + g = np.array([0.0] + float_list(g, None, "g")) + if np.abs(g).max() > 1e100: + raise Invalid("|g| too large") + if np.abs(g).max() == 0: + raise Invalid("u must be non-zero") + g = g / np.abs(g).max() + r2 = _r2(N)[: len(g)] + m = np.arange(len(g), dtype=np.float64) + S0 = float((r2 * g).sum()) + S1 = float((r2 * m * g * g).sum()) + S2 = float((r2 * m * m * g * g).sum()) + if S1 <= 0: + raise Invalid("u must be non-zero (only empty shells used)") + delta = S2 / S1 + val = S0 * S0 / (math.pi * S1) - math.log(delta) - math.log1p(math.log(delta)) + return val, {"delta": delta, "u0_sq_over_grad_sq_times_4pi": S0 * S0 / (math.pi * S1)} diff --git a/graders/tao_c19a_berry_esseen/check.py b/graders/tao_c19a_berry_esseen/check.py new file mode 100644 index 0000000000000000000000000000000000000000..cdeac8e30d60990bd37fb7f0e6b468fd5a45cc60 --- /dev/null +++ b/graders/tao_c19a_berry_esseen/check.py @@ -0,0 +1,51 @@ +"""Tao et al. Optimization Constants C_19 (Berry-Esseen constant): maximize sqrt(n) Delta_n / beta_3. + +Answer: integer atoms a_i with positive integer weights w_i (P(X = a_i) = w_i / sum w), and n. +Mean and variance are exact rationals; the pmf of S_n = X_1 + ... + X_n lives on the integer lattice and is +computed by an FFT power of the characteristic function (absolute error ~1e-12). Since F_n is a step function +with jumps only at lattice points and Phi is continuous increasing, sup_x |F_n - Phi| is attained at a lattice +point z_k, as |F(k) - Phi(z_k)| or |F(k-) - Phi(z_k)|; the grader takes the max over all lattice points of the +support range. Float objective; numerical error in the score is < 1e-6.""" +import math +from fractions import Fraction + +import numpy as np +from scipy.special import ndtr + +from run import Invalid, as_int, int_list + + +def check(inst, ans): + n = as_int(ans.get("n"), "n", 1, inst["max_n"]) + atoms = ans.get("atoms") + weights = ans.get("weights") + if not isinstance(atoms, list) or not 2 <= len(atoms) <= inst["max_atoms"]: + raise Invalid(f"atoms must be a list of 2..{inst['max_atoms']} integers") + A = inst["max_abs_atom"] + int_list(atoms, None, -A, A, "atoms") + if len(set(atoms)) != len(atoms): + raise Invalid("atoms must be distinct") + int_list(weights, len(atoms), 1, inst["max_weight"], "weights") + W = sum(weights) + mu = Fraction(sum(a * w for a, w in zip(atoms, weights)), W) + var = sum(w * (a - mu) ** 2 for a, w in zip(atoms, weights)) / W + if var <= 0: + raise Invalid("degenerate distribution") + sigma = math.sqrt(var) + m3 = float(sum(w * abs(a - mu) ** 3 for a, w in zip(atoms, weights)) / W) + beta3 = m3 / sigma ** 3 + lo, hi = min(atoms), max(atoms) + pmf1 = np.zeros(hi - lo + 1) + for a, w in zip(atoms, weights): + pmf1[a - lo] = w / W + L = n * (hi - lo) + 1 + size = 1 << (L - 1).bit_length() + phi = np.fft.rfft(pmf1, size) + pmf = np.fft.irfft(phi ** n, size)[:L] + k = np.arange(L, dtype=np.float64) + n * lo # lattice values of S_n + z = (k - n * float(mu)) / (sigma * math.sqrt(n)) + F = np.cumsum(pmf) + Fm = F - pmf + Ph = ndtr(z) + delta = float(max(np.abs(F - Ph).max(), np.abs(Fm - Ph).max())) + return math.sqrt(n) * delta / beta3, {"n": n, "beta3": beta3, "Delta_n": delta, "lattice_points": L} diff --git a/graders/tao_c24a_komlos_discrepancy/check.py b/graders/tao_c24a_komlos_discrepancy/check.py new file mode 100644 index 0000000000000000000000000000000000000000..f0bed5c877e714ee7f4f0119f093851dcfab1ea0 --- /dev/null +++ b/graders/tao_c24a_komlos_discrepancy/check.py @@ -0,0 +1,40 @@ +"""Tao et al. Optimization Constants C_24 (Komlos discrepancy constant): maximize disc(A) over matrices with +columns of Euclidean norm <= 1. + +Answer: a positive integer denominator D and an integer matrix M (m x n); A = M / D. +Feasibility exact: sum_i M_ij^2 <= D^2 for every column j (integers). +disc(A) = min_{x in {-1,1}^n} ||A x||_inf, computed exactly: all 2^(n-1) sign vectors with x_1 = +1 +(x and -x are equivalent); M x is an exact integer (float64 products of integers < 2^53).""" +import numpy as np + +from run import Invalid, as_int, int_list + + +def check(inst, ans): + D = as_int(ans.get("denominator"), "denominator", 1, inst["max_denominator"]) + M = ans.get("matrix") + if not isinstance(M, list) or not 1 <= len(M) <= inst["max_rows"]: + raise Invalid(f"matrix must have 1..{inst['max_rows']} rows") + if not isinstance(M[0], list): + raise Invalid("matrix rows must be lists") + n = len(M[0]) + if not 1 <= n <= inst["max_cols"]: + raise Invalid(f"matrix must have 1..{inst['max_cols']} columns") + for r in M: + int_list(r, n, -D, D, "matrix row") + for j in range(n): + if sum(r[j] * r[j] for r in M) > D * D: + raise Invalid(f"column {j} has Euclidean norm > 1") + A = np.array(M, dtype=np.float64) # |entries| <= D <= 1e6, n <= 20: sums exact + best = None + total = 1 << (n - 1) + step = 1 << 16 + for s0 in range(0, total, step): + idx = np.arange(s0, min(total, s0 + step), dtype=np.int64) + X = np.ones((len(idx), n)) + for j in range(1, n): + X[:, j] = 1 - 2 * ((idx >> (j - 1)) & 1) + v = np.abs(X @ A.T).max(axis=1).min() + best = v if best is None else min(best, v) + num = int(round(best)) + return num / D, {"disc_numerator": num, "denominator": D, "rows": len(M), "cols": n} diff --git a/graders/tao_c26a_boolean_bohnenblust_hille/check.py b/graders/tao_c26a_boolean_bohnenblust_hille/check.py new file mode 100644 index 0000000000000000000000000000000000000000..477253d2c9cca792e5097d621b1805c7154152fe --- /dev/null +++ b/graders/tao_c26a_boolean_bohnenblust_hille/check.py @@ -0,0 +1,36 @@ +"""Tao et al. Optimization Constants C_26a (Bohnenblust-Hille constant on the Boolean cube): maximize +(sum_S |f^(S)|^p_d)^(1/p_d) / ||f||_inf with d = deg(f), p_d = 2d/(d+1). + +Answer: n and the integer truth table of f : {-1,1}^n -> Z (index x: bit i set <=> x_{i+1} = -1). +The Walsh-Fourier coefficients are computed exactly in integers (2^n f^(S), int64), so deg(f) and the support +are exact; ||f||_inf is exact; only the final p-norm is floating point. Using p_d with d = deg(f) is the +strongest form (p_d increases with d, so the l^{p_d} norm is largest for the smallest admissible d).""" +import numpy as np + +from run import Invalid, as_int, int_list + + +def check(inst, ans): + n = as_int(ans.get("n"), "n", 1, inst["max_n"]) + lim = inst["max_abs_value"] + vals = int_list(ans.get("values"), 1 << n, -lim, lim, "values") + f = np.array(vals, dtype=np.int64) + sup = int(np.abs(f).max()) + c = f.copy() + for i in range(n): # integer Walsh-Hadamard transform + c = c.reshape(-1, 2, 1 << i) + a, b = c[:, 0, :].copy(), c[:, 1, :].copy() + c[:, 0, :], c[:, 1, :] = a + b, a - b + c = c.reshape(-1) + idx = np.arange(1 << n) + pop = np.zeros(1 << n, dtype=np.int64) + for i in range(n): + pop += (idx >> i) & 1 + nz = c != 0 + deg = int(pop[nz].max()) if nz.any() else 0 + if deg < 1: + raise Invalid("f must be non-constant (degree >= 1)") + p = 2 * deg / (deg + 1) + coef = np.abs(c[nz].astype(np.float64)) / float(1 << n) + lp = float((coef ** p).sum() ** (1 / p)) + return lp / sup, {"n": n, "degree": deg, "p": p, "sup_norm": sup, "support": int(nz.sum())} diff --git a/graders/tao_c27b_biplanar_chromatic/check.py b/graders/tao_c27b_biplanar_chromatic/check.py new file mode 100644 index 0000000000000000000000000000000000000000..9f5ee59cc71828a298ed1a626bb4bbf45740d2ec --- /dev/null +++ b/graders/tao_c27b_biplanar_chromatic/check.py @@ -0,0 +1,85 @@ +"""Tao et al. Optimization Constants C_27b (max chromatic number of biplanar graphs; Earth-Moon problem). + +Answer: N vertices and two edge lists. Each layer must be planar (networkx.check_planarity, exact +combinatorial test); the score is a CERTIFIED lower bound on chi(G1 u G2): starting from the clique number, +k-colourability is refuted by exhaustive DSATUR backtracking (one node budget shared by all k) for k = omega, omega+1, ... until a k-colouring +is found (then chi = k exactly) or the node budget is exhausted (then the score is the last refuted k + 1). +The score never exceeds the true chromatic number.""" +import networkx as nx + +from run import Invalid, as_int, int_list + + +def _layer(v, N, name): + if not isinstance(v, list) or len(v) > 3 * N: + raise Invalid(f"{name} must be a list of at most 3N edges") + G = nx.Graph() + G.add_nodes_from(range(N)) + seen = set() + for e in v: + int_list(e, 2, 0, N - 1, f"{name} edge") + a, b = e + if a == b: + raise Invalid("self-loop") + key = (min(a, b), max(a, b)) + if key in seen: + raise Invalid(f"duplicate edge {key} in {name}") + seen.add(key) + G.add_edge(a, b) + if not nx.check_planarity(G)[0]: + raise Invalid(f"{name} is not planar") + return seen + + +def _colourable(adj, N, k, budget, nodes): + """True / False / None (budget exhausted). DSATUR-ordered exhaustive backtracking. + nodes = [count] is shared across calls, so the budget bounds the total work of one grading.""" + col = [-1] * N + + def rec(done): + if done == N: + return True + nodes[0] += 1 + if nodes[0] > budget: + return None + best, bsat, bdeg = -1, -1, -1 + for v in range(N): + if col[v] < 0: + used = {col[u] for u in adj[v] if col[u] >= 0} + s, d = len(used), len(adj[v]) + if s > bsat or (s == bsat and d > bdeg): + best, bsat, bdeg, bused = v, s, d, used + if bsat >= k: + return False + maxc = max(col) + 1 + for c in range(min(k, maxc + 1)): # symmetry breaking: at most one new colour + if c not in bused: + col[best] = c + r = rec(done + 1) + if r is not False: + return r + col[best] = -1 + return False + return rec(0) + + +def check(inst, ans): + N = as_int(ans.get("n"), "n", 1, inst["max_vertices"]) + E = _layer(ans.get("layer1"), N, "layer1") | _layer(ans.get("layer2"), N, "layer2") + G = nx.Graph() + G.add_nodes_from(range(N)) + G.add_edges_from(E) + adj = [set(G[v]) for v in range(N)] + omega = max(len(c) for c in nx.find_cliques(G)) + k = omega + status = "exact" + nodes = [0] + while True: + r = _colourable(adj, N, k, inst["node_budget"], nodes) + if r is True: + break + if r is None: + status = "budget_exhausted" + break + k += 1 + return k, {"n": N, "edges": len(E), "clique_number": omega, "chromatic_lower_bound": k, "status": status} diff --git a/graders/tao_c37a_degree_sensitivity/check.py b/graders/tao_c37a_degree_sensitivity/check.py new file mode 100644 index 0000000000000000000000000000000000000000..9f39230bb71555ca2f274db314846e30dee6e4e1 --- /dev/null +++ b/graders/tao_c37a_degree_sensitivity/check.py @@ -0,0 +1,33 @@ +"""Tao et al. Optimization Constants C_37 (degree-sensitivity exponent): maximize log s(f) / log deg(f). + +Answer: n (2..max_n) and the full truth table of f: {0,1}^n -> {0,1}, entry index x = sum_i x_i 2^(i-1). +deg(f) is computed exactly by the integer Moebius transform; s(f) exactly by flipping each bit.""" +import math + +import numpy as np + +from run import Invalid, as_int, int_list + + +def check(inst, ans): + n = as_int(ans.get("n"), "n", 2, inst["max_n"]) + tt = int_list(ans.get("truth_table"), 1 << n, 0, 1, "truth_table") + f = np.array(tt, dtype=np.int64) + c = f.copy() + idx = np.arange(1 << n) + for i in range(n): # Moebius transform: c_S = sum_{T subset S} (-1)^{|S-T|} f(T) + c = c.reshape(-1, 2, 1 << i) + c[:, 1, :] -= c[:, 0, :] + c = c.reshape(-1) + pop = np.zeros(1 << n, dtype=np.int64) + for i in range(n): + pop += (idx >> i) & 1 + nz = c != 0 + deg = int(pop[nz].max()) if nz.any() else 0 + if deg < 2: + raise Invalid(f"deg(f) must be at least 2 (got {deg})") + sens = np.zeros(1 << n, dtype=np.int64) + for i in range(n): + sens += f != f[idx ^ (1 << i)] + s = int(sens.max()) + return math.log(s) / math.log(deg), {"n": n, "degree": deg, "sensitivity": s} diff --git a/graders/tao_c40a_lehmer_mahler/check.py b/graders/tao_c40a_lehmer_mahler/check.py new file mode 100644 index 0000000000000000000000000000000000000000..d6841714266e0113e6136a983749a6e4c4fff16e --- /dev/null +++ b/graders/tao_c40a_lehmer_mahler/check.py @@ -0,0 +1,57 @@ +"""Tao et al. Optimization Constants C_40a (Lehmer's Mahler measure constant): minimize M(f) > 1. + +Answer: integer coefficients a_0..a_d (constant term first), 1 <= d <= max_degree. +Exactness: all x-factors and cyclotomic factors are divided out in exact integer arithmetic (they have +Mahler measure 1). If nothing but +-1 remains, M(f) = 1 (Kronecker) and the answer is invalid. Otherwise the +remaining part g has M(g) > 1 exactly (Kronecker), and M(f) = M(g) is evaluated from the roots of the +square-free factors of g (numpy eigenvalue roots, float objective).""" +import numpy as np +import sympy as sp + +from run import Invalid, int_list + +_X = sp.Symbol("x") + + +def _cyclo_orders(maxdeg): + return [m for m in range(1, 8 * maxdeg + 2) if sp.totient(m) <= maxdeg] + + +def check(inst, ans): + D, B = inst["max_degree"], inst["max_abs_coefficient"] + a = ans.get("coefficients") + if not isinstance(a, list) or not 2 <= len(a) <= D + 1: + raise Invalid(f"coefficients must be a list of length 2..{D + 1} (degree 1..{D})") + int_list(a, None, -B, B, "coefficients") + if a[-1] == 0: + raise Invalid("leading coefficient a_d must be non-zero") + while a[0] == 0: # strip powers of x (M(x) = 1) + a = a[1:] + g = sp.Poly(list(reversed(a)), _X, domain="ZZ") + removed = [] + for m in _cyclo_orders(D): + if g.degree() < sp.totient(m): + continue + phi = sp.Poly(sp.cyclotomic_poly(m, _X), _X, domain="ZZ") + while g.degree() >= phi.degree(): + q, r = g.div(phi) + if not r.is_zero: + break + g = q + removed.append(m) + if g.degree() == 0 and abs(int(g.LC())) == 1: + raise Invalid("f is a product of cyclotomic polynomials and x, so M(f) = 1") + M = 1.0 + content, factors = g.sqf_list() + M *= abs(int(content)) + for h, e in factors: + if h.degree() == 0: + M *= abs(int(h.LC())) ** e + continue + roots = np.roots([float(c) for c in h.all_coeffs()]) + mh = abs(float(h.LC())) * float(np.prod(np.maximum(1.0, np.abs(roots)))) + M *= mh ** e + if not np.isfinite(M) or M <= 1.0: + raise Invalid("numerical failure evaluating M(f)") + return M, {"degree": len(ans["coefficients"]) - 1, "cyclotomic_factors_removed": removed, + "noncyclotomic_degree": g.degree()} diff --git a/graders/tao_c49a_sunflower_free/check.py b/graders/tao_c49a_sunflower_free/check.py new file mode 100644 index 0000000000000000000000000000000000000000..b0e3452346c86236191a94145bdcc55660c9ff87 --- /dev/null +++ b/graders/tao_c49a_sunflower_free/check.py @@ -0,0 +1,68 @@ +"""Tao constant C49a (Erdos-Szemeredi 3-sunflower-free capacity), direct product certificate. + +A Sperner (antichain) 3-sunflower-free family F of subsets of [n] gives mu_3^S >= |F|^(1/n): the k-fold +product of F on k disjoint copies of [n] is again Sperner and sunflower-free, so f(kn) >= |F|^k. +Score = |F| (maximize), for the fixed n of the instance. + +Exact check. A triple {A, B, C} of distinct sets is a 3-sunflower iff C contains A&B and C misses A^B (then +C&A = C&B = A&B). For a Sperner family neither A nor B lies in that interval, so F is sunflower-free iff for +every pair A != B the interval [A&B, ~(A|B) | (A&B)] of the Boolean lattice contains no member of F. +Interval counts for all intervals are precomputed by a ternary zeta transform over 3^n states. +""" +import numpy as np + +from run import Invalid, int_list + + +def _masks(inst, ans): + n = inst["n"] + sets = ans.get("sets") + if not isinstance(sets, list) or not sets: + raise Invalid("sets must be a non-empty list") + if len(sets) > 2 ** n: + raise Invalid("too many sets") + masks = [] + for s in sets: + s = int_list(s, None, 0, n - 1, "set") + if len(set(s)) != len(s): + raise Invalid("a set lists an element twice") + m = 0 + for x in s: + m |= 1 << x + masks.append(m) + if len(set(masks)) != len(masks): + raise Invalid("duplicate sets") + return n, np.array(masks, dtype=np.int64) + + +def check(inst, ans): + n, M = _masks(inst, ans) + m = len(M) + full = (1 << n) - 1 + # ternary weight of a mask: sum_{i in mask} 3^i + tern = np.zeros(1 << n, dtype=np.int64) + for i in range(n): + tern[np.arange(1 << n) >> i & 1 == 1] += 3 ** i + # h[t] for ternary t (digit 0 = not in C, 1 = in C, 2 = free) = #{C in F consistent with t} + h = np.zeros(3 ** n, dtype=np.int32) + h[tern[M]] = 1 + h = h.reshape((3,) * n) # axis k <-> digit of 3^(n-1-k) + for ax in range(n): + idx0 = [slice(None)] * n + idx1 = [slice(None)] * n + idx2 = [slice(None)] * n + idx0[ax], idx1[ax], idx2[ax] = 0, 1, 2 + h[tuple(idx2)] = h[tuple(idx0)] + h[tuple(idx1)] + h = h.reshape(-1) + for i in range(m - 1): + A = M[i] + B = M[i + 1:] + inter = A & B + if np.any(inter == A) or np.any(inter == B): + raise Invalid("not Sperner: one set contains another") + idx = tern[inter] + 2 * tern[full & ~(A | B)] + bad = np.nonzero(h[idx] > 0)[0] + if len(bad): + j = i + 1 + int(bad[0]) + raise Invalid(f"3-sunflower through sets #{i} and #{j}") + return float(m), {"size": m, "mu_lower_bound": float(m) ** (1.0 / n)} diff --git a/graders/tao_c71a_fei_ratio/check.py b/graders/tao_c71a_fei_ratio/check.py new file mode 100644 index 0000000000000000000000000000000000000000..db47b311903899504d6a58af6328a0a55903aecc --- /dev/null +++ b/graders/tao_c71a_fei_ratio/check.py @@ -0,0 +1,56 @@ +"""Tao constant C71a (Fourier Entropy-Influence constant), lower bound via O'Donnell-Tan amplification. + +For a balanced f: {-1,1}^n -> {-1,1} (f-hat(empty) = 0) with total influence I > 1, the recursive self-composition +f^(d) has H = H(f)(I^d - 1)/(I - 1) and Inf = I^d, so C71 >= H(f)/(I(f) - 1). Score = H(f)/(I(f) - 1) (maximize). + +Answer: n (2..20) and the truth table as a hex string of 2^n / 4 digits (n >= 2). Expanding each hex digit into +4 bits, most significant bit first, gives a bit string b_0 b_1 ... b_{2^n - 1}; b_j is the value at the input whose +coordinate i (0-based) is bit i of j; b_j = 1 means f = -1, b_j = 0 means f = +1. +Walsh-Hadamard coefficients W(S) = 2^n f-hat(S) are computed exactly in int64; balance and I > 1 are checked +exactly; H is evaluated in float64 from the exact integers. +""" +import math +import re +from fractions import Fraction + +import numpy as np + +from run import Invalid, as_int + +HEX = re.compile(r"^[0-9a-fA-F]+$") + + +def check(inst, ans): + n = as_int(ans.get("n"), "n", 2, inst.get("max_n", 20)) + tt = ans.get("truth_table") + if not isinstance(tt, str) or len(tt) != (1 << n) // 4 or not HEX.match(tt): + raise Invalid(f"truth_table must be a hex string of exactly {(1 << n) // 4} digits") + nib = np.frombuffer(bytes.fromhex(tt if len(tt) % 2 == 0 else tt + "0"), dtype=np.uint8) + bits = np.unpackbits(nib)[: 1 << n].astype(np.int64) + f = 1 - 2 * bits # +1 / -1 + if int(f.sum()) != 0: + raise Invalid("f must be balanced (exactly half of the entries equal to 1)") + W = f.copy() + h = 1 + while h < len(W): # in-place integer fast Walsh-Hadamard transform + W = W.reshape(-1, 2, h) + a, b = W[:, 0, :].copy(), W[:, 1, :].copy() + W[:, 0, :], W[:, 1, :] = a + b, a - b + W = W.reshape(-1) + h *= 2 + W2 = W * W # = 4^n f-hat(S)^2, exact + pop = np.zeros(1 << n, dtype=np.int64) + for i in range(n): + pop += (np.arange(1 << n) >> i) & 1 + four_n = 1 << (2 * n) + assert int(W2.sum()) == four_n + infl = Fraction(int((W2 * pop).sum()), four_n) + if infl <= 1: + raise Invalid("total influence must exceed 1 (f is a dictator or anti-dictator)") + nz = W2[W2 > 0].astype(np.float64) + p = nz / float(four_n) + H = float(-(p * np.log2(p)).sum()) + score = H / float(infl - 1) + if not math.isfinite(score): + raise Invalid("non-finite score") + return score, {"entropy": H, "influence": float(infl), "influence_exact": str(infl)} diff --git a/graders/tao_c73a_hollow_lattice_width/check.py b/graders/tao_c73a_hollow_lattice_width/check.py new file mode 100644 index 0000000000000000000000000000000000000000..af2c5d7c40f59f1f0e0a23b06dc854e1e2742d1b --- /dev/null +++ b/graders/tao_c73a_hollow_lattice_width/check.py @@ -0,0 +1,137 @@ +"""Tao constant C73a (flatness constant Flt(3)), lower bound via an explicit hollow polytope. + +Answer: a common denominator D (1 <= D <= 10^6) and 4..16 integer points N_i in Z^3; the body is +K = conv(N_i / D). Requirements: K is 3-dimensional, every coordinate satisfies |N_ij / D| <= 50, and K is hollow: +no point of Z^3 lies in the interior of K. Score = lattice width w(K) = min over nonzero u in Z^3 of +(max_K u.x - min_K u.x) (maximize). Everything is exact integer arithmetic: + * facets = planes through 3 affinely independent input points with all input points on one side; + an integer point p is interior iff it is strictly inside every facet plane (scanned over all integer (x, y) + columns of the bounding box, with the admissible z-range computed exactly); + * width: W0 = min width over e1, e2, e3. Any u with width(u) <= W0 satisfies |u.d_j| <= W0 for three + linearly independent edge vectors d_j, which bounds u in an explicit box; all u in that box are evaluated. +""" +from fractions import Fraction +from itertools import combinations + +import numpy as np + +from run import Invalid, as_int, int_list + +MAXC = 50 +MAX_BOX = 1_000_000 + + +def _cross(a, b): + return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]) + + +def _dot(a, b): + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + + +def _sub(a, b): + return (a[0] - b[0], a[1] - b[1], a[2] - b[2]) + + +def _det(a, b, c): + return _dot(a, _cross(b, c)) + + +def _fdiv(a, b): # floor(a / b), b > 0 + return a // b + + +def check(inst, ans): + D = as_int(ans.get("denominator"), "denominator", 1, 10 ** 6) + pts = ans.get("points") + if not isinstance(pts, list) or not 4 <= len(pts) <= 16: + raise Invalid("points must be a list of 4..16 integer triples") + P = [tuple(int_list(p, 3, -MAXC * D, MAXC * D, "point")) for p in pts] + if len(set(P)) != len(P): + raise Invalid("duplicate points") + # facets (a, c) with a.x <= c for all points, a integer, at least one point strictly inside + facets = set() + full_dim = False + for i, j, k in combinations(range(len(P)), 3): + nrm = _cross(_sub(P[j], P[i]), _sub(P[k], P[i])) + if nrm == (0, 0, 0): + continue + c = _dot(nrm, P[i]) + vals = [_dot(nrm, q) - c for q in P] + if all(v <= 0 for v in vals): + pass + elif all(v >= 0 for v in vals): + nrm, c = (-nrm[0], -nrm[1], -nrm[2]), -c + else: + continue + if all(_dot(nrm, q) == c for q in P): + continue + full_dim = True + from math import gcd + g = gcd(gcd(abs(nrm[0]), abs(nrm[1])), gcd(abs(nrm[2]), abs(c))) + facets.add((nrm[0] // g, nrm[1] // g, nrm[2] // g, c // g)) + if not full_dim: + raise Invalid("the points are coplanar; K must be 3-dimensional") + facets = list(facets) + # hollowness: integer p is interior iff a.(D p) < c for every facet + lo = [min(q[t] for q in P) for t in range(3)] + hi = [max(q[t] for q in P) for t in range(3)] + xs = range(-(-lo[0] // D), hi[0] // D + 1) + ys = range(-(-lo[1] // D), hi[1] // D + 1) + for x in xs: + for y in ys: + zlo, zhi = None, None # need zlo < D z < zhi ... handled as strict rational bounds on z + ok = True + for a0, a1, a2, c in facets: + r = c - a0 * D * x - a1 * D * y # need a2 * D * z < r + if a2 == 0: + if r <= 0: + ok = False + break + elif a2 > 0: + b = Fraction(r, a2 * D) # z < b + zhi = b if zhi is None or b < zhi else zhi + else: + b = Fraction(r, a2 * D) # z > b + zlo = b if zlo is None or b > zlo else zlo + if not ok: + continue + # bounded body: both bounds exist + z = zlo.numerator // zlo.denominator + 1 # smallest integer > zlo + if z < zhi: + raise Invalid(f"not hollow: integer point ({x}, {y}, {z}) lies in the interior of K") + # lattice width (all widths are integers / D) + A = np.array(P, dtype=np.int64) + + def width(u): + v = [_dot(u, q) for q in P] + return max(v) - min(v) + + W0 = min(width((1, 0, 0)), width((0, 1, 0)), width((0, 0, 1))) + diffs = [_sub(q, P[0]) for q in P[1:]] + best = None + for a, b, c in combinations(diffs, 3): + d = abs(_det(a, b, c)) + if d and (best is None or d > best[0]): + best = (d, a, b, c) + _, a, b, c = best + # rows of M = (d_a, d_b, d_c); u = M^{-1} y with |y_j| <= W0 + det = _det(a, b, c) + adj_cols = [_cross(b, c), _cross(c, a), _cross(a, b)] # M^{-1} = [these as columns] / det + bound = [] + for t in range(3): + s = sum(abs(col[t]) for col in adj_cols) + bound.append(int(Fraction(W0 * s, abs(det)))) + cnt = (2 * bound[0] + 1) * (2 * bound[1] + 1) * (2 * bound[2] + 1) + if cnt > MAX_BOX: + raise Invalid("K is too elongated/sheared for the width search; apply a unimodular map first") + g = [np.arange(-bt, bt + 1, dtype=np.int64) for bt in bound] + U = np.stack(np.meshgrid(*g, indexing="ij"), -1).reshape(-1, 3) + U = U[np.any(U != 0, axis=1)] + V = U @ A.T + wid = V.max(axis=1) - V.min(axis=1) + wmin = int(wid.min()) + wmin = min(wmin, W0) + u = U[int(wid.argmin())].tolist() if wid.min() <= W0 else None + w = Fraction(wmin, D) + return float(w), {"lattice_width": str(w), "width_direction": u, "facets": len(facets)} diff --git a/graders/tao_c88a_admissible_tuple/check.py b/graders/tao_c88a_admissible_tuple/check.py new file mode 100644 index 0000000000000000000000000000000000000000..a90fed82fcdd909cb7aca526677d0862294514b0 --- /dev/null +++ b/graders/tao_c88a_admissible_tuple/check.py @@ -0,0 +1,29 @@ +"""Tao constant C88a (bounded prime gaps H_1): narrow admissible k-tuples. + +If DHL[k,2] holds (every admissible k-tuple has infinitely many translates containing two primes), then +H_1 <= diameter of any admissible k-tuple. Answer: k distinct integers; admissible iff for every prime p <= k the +residues h mod p miss at least one class (primes p > k can never be covered by k residues). Score = max - min +(minimize). Exact integer check. +""" +from run import Invalid, int_list + + +def _primes(n): + s = bytearray([1]) * (n + 1) + s[0:2] = b"\x00\x00" + for i in range(2, int(n ** 0.5) + 1): + if s[i]: + s[i * i::i] = bytearray(len(s[i * i::i])) + return [i for i in range(n + 1) if s[i]] + + +def check(inst, ans): + k = inst["k"] + h = int_list(ans.get("tuple"), k, -10 ** 7, 10 ** 7, "tuple") + if len(set(h)) != k: + raise Invalid("tuple entries must be distinct") + for p in _primes(k): + if len({x % p for x in h}) == p: + raise Invalid(f"not admissible: the tuple covers every residue class mod {p}") + d = max(h) - min(h) + return float(d), {"diameter": d} diff --git a/graders/tao_c90a_covering_min_modulus/check.py b/graders/tao_c90a_covering_min_modulus/check.py new file mode 100644 index 0000000000000000000000000000000000000000..c99121bd72482d82719a3a0f2a50ddfad964a944 --- /dev/null +++ b/graders/tao_c90a_covering_min_modulus/check.py @@ -0,0 +1,41 @@ +"""Tao constant C90a (maximum minimum modulus of a distinct covering system), lower bound. + +Answer: a list of congruences [a, n] with distinct moduli n >= 2, 0 <= a < n, at most 1000 congruences and +L = lcm(moduli) <= 10^8. They must cover Z, i.e. every residue mod L. Score = min modulus (maximize). +Exact check: a boolean array over Z/L, every class a mod n marks a, a+n, ..., (a + L - n). +""" +from math import gcd + +import numpy as np + +from run import Invalid, int_list + +MAX_L = 10 ** 8 +MAX_K = 1000 + + +def check(inst, ans): + cs = ans.get("congruences") + if not isinstance(cs, list) or not 1 <= len(cs) <= MAX_K: + raise Invalid(f"congruences must be a list of 1..{MAX_K} pairs [a, n]") + pairs = [] + L = 1 + for c in cs: + a, n = int_list(c, 2, None, None, "congruence") + if not 2 <= n <= MAX_L or not 0 <= a < n: + raise Invalid("each congruence [a, n] needs 2 <= n <= 10^8 and 0 <= a < n") + L = L // gcd(L, n) * n + if L > MAX_L: + raise Invalid("lcm of the moduli exceeds 10^8") + pairs.append((a, n)) + mods = [n for _, n in pairs] + if len(set(mods)) != len(mods): + raise Invalid("moduli must be distinct") + cov = np.zeros(L, dtype=bool) + for a, n in sorted(pairs, key=lambda t: t[1]): + cov[a::n] = True + if not cov.all(): + r = int(np.argmin(cov)) + raise Invalid(f"not a covering: the residue {r} mod {L} is uncovered") + m = min(mods) + return float(m), {"min_modulus": m, "lcm": L, "num_congruences": len(pairs)}