Interactive companion · Chapter 2 · A deeper look at search and optimization

Problems and Algorithms Lab

Classify the problem before choosing an algorithm, then pick a search strategy, often a heuristic: a rule of thumb that finds good answers fast without promising the best.

Based on Chapter 2, “A deeper look at search and optimization,” in Alaa Khamis, Optimization Algorithms: AI techniques for design, planning, and control problems, Manning Publications, 2024 (ISBN 978-1633438835).

Min-conflicts repairing an 8-queen board.

Part 1 · Section 2.1

Classifying optimization problems

Figure 2.1 classifies problems by variables, objectives, constraints, linearity and time budget. Pick an example to see how it is classified.

Section 2.1 of the book explains each axis of Figure 2.1 with examples, and why classifying lets one model serve many problems.

Problem classifier

Examples from Chapters 1 and 2

Counting search spaces (Section 2.1.1)

Combinatorial solutions are sets, combinations or permutations. Use the counters to see how fast combinations, TSP tours (n!) and clustering partitions (equation 2.1) grow.

Section 2.1.1 of the book works through these counts, compares exact and approximate TSP algorithms, and explains P, NP and NP-hard problems.

Count it

Landscapes: unimodal, multimodal and deceptive (Listing 2.1)

A unimodal landscape has one optimum, a multimodal one has several, and a deceptive one hides the global minimum in a narrow valley (Figure 2.4). Click the map to start a search: the deterministic compass search repeats its path, while the stochastic searches change from run to run.

Listing 2.1 in the book builds these landscapes in Python; Section 2.2 explains why randomness helps escape local optima.

Search a landscape

Minimize: brighter is lower · click to start

Constraint satisfaction: the n-queen problem (Listings 2.2 and 2.3)

A constraint-satisfaction problem has no objective, only constraints: place n queens so no two share a row, column or diagonal. Click a square to move that column’s queen there, or let min-conflicts move an attacked queen to its least-attacked row.

Section 2.1.2 of the book repairs a 4-queen board by hand (Figure 2.5), shows why Listing 2.2 cycles for n = 6, and solves it with CP-SAT (Listing 2.3).

Place the queens

Constraints and Lagrange multipliers (Listings 2.4 and 2.5)

Splitting tickets between x in-person and y online sales under a package limit x + y = 10,000 is an equality-constrained problem. Move along the constraint line and watch the profit; the Lagrangian finds the peak analytically.

Section 2.1.3 of the book derives the profit model (equation 2.2) and solves the Lagrangian conditions with SymPy in Listing 2.5 (Figure 2.8).

Split 10,000 tickets

Linear programming: the animal feed mix (Listing 2.6)

When the objective and every constraint are linear, the problem is a linear program: here, the cheapest mix of corn, limestone and soybean meal that meets calcium, protein and fiber limits. Click inside the plot to test any mix, or jump to the optimum.

Section 2.1.4 of the book solves this feed mix with PuLP (Listing 2.6), explains why the optimum sits at a vertex, and introduces nonlinear and quadratic programs.

Find the cheapest feasible mix

feasible regionoptimumyour mix

Design, planning and control problems (Section 2.1.5)

Design problems run offline for quality, planning problems need answers in minutes, control problems in milliseconds. Paint the 50 voters below into 5 districts of 10 and see how the lines change who wins.

Section 2.1.5 of the book compares these time scales with real examples (Figure 2.12) and explains districting criteria and gerrymandering (Figure 2.13).

Draw the districts

Illustrative: 20 Shield and 30 Bell voters
Paint with district
Preset maps

Part 2 · Section 2.2

Classifying search and optimization algorithms

Local or global, deterministic or stochastic: the landscape lab above shows the difference, and the Treasure Hunting Mission turns each algorithm family into a way of searching an island.

Open the Treasure Hunting Mission

Section 2.2 of the book maps each algorithm family to the chapter that covers it and shows how randomness changes a search (Figure 2.16).

Part 3 · Section 2.3

Heuristics and metaheuristics

