1.31

From The Algorithm Design Manual Solution Wiki
Jump to navigation Jump to search

What has to be checked
The rule “every possible draw of 6 numbers must share at least 3 numbers with one of my tickets” is equivalent to
    • every 3-element subset (triple) of {1,…,49} appears inside at least one ticket.
There are only C(49,3)=18 424 triples, so we can test coverage by seeing whether our tickets cover them all.

Testing a given ticket set (pseudo-Python)

from itertools import combinations def covered(ticket_set): triples=set(combinations(range(1,50),3)) # 18 424 triples for t in ticket_set: # each t is length-6 for tri in combinations(t,3): triples.discard(tri) # mark triple as covered if not triples: # early exit return True return False # some triple is still missing
Run covered(my_tickets); it returns True iff the tickets give complete Lotto coverage.

Building a “good” (small) ticket set
We face a classic set-cover problem. A fast heuristic is greedy search: repeatedly add the ticket that covers the largest number of still-uncovered triples.
Greedy + random sampling quickly reaches the optimum 163 tickets discovered by exhaustive research.
from itertools import combinations from random import sample NTRIES = 6000 # candidates tested each round numbers = range(1,50) triples = set(combinations(numbers,3)) tickets = [] while triples: best_ticket, best_gain = None, -1 for _ in range(NTRIES): # evaluate random tickets cand = tuple(sorted(sample(numbers,6))) gain = sum(1 for tri in combinations(cand,3) if tri in triples) if gain > best_gain: best_ticket, best_gain = cand, gain tickets.append(best_ticket) # keep the winner for tri in combinations(best_ticket,3): # delete its triples triples.discard(tri) print(len(tickets)) # ≈170; raise NTRIES to push toward 163
Improve the result by increasing NTRIES, seeding with hand-known good tickets, or adding local search (swap one or two numbers and keep the mutation if it covers more triples).

Using the triple-coverage test plus the greedy/random generator you can validate any proposed ticket list and automatically hunt for near-minimal Lotto systems.

Back to Chapter 1 .