"""Original corpus and exact scoring; MIT. Generated problem corpus: CC0-1.0.""" import itertools import json import random import re from pathlib import Path ROOT = Path(__file__).resolve().parent SEED = 20260912 def enumerate_optimum(items, capacity): best, winners = -1, [] for mask in itertools.product((0, 1), repeat=len(items)): chosen = [x for x, take in zip(items, mask) if take] if sum(x['weight'] for x in chosen) > capacity: continue value = sum(x['value'] for x in chosen) ids = [x['id'] for x in chosen] if value > best: best, winners = value, [ids] elif value == best: winners.append(ids) return best, winners def dp_optimum(items, capacity): dp = [0] * (capacity + 1) for item in items: for c in range(capacity, item['weight'] - 1, -1): dp[c] = max(dp[c], dp[c - item['weight']] + item['value']) return dp[capacity] def make_corpus(): rng = random.Random(SEED) families, attempts = [], 0 while len(families) < 4: attempts += 1 if attempts > 10000: raise RuntimeError('Corpus selection did not converge') items = [dict(id=chr(65+i), weight=rng.randint(2, 9), value=rng.randint(3, 24)) for i in range(6)] capacity = sum(x['weight'] for x in items) // 2 a, b = [enumerate_optimum(items, c) for c in (capacity, capacity+1)] if len(a[1]) != 1 or len(b[1]) != 1 or a[0] == b[0]: continue families.append((items, capacity)) cases = [] for family, (items, base) in enumerate(families, 1): for increment in (0, 1): capacity = base + increment optimum, sets = enumerate_optimum(items, capacity) assert optimum == dp_optimum(items, capacity) for lang in ('en', 'zh'): if lang == 'en': text = f'Select a subset of these six indivisible items. Each item may be selected at most once. Total weight must be at most {capacity}. Maximize total value.\nID | weight | value\n' tail = '\nExplain your calculation briefly, then give exactly one final line using this format (example only): FINAL_JSON: {"value": 12, "items": ["A", "C"]}. Report the maximum value and one optimal subset.' else: text = f'从以下六个不可分割的物品中选择一个子集。每个物品最多选一次,总重量不能超过{capacity}。请使总价值最大。\n编号 | 重量 | 价值\n' tail = '\n简要说明计算过程,然后严格用以下格式给出唯一的最终行(仅为格式示例):FINAL_JSON: {"value": 12, "items": ["A", "C"]}。报告最大价值和一个最优子集。' text += '\n'.join(f"{x['id']} | {x['weight']} | {x['value']}" for x in items) cases.append(dict(id=f'f{family}-c{increment}-{lang}', family=family, increment=increment, language=lang, items=items, capacity=capacity, optimum=optimum, optimal_sets=sets, prompt=text+tail)) return dict(seed=SEED, rejected_candidates=attempts-4, cases=cases) def score(case, text, thinking, truncated): result = dict(strict_correct=False, parsed=False, feasible=False, value_consistent=False, optimal=False, truncated=truncated) if thinking and '' not in text: return {**result, 'reason': 'no_final_channel'} final = text.rsplit('', 1)[-1] markers = list(re.finditer(r'(?m)^\s*FINAL_JSON:\s*', final)) if len(markers) != 1: return {**result, 'reason': 'missing_or_ambiguous_marker'} try: answer, end = json.JSONDecoder().raw_decode(final[markers[0].end():]) suffix = final[markers[0].end()+end:].strip() if suffix not in ('', '```'): raise ValueError('trailing content') if not isinstance(answer, dict) or set(answer) != {'value', 'items'}: raise ValueError('schema') ids = answer['items'] if type(answer['value']) is not int or not isinstance(ids, list) or not all(isinstance(x, str) for x in ids): raise ValueError('types') lookup = {x['id']:x for x in case['items']} if len(ids) != len(set(ids)) or not set(ids) <= set(lookup): raise ValueError('invalid or repeated ID') except (ValueError, TypeError) as exc: return {**result, 'reason': 'invalid_final_json: '+str(exc)} weight = sum(lookup[x]['weight'] for x in ids) value = sum(lookup[x]['value'] for x in ids) result.update(parsed=True, answer=answer, actual_weight=weight, actual_value=value, feasible=weight<=case['capacity'], value_consistent=value==answer['value'], optimal=value==case['optimum']) result['strict_correct'] = all(result[x] for x in ('feasible', 'value_consistent', 'optimal')) and not truncated result['reason'] = 'correct' if result['strict_correct'] else ('budget_exhausted' if truncated else 'incorrect_solution') return result if __name__ == '__main__': target = ROOT/'corpus.json' data = json.dumps(make_corpus(), ensure_ascii=False, indent=2)+'\n' if target.exists() and target.read_text(encoding='utf-8') != data: raise SystemExit('Existing corpus differs; refusing to overwrite') target.write_text(data, encoding='utf-8') print(f'{len(make_corpus()["cases"])} prompts written; enumeration agrees with independent DP')