Heuristics are rules of thumb that find acceptable solutions in practical time without guarantees; metaheuristics guide them by balancing exploration and exploitation.

Bin packing (Figures 2.17 to 2.20, Listing 2.7)

Pack objects into bins of size 7

Lower bound = ⌈total / capacity⌉

Load a 4 × 8 container (Listing 2.7)

Objects 3×1, 3×3, 5×1, 4×2, 3×2

Section 2.3 of the book packs these objects by hand (Figures 2.17 to 2.20) and implements container loading in Listing 2.7.

Heuristic search strategies: the cargo bike again

Three ways to generate candidates for the cargo bike of Section 1.3.3, written as a bit string: construct one greedily, modify one by swapping items, or recombine two. Click the bits to edit the current solution.

Section 2.3 of the book links each strategy to the algorithms built on it (Table 2.3, Figure 2.21).

Build, modify, recombine

Part 4 · Section 2.4

Nature-inspired algorithms

Nature solves ill-structured, dynamic, multimodal problems without global information, and many algorithms mimic how it does so.

Section 2.4 of the book maps each source of inspiration, from physics to neuroscience, to the algorithms in later chapters.

Part 5 · Code

Python in Google Colab

Open the book’s Chapter 2 notebooks in Colab, or the companion notebook with the from-scratch code below.

Notebooks

From-scratch implementations

# Counting search spaces (Section 2.1.1)
import math

# Fitness plan: choose r = 3 of n = 5 exercises
n, r = 5, 3
print("combinations with repetition:   ", math.comb(n + r - 1, r))       # 35
print("combinations without repetition:", math.comb(n, r))               # 10, "5 choose 3"
print("permutations with repetition:   ", n ** r)                        # 125
print("permutations without repetition:", math.perm(n, r))               # 60

# Traveling salesman problem: brute force vs. dynamic programming (Bellman-Held-Karp)
for cities in (5, 10, 13, 20):
    print(f"{cities:2d} cities: {math.factorial(cities):.3e} tours (ATSP), "
          f"{math.factorial(cities - 1) // 2:.3e} distinct symmetric tours, Held-Karp ~ {2 ** cities * cities ** 2:.3e} steps")


def stirling2(n, k):
    """Stirling number of the second kind: ways to partition n objects into k non-empty groups (equation 2.1)."""
    return sum((-1) ** i * math.comb(k, i) * (k - i) ** n for i in range(k + 1)) // math.factorial(k)


# Smart cart clustering: n carts around k assembly points
print(f"S(50, 4) = {stirling2(50, 4):.2e}")                              # 5.3e28
print(f"S(100, 4) = {stirling2(100, 4):.2e}")                            # 6.7e58

To run: open the companion notebook in Colab and press Shift+Enter in each cell, or paste a tab’s code into any notebook.

Part 6 · Summary

What to remember

Classify the problem

Its variables, objectives, constraints and time budget guide the algorithm choice.

Search spaces explode

They grow so fast that exhaustive search soon becomes impossible.

Classify the algorithm

Local or global, deterministic or stochastic: each fits different problems.

Heuristics

Rules of thumb find good solutions fast, without guarantees.

References: M. Held and R. M. Karp, “A dynamic programming approach to sequencing problems,” 1962. N. Christofides, “Worst-case analysis of a new heuristic for the travelling salesman problem,” 1976. P. A. Jensen and J. F. Bard, Operations Research Models and Methods, 2003. A. Khamis, Optimization Algorithms: AI techniques for design, planning, and control problems, Manning, 2024, Chapter 2.

Part 7 · Quiz

Check your understanding

Two quick questions on Chapter 2. Pick an answer to check it.

Q1. You start two searches from the same point on a multimodal landscape, twice each: a deterministic compass search and a stochastic search. What should you expect?

Q2. In the animal feed mix linear program, why does the cheapest feasible mix sit at a vertex of the feasible region?

For more exercises with full solutions, see Appendix C, “Exercises and solutions,” in Optimization Algorithms. The coding solutions are also on GitHub (Chapter 2).