OCR H446, section 2.2.2 (f)
This point asks you to apply six methods to solve problems. For each, you need to know what it is, when it suits a problem, and how it works.
1. Backtracking
Backtracking solves a problem by building a solution one step at a time. When a step leads to a dead end (a choice that can't work), it undoes it (backtracks) and tries another choice.
- Uses recursion or a stack.
- Suits puzzles and searches with constraints: mazes, Sudoku, the eight queens, finding a route.
- It doesn't try complete bad solutions: a bad partial choice is abandoned early (this is called pruning).
- Depth-first traversal of a tree or graph (2.3.1) backtracks too: at a node with no unvisited children, it goes back to the previous node, and keeps going back until it reaches a node that still has unvisited children.
Example: maze. At each junction, try a direction. If it's a dead end, return to the last junction and try another.
def solve(maze, x, y, path):
if maze[y][x] == "E": # reached the exit
return True
if maze[y][x] != " " or (x, y) in path:
return False # wall or already visited
path.append((x, y)) # make a choice
for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
if solve(maze, x + dx, y + dy, path):
return True
path.pop() # dead end: BACKTRACK
return False
Compared with brute force: it is much faster in practice because it cuts off whole branches, but its worst case can still be very slow.
2. Data mining
Data mining is analysing very large data sets to find patterns, trends and relationships that aren't obvious: it turns large quantities of data into useful information.
- Uses statistics and algorithms (clustering, classification, association rules).
- Suits big data where manual analysis is impossible.
- Examples:
- A supermarket finds that people who buy pasta often also buy pasta sauce (association), so it places them together or offers a deal.
- A bank spots unusual transactions that suggest fraud.
- A streaming service recommends programmes.
- A hospital finds risk factors for a disease.
- Issues: privacy and consent, bias in the data, and spurious patterns (a pattern may be coincidence).
3. Heuristics
A heuristic is a rule of thumb or shortcut that finds a good, but not guaranteed best, solution quickly. It trades accuracy for speed.
- Used when the exact solution is too slow (an intractable problem, 2.2.2 (a)) or no exact method exists.
- Examples:
- Nearest neighbour for the travelling salesman: always go to the closest unvisited place.
- A* search uses a heuristic estimate of the distance remaining to guide the search.
- A virus scanner flags files that look like malware (heuristic detection).
- A chess program scores positions with a rule such as "pieces are worth points".
- A spam filter looks for words common in spam.
- Advantages: fast and practical for hard problems. Disadvantages: the answer may not be the best, and it can give false positives or negatives.
4. Performance modelling
Performance modelling uses a simulation or mathematical model to predict how a system will perform under different conditions, without building or testing the real thing.
- Used to test speed, capacity, cost and safety.
- Examples:
- How many users a website can handle before it slows down, by simulating increasing numbers of visitors.
- Wind tunnel or crash-test simulation of a new car.
- Traffic flow models to plan road changes.
- Testing a network design for bottlenecks.
- Stress testing a processor design.
- Advantages: cheaper, safer and quicker than real tests, and you can try extreme or dangerous situations, and change one factor at a time.
- Disadvantages: the model is an abstraction (2.1.1 (c)), so results are only as good as its assumptions and data, and it needs validation against real data.
5. Pipelining
Pipelining is splitting a task into stages, so that several items are in different stages at the same time, like an assembly line. As one item moves to the next stage, the next item enters the first.
- Famous in the processor: while one instruction is being executed, the next is being decoded and the one after is being fetched (1.1.1 (c)).
- Also used in graphics (GPU) pipelines, data processing and Unix command pipes.
Without pipelining, three instructions of three stages take 9 time units. With it, they take 5.
- Benefit: higher throughput, with the hardware kept busy.
- Problem: a branch can mean the instructions already in the pipeline are the wrong ones and must be discarded, and a stage that depends on the result of the previous instruction has to wait (a hazard).
# a pipeline of steps in a program: each output feeds the next
lines = read_file("log.txt")
errors = filter(is_error, lines)
messages = map(clean, errors)
report(messages)
6. Visualisation
Visualisation is presenting data or the working of a system in a visual form (graphs, charts, maps, diagrams, animations) so that patterns and meaning are easier to see and understand.
- Examples:
- A line chart of sales over time shows trends.
- A heat map of website clicks.
- A map coloured by population density.
- Animating how a sorting algorithm moves items.
- A network diagram of social connections.
- Dashboards for monitoring a system.
- Benefits: people understand pictures faster than tables of numbers, and can spot outliers and trends, and communicate results.
- Risks: a misleading scale or chart type can distort the message.
Choosing a method
| Situation | Method |
|---|---|
| A search with choices and constraints, where bad choices can be undone | Backtracking |
| Huge data sets, with hidden patterns wanted | Data mining |
| The best answer is too slow to find | Heuristics |
| Predict the behaviour of a system without building it | Performance modelling |
| A process can be split into stages that overlap | Pipelining |
| Make complex data understandable | Visualisation |
Worked example
Task: a council wants to plan bin-collection rounds for 200 streets, to minimise the distance driven.
- Recognition: it's a vehicle routing problem, a version of the travelling salesman problem, which is intractable for 200 stops, so it can't be solved exactly in reasonable time.
- Heuristic: use nearest neighbour to build a good route quickly, then improve it. The answer isn't guaranteed best, but is good enough.
- Data mining: analyse past collection data to find which streets have more waste, and when, so the rounds fit the pattern.
- Performance modelling: simulate the new rounds with different numbers of lorries to predict fuel costs and times before changing real services.
- Visualisation: show the routes on a map, with heavy-waste streets in a darker colour, so that councillors can see the proposal.
Exam tip: for each method, say what it does and why it suits the scenario. Know the key trade-off of each: heuristics give a quick but possibly non-optimal answer; performance models are only as good as their assumptions; pipelining can be disrupted by branches; backtracking uses recursion and abandons dead ends.
Check yourself
What does backtracking do when it reaches a dead end?
It undoes the last choice(s) and tries a different alternative, instead of continuing along a path that cannot succeed.
What is data mining?
Analysing very large data sets to find patterns, trends and relationships that aren't obvious.
What is a heuristic, and what is the trade-off?
A rule of thumb that finds a good solution quickly. The trade-off is that the solution isn't guaranteed to be the best.
Give two advantages of performance modelling
Any two of: cheaper and safer than building the real thing; quicker; extreme situations can be tested; one factor can be changed at a time.
How does pipelining speed up a processor?
It overlaps the stages of different instructions, so that while one is being executed the next is being decoded and the one after is fetched, which increases throughput.
Why is visualisation useful?
It presents data in a visual form so that patterns, trends and outliers are easier to see and understand than in tables of numbers.