liveBook · Manning

Brute-force search

As explained in Classic Computer Science Problems in Swift: Essential techniques for practicing programmers

Brute-force search systematically examines many or all possible candidates until a valid solution is found.

Brute-force search tests many or all possible candidates until it finds a valid solution. It is straightforward to implement, but the candidate space can grow too quickly for larger problems. section 8.2 section 3.5

A practical brute-force solution usually follows these steps:

  • Represent the input and candidate choices in searchable structures, such as city arrays and distance dictionaries. section 8.2
  • Generate candidates, often with recursion and backtracking; permutation generation swaps elements, recurses, and restores the previous arrangement. section 8.2
  • Validate each candidate, rejecting duplicate assignments or incomplete paths and retaining the best valid result. section 8.2 section 3.5

Traveling salesman problem

For five Vermont cities, generate every city permutation, append its starting city to close the route, total the pairwise distances, and keep the shortest path. The implementation finds a 318-mile route. The same exhaustive pattern solves SEND+MORE=MONEY by trying digit assignments, enforcing distinct digits, and checking the equation when all letters are assigned. section 8.2 section 3.5

Table 8.2. Driving distances between cities in Vermont
 

Rutland

Burlington

White River Junction

Bennington

Brattleboro

Rutland 0 67 46 55 75
Burlington 67 0 91 122 153
White River Junction 46 91 0 98 65
Bennington 55 122 98 0 40
Brattleboro 75 153 65 40 0

Use the distance table to trace candidate routes and understand how each path receives its total. section 8.2

How Classic Computer Science Problems in Swift: Essential techniques for practicing programmers covers it

How deep it goes
Explains candidate representation, recursive permutation generation, backtracking, validation, and result selection, while showing poor scalability.
Examples
Uses a five-city traveling salesman instance and the SEND+MORE=MONEY cryptarithmetic puzzle.
What it assumes
Assumes basic Swift functions, arrays, dictionaries, recursion, and collection operations while modeling constraints explicitly.
What you can do after
Build it from scratch in Swift by generating permutations, evaluating routes, and enforcing puzzle constraints.
How it connects
Connects to permutations, backtracking search, constraint satisfaction problems, breadth-first search, depth-first search, and path-finding algorithms.

Also explained in

Compare how 7 books explain brute-force search →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Classic Computer Science Problems in Swift: Essential techniques for practicing programmers. The section links point to the parts of the book it draws on.