A Level Computer Science · Chapter 23 · Component 02: Algorithms and programming
Good programs come from good tools, careful testing and the right method, from an IDE that finds bugs to backtracking and heuristics for hard problems.
This chapter teaches how programmers develop and debug code in an integrated development environment, and how they choose test data and test strategies that find bugs. It then teaches the computational methods used to attack hard problems, from divide and conquer and backtracking to heuristics, data mining, performance modelling, pipelining and visualisation.
In this chapter · jump to a section
Start here
Your route through this chapter
By the end of this chapter you will be able to:
- describe the features of an IDE that help a programmer write, run and debug code
- choose normal, boundary and erroneous test data for a program and state the expected results
- explain black-box, white-box, unit, integration, alpha, beta and acceptance testing
- explain which problems can be solved by computational methods, and use problem recognition, decomposition and divide and conquer
- explain backtracking and heuristics, and compare a heuristic's answer with the best answer
- explain data mining, performance modelling, pipelining and visualisation, and calculate support, confidence and run times
Time: three sessions, about 4 hours, plus the programming task.
You need first: the habits of Computational thinking, and the algorithms of Searching and sorting algorithms.
The big picture
The big picture
Writing a program is only part of the job. Almost every program contains mistakes when it is first written, and finding them takes longer than writing the code. Professional programmers use powerful tools to find bugs, and they test their programs in planned, systematic ways. A bug that reaches the users costs far more to fix than one caught early.
The first tool is the integrated development environment, or IDE. It brings together an editor, a translator, a way to run the program and a debugger. It points out mistakes as you type, lets you pause a running program and look inside it, and shows you exactly where an error happened. Learning to use these features well is one of the quickest ways to become a better programmer.
The second tool is testing. A test runs the program with chosen inputs and compares what happens with what should happen. The skill lies in choosing the inputs. A handful of well-chosen tests, especially at the edges of the allowed values, finds far more bugs than hundreds of random ones. Testing can show that bugs exist, but it can never prove that there are none.
The rest of the chapter is about harder problems. Some problems are easy to state but very hard to solve, because the number of possible answers is enormous. Planning the shortest route through 20 towns has more possible routes than there are grains of sand on Earth. Computer scientists have developed general methods for such problems. They break them into smaller ones, search cleverly and abandon dead ends, and accept a good answer when the best is out of reach.
These methods are not tied to one language or one kind of program. Divide and conquer appears in binary search, merge sort and the fast multiplication of huge numbers. Backtracking solves puzzles, timetables and route problems. Heuristics guide sat-navs, games and delivery firms. Data mining finds patterns in shopping records and medical data. Recognising which method fits a problem is often the key step towards solving it.
The two halves of the chapter are linked. A heuristic must be tested to see how far its answers fall from the best ones. A backtracking program must be debugged, which is hard because its recursion runs deep. A performance model predicts how long a program will take before it is run on real data. Good tools and good methods go together.
Section 1
Development environments
What an IDE provides
An integrated development environment is a single program that provides the tools needed to write, translate, run and debug code. Well-known IDEs include Visual Studio Code, PyCharm and IDLE, which comes with Python. Their features fall into two groups: those that help you write code, and those that help you find and fix its errors.
Editing features make code easier to write and read. Syntax highlighting colours keywords, strings and comments differently, so mistakes such as an unclosed string stand out. Automatic indentation keeps blocks lined up. Code completion suggests the names of variables and subroutines as you type, which saves time and avoids spelling mistakes. Line numbers let error messages point to an exact place.
Kinds of error
A syntax error breaks the rules of the language, such as a missing bracket or a misspelt keyword. The translator cannot understand the code, so the program will not run at all. An IDE usually marks syntax errors as you type, with a line number and a message, so they are the easiest kind to fix.
A runtime error happens while the program is running, such as dividing by zero or reading past the end of an array. The program stops and reports the error. A logic error is the hardest kind: the program runs to the end without complaint but gives the wrong answer, because the algorithm itself is wrong. Only testing finds logic errors.
Common mistake: thinking a program that compiles without errors is correct. A translator checks only that the code follows the language's rules. A program with a wrong condition or a wrong formula translates and runs perfectly well, and gives the wrong answer every time.
Debugging tools
A breakpoint pauses the program when it reaches a chosen line. The programmer can then look at the value of every variable at that moment. Stepping runs the program one line at a time from a breakpoint, so the programmer can see exactly which path it takes through each decision and loop. A watch window keeps chosen variables on screen and updates them at every step.
These tools let a programmer test a theory about a bug. If the average of some marks comes out too low, a breakpoint inside the loop shows whether the total is being built correctly. Stepping through one pass after another shows the exact line where the value first goes wrong. That is far quicker than adding print statements and running the program again and again.
Worked example 1: finding a logic error with a watch
A loop should add the marks 6, 8 and 10 and print their average, 8. It prints 4.67. A watch on total and count shows the values below. Find the bug.
| Working | Reason |
|---|---|
| After pass 1: total 0, count 1 | The first mark has not been added |
| After pass 2: total 6, count 2 | The total lags one mark behind the count |
| After pass 3: total 14, count 3 | The last mark, 10, is never added |
| 14 ÷ 3 = 4.67, the wrong average printed | The output matches what the watch shows |
| Bug: the loop adds the previous mark, not the current one | Fix the index used inside the loop |
Worked example 2: classifying errors
Classify each fault: a missing closing bracket; a division by a count that is 0; a loop that stops one item early.
| Working | Reason |
|---|---|
| Missing bracket: syntax error | The code breaks the rules of the language |
| Dividing by a count of 0: runtime error | The program stops when the division happens |
| Stopping one item early: logic error | The program runs but gives a wrong answer |
| Only the logic error needs testing to find | The other two are reported automatically |
A debugging strategy
Debugging works best as a method rather than guesswork. First, reproduce the bug: find an input that always makes it happen. Then narrow down where it happens, by setting a breakpoint halfway through the suspect code and checking whether the values are still right there. Each check halves the code that could contain the bug, just as binary search halves a list.
Once the faulty line is found, fix the cause, not just the symptom. A loop that adds one item too many should be corrected at its condition, not by subtracting the extra item afterwards. Finally, rerun every earlier test, to check that the fix has not broken anything else.
The runtime environment
An IDE also provides a runtime environment: a safe place to run the program and see its output and errors. Many IDEs include a console for typing commands, tools for running tests automatically and links to version control, which keeps every saved version of the code. With version control, a change that breaks the program can be undone, and a team can work on the same files without overwriting each other's work.
Check yourself. A program runs without crashing but always prints the total as zero. What kind of error is this, and which IDE tool would you use first?
Show the answer
It is a logic error, because the program runs but gives the wrong answer. A breakpoint inside the loop, with a watch on the total, shows whether the total is ever being added to.
Section 2
Test data
Normal, boundary and erroneous data
Test data is chosen to check that a program does what it should with every kind of input. Normal data is typical data the program should accept, such as a mark of 50 out of 100. Boundary data lies at the edges of the allowed range, such as 0 and 100. Erroneous data should be rejected, such as −1, 101 or the word "fifty".
Boundary data matters because many bugs live at the edges. A programmer who means "up to and including 100" may type < 100 instead of <= 100. The program then accepts 99 and rejects 100. Normal data such as 50 passes either way, so only a test at the boundary finds the bug. Testing just outside the boundary, at −1 and 101, checks that the edges are not too generous either.
Figure 23.1 tests a range check for an exam mark. Move the test value across the range, then switch on the wrong model to compare the buggy check with the correct one.
Boundary testing a range check
- Kind of test data
- boundary
- Correct check
- accepts
- Expected result
- accepted
Common mistake: thinking a program that passes its normal tests is correct. Normal data exercises the middle of the range, where almost every version of a check gives the same answer. Bugs in a condition show up at its boundaries, so a test plan without boundary data misses them.
Worked example 3: choosing test data
A program accepts the number of tickets in one order, from 1 to 10. Choose test data and state the expected result for each value.
| Working | Reason |
|---|---|
| Normal: 5, expected to be accepted | A typical order in the middle |
| Boundary: 1 and 10, both expected to be accepted | The smallest and largest allowed orders |
| Just outside: 0 and 11, both expected to be rejected | Check that the edges are not too generous |
| Erroneous: "two", expected to be rejected with a message | Data of the wrong type must not crash it |
| Test values: 0, 1, 10, 11 at the edges | Each side of each boundary is checked |
Worked example 4: finding an off-by-one bug
A check for marks from 0 to 100 was typed as mark >= 0 AND mark < 100. Which test values expose the bug?
| Working | Reason |
|---|---|
| Mark 50: both checks accept it | Normal data cannot tell them apart |
| Mark 0: both accept it; mark −1: both reject it | The lower boundary is written correctly |
| Mark 100: the buggy check rejects it | Its top boundary uses < instead of <= |
| Mark 101: both reject it | Just outside the range, they agree again |
| So only the boundary value 100 exposes the bug | Boundary tests are the ones that find it |
Test plans
A test plan lists every test before testing starts. For each test it gives a number, the purpose of the test, the input, the kind of data and the expected result. When the tests are run, the actual result is recorded next to the expected one. Any difference is a bug to investigate and fix, after which the tests are run again.
Writing the plan before the code is written has a big advantage. The expected results come from the requirements, not from whatever the program happens to do. A programmer who works out the expected result after running the code is tempted to accept a wrong answer as right.
Running the tests again after every fix is called regression testing. A fix in one place can break something elsewhere, especially in a large program. Keeping the tests as code, so that a single command reruns them all, makes regression testing quick enough to do every time. Many teams run their whole test suite automatically whenever someone saves a change.
Check yourself. A program accepts a password between 8 and 20 characters long. List four boundary lengths to test and the expected result for each.
Show the answer
Test lengths of 7 and 21, which should be rejected, and 8 and 20, which should be accepted. Together they check both sides of both boundaries of the allowed length.
Section 3
Testing strategies
Why testing needs a strategy
No program can be tested with every possible input. A function that takes two whole numbers has billions of possible input pairs. So testing must be planned: each test should check something different, and together the tests should cover every requirement and every part of the code. A testing strategy decides what to test, who tests it and when.
Black-box and white-box testing
Black-box testing treats the program as a box whose inside cannot be seen. The tester chooses inputs from the requirements and checks the outputs, without looking at the code. This is how users experience the program, and it can be done by people who cannot program. It tests whether the program does what it should.
White-box testing uses knowledge of the code. The tester chooses inputs so that every line, every branch of every decision and every loop is exercised at least once. This tests how the program does what it does, and can find code that is never reached or a branch that is never tested. It needs someone who can read the code.
The two approaches find different bugs, so good testing uses both. Black-box tests find missing features and misunderstood requirements, which white-box tests cannot see. White-box tests find branches that black-box tests happen to miss, such as a rarely used error message.
Stages of testing
Testing happens in stages as a program is built. Unit testing checks each subroutine on its own. Integration testing checks that units work together when they are joined. System testing checks the whole program against the requirements. Each stage finds bugs that the stage before could not.
Alpha testing is done inside the company that wrote the program, often by testers who were not its programmers. Beta testing gives a nearly finished version to a group of real users outside the company, who use it in real conditions and report problems. Acceptance testing is done by the client, to confirm that the program meets the agreed requirements before they accept and pay for it.
Common mistake: thinking testing can prove a program has no bugs. Testing can only show that bugs are present. A program with even a few decisions has too many paths to test them all. So a passing test plan shows that the tested cases work, not that every case does.
Worked example 5: white-box path coverage
A function contains three separate IF ... ELSE decisions in sequence. How many tests are needed to cover every path, and how many to cover every branch?
| Working | Reason |
|---|---|
| Every path: 2³ = 8 tests | Each decision doubles the number of paths |
| Every branch: each decision true once and false once | Branch coverage tests each outcome, not each combination |
| Two tests can do it: all true, then all false | Each test covers one outcome of every decision |
| So branch coverage needs 2 tests; path coverage needs 8 | Full path coverage grows far faster |
Worked example 6: choosing a strategy
A games company has finished a new game. Its programmers have tested every function. Which testing should come next, and who should do it?
| Working | Reason |
|---|---|
| Integration testing, by the programmers | Check that the tested functions work together |
| Alpha testing, by the company's own testers | Find bugs before anyone outside sees the game |
| Beta testing, by a group of real players | Real players use it in unexpected ways |
| Fix the reported bugs, then rerun the earlier tests | A fix can break something that worked |
Some teams write their tests before the code, an approach called test-driven development. Each test describes one small piece of required behaviour and fails at first, because the code does not exist yet. The programmer then writes just enough code to make it pass. The finished program arrives with a full set of tests that run in seconds.
Beta testing is especially valuable for games and apps, because real users run them on thousands of different devices, in ways the programmers never imagined. But beta testers report problems informally, so the company still needs its own planned tests. The final check, acceptance testing, matters most when a program has been written for one particular client who must confirm it does what they asked for.
Check yourself. Explain the difference between alpha testing and beta testing.
Show the answer
Alpha testing is done inside the developing company, often by its own testers. Beta testing gives a nearly finished version to real users outside the company, who use it in real conditions and report problems.
Section 4
Solving problems computationally
Which problems can computers solve?
Not every problem can be solved by a computer. A problem can be solved by computational methods if it can be stated precisely and its inputs and outputs can be held as data. There must also be an algorithm that produces the answer. "Which route is shortest?" fits. "Which painting is most beautiful?" does not, because beauty cannot be measured precisely.
Even a solvable problem may be impossible in practice. A problem is tractable if it can be solved in a reasonable time as it grows, usually with an algorithm whose time grows as a polynomial such as n². It is intractable if every known algorithm needs time that grows exponentially or faster. Some problems, such as deciding whether any program will eventually stop, cannot be solved by any algorithm at all.
Common mistake: thinking any problem can be solved by a computer if it is given enough time. Some problems have no algorithm at all, and others need so much time that no computer could finish them before the Sun burns out. For those, a good answer found quickly is the realistic goal.
Features of a computable problem
Before choosing a method, it helps to ask what the problem needs. Can its inputs be measured and stored? Is there a clear test for a correct answer? How large will the inputs grow? A school timetable has clear inputs, such as teachers, rooms and lessons, and a clear test: no clashes. But the number of possible timetables is vast, so the method must be chosen with care.
Some problems can be made computable by changing the question. "Which film will a viewer enjoy?" cannot be answered exactly. "Which films did viewers with similar tastes rate highly?" can be, using data. Much of modern computing works by replacing a vague question with a precise one that is close enough to be useful.
Problem recognition
Problem recognition means seeing that a new problem is really an example of one that has already been solved. Planning a delivery route, routing network packets and finding a path for a game character are all the shortest-path problem. Once the problem is recognised, a known algorithm, such as Dijkstra's or A*, can be used instead of inventing a new one.
Decomposition and abstraction
Decomposition breaks a big problem into smaller ones that can be solved separately, as in a structure diagram. Abstraction removes the detail that does not matter. Together they turn a huge, vague problem into a set of small, precise ones. Both were taught in Computational thinking; here they are tools for finding a method, not just for planning code.
Divide and conquer
Divide and conquer is a particular kind of decomposition. The problem is split into smaller problems of the same kind, each is solved, usually by the same method, and the answers are combined. Binary search divides a sorted list in half at each step and searches only one half. Merge sort divides a list in half, sorts each half and merges the two sorted halves.
The power of divide and conquer comes from halving. A list of a million items can be halved only about 20 times before one item is left. So binary search needs at most 20 comparisons, where linear search might need a million. Merge sort has about log₂ n levels, each doing about n work, so it takes about n log₂ n steps rather than bubble sort's n².
Problem recognition also saves effort in a less obvious way. Once a problem is known to be intractable, nobody needs to waste time looking for a fast exact algorithm. The effort can go into a heuristic instead. Or the problem can be made smaller, for example by splitting a big delivery area into zones that are each small enough to solve exactly.
Derivation: why halving takes about log₂ n steps
Each comparison in binary search halves the number of items left. After k comparisons, n items have been cut down to
The search must end by the time one item is left. Setting n ÷ 2ᵏ equal to 1 and taking logarithms to base 2 gives
Because k must be a whole number, the worst case is the next whole number above log₂ n, which is ⌊log₂ n⌋ + 1 comparisons. For a million items that is 20.
Worked example 7: halving a million
A sorted list holds 1,000,000 names. What is the largest number of comparisons binary search needs?
| Working | Reason |
|---|---|
| Each comparison halves the part left to search | The method discards half every time |
| 2¹⁹ = 524,288 and 2²⁰ = 1,048,576 | The million lies between these powers of two |
| So at most 20 comparisons are needed | Twenty halvings leave a single item |
| Linear search might need 1,000,000 | It checks the names one at a time |
Worked example 8: is it tractable?
A van must visit n towns once each and return. Checking every route takes (n − 1)! ÷ 2 routes. Compare 6 towns with 20.
| Working | Reason |
|---|---|
| 6 towns: 5! ÷ 2 = 60 routes | Few enough to check every one |
| 20 towns: 19! ÷ 2, about 6 × 10¹⁶ routes | The factorial grows faster than any power |
| At a billion routes a second, about two years | Far too slow for a daily delivery plan |
| So for many towns, an exact search is impractical | A faster method that gives a good answer is needed |
Check yourself. Give two examples of problems that can be solved by divide and conquer.
Show the answer
Binary search halves a sorted list and searches one half. Merge sort halves a list, sorts each half and merges them. Both split the problem into smaller problems of the same kind.
Section 5
Backtracking and heuristics
Backtracking
Backtracking builds a solution one step at a time. At each step it tries an option. If the partial solution can still lead to an answer, it moves on to the next step. If it cannot, it undoes the last step, goes back and tries the next option. Like someone in a maze, it follows a path until it hits a dead end, then returns to the last junction and tries another way.
The classic example is placing n queens on an n × n chessboard so that no two attack each other. Backtracking places one queen in each row, trying each column in turn. As soon as a queen is attacked, that column is abandoned. If no column in a row works, the algorithm goes back and moves the queen in the row above.
Backtracking saves enormous amounts of work because it abandons a whole family of partial solutions at once. When the third queen is attacked, every board that starts with those three queens is ruled out without being built. Brute force, by contrast, would build each complete board and only then check it. Backtracking is naturally written with recursion, where each call places one queen.
Worked example 9: backtracking against brute force
Compare the work done by backtracking and by brute force to find every solution for four queens.
| Working | Reason |
|---|---|
| Brute force: 4⁴ = 256 complete boards | Any of four columns in each of four rows |
| Backtracking tries 60 placements in total | Dead ends are abandoned as soon as they appear |
| Both find the same 2 solutions | Backtracking skips only boards that cannot work |
| For eight queens: 16,777,216 boards against 15,720 tries | The saving grows dramatically with the board size |
Backtracking solves many practical problems of the same shape. A timetabling program places one lesson at a time and backs up when a teacher or a room is double-booked. A sudoku solver fills one square at a time and backs up when a row, column or box repeats a digit. In each case, checking a partial answer early is what makes the search fast.
Heuristics
A heuristic is a rule of thumb that finds a good answer quickly, without any guarantee that it is the best. It is used when the best answer would take too long to find. The nearest-neighbour heuristic for routes is a simple example: from each town, drive to the closest town not yet visited, and return home at the end.
Figure 23.2 compares the nearest-neighbour route with the best route for up to six towns. Change the number of towns, then switch on the wrong model.
A heuristic route through towns
- Nearest neighbour
- ACEBDA, 20.22 km
- Best route
- ABEDCA, 17.63 km
- Different routes
- 12
Common mistake: thinking a heuristic's answer is always the best one. A heuristic makes the choice that looks best at each step, which can lead it into a poor position later. Its answers are usually good, but they must be tested against the best answers where those can be found.
Worked example 10: how good is the heuristic?
For the six towns of Figure 23.2, nearest neighbour gives a route of 24.22 km and trying every route gives 19.63 km. How much longer is the heuristic's route?
| Working | Reason |
|---|---|
| Extra distance = 24.22 − 19.63 = 4.59 km | The heuristic's route minus the best |
| As a percentage: 4.59 ÷ 19.63 × 100, about 23% | Compare the extra with the best route |
| The best route needed 60 routes to be checked | For six towns that is still quick |
| For 20 towns the heuristic is the only practical choice | Checking every route would take years |
Heuristics are used everywhere that the best answer is too expensive. A* search uses a heuristic, the straight-line distance to the goal, to decide which path to explore next. Chess programs use heuristics to judge positions they cannot search to the end. Delivery firms use heuristics to plan thousands of routes every morning.
Check yourself. Why does backtracking find solutions to the queens problem far faster than brute force?
Show the answer
Backtracking checks each partial board as it is built and abandons it as soon as two queens clash. That rules out every board starting that way at once, whereas brute force builds and checks each complete board.
Section 6
Data mining, performance modelling, pipelining and visualisation
Data mining
Data mining searches large amounts of data for patterns and relationships that are not obvious. Shops mine their sales records to find items often bought together. Banks mine transactions to spot fraud. Hospitals mine patient records to find early signs of disease. The patterns can guide decisions, such as where to place goods in a shop or which payments to check.
Two simple measures describe a pattern of items bought together. The support of a set of items is the share of all baskets that contain the whole set. The confidence of a rule "if A then B" is the share of baskets containing A that also contain B. A rule with high support and high confidence is worth acting on.
Worked example 11: support and confidence
Using the five baskets, find the support of {bread, butter} and the confidence of the rule "if bread then butter".
| Working | Reason |
|---|---|
| Baskets with bread and butter: 2, 4 and 5 | Three of the five baskets hold both |
| Support = 3 ÷ 5 = 0.6 | The share of all baskets containing the set |
| Baskets with bread: 1, 2, 4 and 5 | Four baskets contain bread |
| Confidence = 3 ÷ 4 = 0.75 | Of the bread baskets, the share with butter |
Common mistake: thinking a pattern found by data mining proves one thing causes another. Data mining finds things that happen together, not why they happen. Two items may be bought together because both are on offer, or because of a third factor, so a pattern needs explaining before it is acted on.
Data mining raises questions as well as answers. The data is often personal, so it must be collected and kept within data protection law. Patterns found in past data may reflect past unfairness. And with enough data, some patterns appear purely by chance, so findings should be checked on fresh data.
Performance modelling
Performance modelling predicts how a system will behave before it is built or before it meets real loads. A model might predict how long a program will take with ten times as much data, or how many users a server can handle. It avoids the cost of building a system that turns out to be too slow, or of testing it with millions of real users.
A simple model uses an algorithm's order of growth. If an O(n²) program takes 2 seconds for 1,000 items, ten times as many items take 10² = 100 times as long. That prediction comes from the model alone, without running the program on 10,000 items.
Worked example 12: predicting a run time
An O(n²) sort takes 2 seconds for 1,000 items. Predict its time for 10,000 items, and compare an O(n log n) sort that also takes 2 seconds for 1,000.
| Working | Reason |
|---|---|
| The data grows by a factor of 10 | From 1,000 items to 10,000 items |
| O(n²): time × 10² = 2 × 100 = 200 s | The time grows with the square of n |
| O(n log n): 2 × 10 × log 10,000 ÷ log 1,000 | Scale both n and its logarithm |
| = 2 × 10 × 4 ÷ 3, about 26.7 s | So the faster-growing sort is far slower |
Pipelining
Pipelining splits a task into stages, and passes the output of each stage straight on to the next, like an assembly line. While the second stage works on the first item, the first stage starts on the second. Once the pipeline is full, one finished item comes out at every step, even though each item still passes through every stage.
Pipelining is used in processors, which fetch one instruction while decoding another and executing a third. It is also used to process data: one stage reads records, the next cleans them and the next analyses them. With k stages of one step each, n items take k + n − 1 steps, rather than k × n.
Pipelining does not make any single item faster. Each item still passes through every stage, so the first item takes as long as before. The gain comes from overlap: the stages stay busy on different items. A pipeline is only as fast as its slowest stage, so the stages should take about the same time.
Derivation: the steps taken by a pipeline
Let a pipeline have k stages, each taking one step. The first item needs k steps to pass through every stage, and after that one item leaves at every step. So n items take
The speed-up is the ratio of the two. When n is much larger than k, the 1 and the k in the denominator hardly matter.
So a k-stage pipeline approaches k times the speed for a long run of items. For 100 items and five stages, it takes 104 steps instead of 500.
Visualisation
Visualisation presents data or a solution as a picture, such as a chart, a map or a diagram. People spot patterns in pictures far faster than in tables of numbers. A graph of run time against data size shows at a glance whether an algorithm grows linearly or quadratically. A map of delivery routes shows a bad route immediately. Visualisation helps programmers understand problems and helps users understand answers.
Good visualisation is designed with care. A chart with a misleading scale can make a small change look huge, and too many colours can hide the pattern it was meant to show. The picture should answer one clear question, with labelled axes and units, so that the viewer sees the point without being misled.
Check yourself. A three-stage data pipeline processes 10 batches, each stage taking one step. How many steps does it take, and how many without pipelining?
Show the answer
With pipelining it takes 3 + 10 − 1 = 12 steps, because a batch finishes every step once the pipeline is full. Without pipelining each batch takes 3 steps, so 10 batches take 30 steps.
Reference
Key algorithms and definitions
| Term or algorithm | What it means | Example | Cost or rule to learn |
|---|---|---|---|
| IDE | Tools to write, run and debug code | Breakpoints, watches, stepping | Finds logic errors faster |
| Syntax, runtime and logic errors | Broken rules, a crash, a wrong answer | Missing bracket; divide by 0; wrong condition | Only tests find logic errors |
| Normal, boundary, erroneous data | Typical, at the edges, to be rejected | 50; 0 and 100; −1 and 101 | Test both sides of each boundary |
| Black-box and white-box testing | From the requirements or from the code | Inputs only; every branch | Use both |
| Alpha, beta, acceptance testing | In-house, real users, the client | Testers; volunteers; the buyer | In that order |
| Tractable problem | Solvable in polynomial time | Sorting is O(n log n) | Exponential or factorial is intractable |
| Divide and conquer | Split into smaller problems of the same kind | Binary search, merge sort | Halving gives log₂ n levels |
| Backtracking | Build step by step, undo dead ends | n queens | Far fewer tries than brute force |
| Heuristic | A quick rule giving a good answer | Nearest neighbour | Not always the best |
| Data mining | Finding patterns in large data | Items bought together | Support and confidence |
| Pipelining | Stages work on different items at once | Read, clean, analyse | k + n − 1 steps |
Programming task
Programming task: a backtracking queens solver
Aim
Write a Python program that uses backtracking to find every way of placing n queens on an n × n board so that none attack each other. It must report how many solutions there are for each board size from 1 to 8.
Design
The program stores a partial solution as a list, cols, where cols[r] is the column of the queen in row r. A function safe checks whether a new queen in a given row and column clashes with any queen already placed. Two queens clash if they share a column, or if the difference between their columns equals the difference between their rows, which means they share a diagonal.
A recursive function place tries each column in the current row. If the queen is safe, it adds it to the list, calls itself for the next row, then removes the queen again so the next column can be tried. That removal is the backtracking step. When every row has a queen, a complete solution has been found and is counted.
Code
def safe(cols, row, col):
for r in range(row):
if cols[r] == col or abs(cols[r] - col) == row - r:
return False
return True
def solve(n):
solutions = []
cols = []
def place(row):
if row == n:
solutions.append(list(cols))
return
for col in range(n):
if safe(cols, row, col):
cols.append(col)
place(row + 1)
cols.pop()
place(0)
return solutions
for n in range(1, 9):
print(n, "queens:", len(solve(n)), "solutions")
print("first solution for 4:", solve(4)[0])
The inner function place can see cols and solutions, so they need not be passed at every call. Copying cols with list(cols) when a solution is found matters, because cols itself keeps changing as the search continues.
Testing
| Test | Input | Expected output | Why this test |
|---|---|---|---|
| 1 | n = 1 | 1 solution | The smallest board |
| 2 | n = 2 | 0 solutions | No placement works at all |
| 3 | n = 3 | 0 solutions | Still impossible |
| 4 | n = 4 | 2 solutions | Matches worked example 9 |
| 5 | n = 5 | 10 solutions | More solutions than n |
| 6 | n = 6 | 4 solutions | Fewer than for 5 |
| 7 | n = 8 | 92 solutions | The classic eight queens |
| 8 | first solution for 4 | [1, 3, 0, 2] | Columns counted from 0 |
Evaluation
The solver gives the expected count for every board size, including the cases with no solutions at all, where it correctly reports 0 rather than failing. Eight queens takes a fraction of a second, because backtracking abandons dead ends early instead of checking all 16,777,216 boards.
The program could be improved by keeping sets of the columns and diagonals already used, so that safe takes one step instead of a loop. For much larger boards, there are so many solutions that the program should stop at the first one. A heuristic that tries the least crowded columns first would find it sooner.
Practice
Practice ladder
Rung 1: Recall and fluency
Q1. Describe two IDE features that help a programmer debug a program.
Worked solution to Q1
A breakpoint pauses the program at a chosen line so the values of variables can be inspected. Stepping then runs one line at a time, showing exactly which path the program takes.
Q2. Define boundary test data, and give an example for a range from 1 to 50.
Worked solution to Q2
Boundary data lies at the edges of the allowed range, where bugs are most likely. For a range from 1 to 50, the values 1 and 50 are boundary data, with 0 and 51 just outside it.
Q3. Explain the idea of a heuristic, and say when one is used.
Worked solution to Q3
A heuristic is a rule of thumb that finds a good answer quickly, without guaranteeing the best one. It is used when finding the best answer would take far too long.
Rung 2: Application
Q4. A sorted list holds 4,000 items. What is the largest number of comparisons binary search needs?
Worked solution to Q4
Each comparison halves the part left to search. 2¹¹ = 2,048 and 2¹² = 4,096, so 4,000 items are covered by twelve halvings, and at most 12 comparisons are needed.
Q5. Using the five baskets of section 6, find the confidence of the rule "if butter then bread".
Worked solution to Q5
Butter appears in baskets 2, 4 and 5, and every one of those also contains bread. So the confidence is 3 ÷ 3 = 1: every butter buyer here also bought bread.
Q6. A function has four IF ... ELSE decisions in sequence. How many tests are needed for full path coverage?
Worked solution to Q6
Each decision doubles the paths, so four in sequence give 2⁴ = 16 paths. Full path coverage therefore needs 16 tests, though branch coverage needs only 2.
Q7. A four-stage pipeline processes 20 items, each stage taking one step. How many steps does it take?
Worked solution to Q7
The first item takes 4 steps to pass through all four stages, and one more item finishes each step after that. So the total is 4 + 20 − 1 = 23 steps, against 80 without pipelining.
Rung 3: Analysis
Q8. Explain why black-box testing alone might miss a bug in a rarely used error message.
Worked solution to Q8
Black-box tests are chosen from the requirements, so they may never trigger the unusual case that shows the message. White-box testing chooses inputs to exercise every branch, so it would reach that code.
Q9. A program accepts a temperature from −20 to 40 inclusive. List six test values, with the kind of data and expected result for each.
Worked solution to Q9
Normal 10 accepted; boundary −20 and 40 accepted; just outside, −21 and 41 rejected; erroneous "hot" rejected with a message. These test the middle, both edges and a value of the wrong type.
Q10. For five queens, backtracking finds 10 solutions. How many complete boards would brute force check?
Worked solution to Q10
Brute force puts each of the five queens in any of five columns, giving 5⁵ = 3,125 complete boards to build and check. Backtracking needs only 220 tries, because it abandons each dead end early.
Q11. An O(n²) program takes 3 seconds for 2,000 records. Predict its time for 6,000 records.
Worked solution to Q11
The data grows by a factor of 3, so an O(n²) time grows by 3² = 9. The predicted time is 3 × 9 = 27 seconds for 6,000 records.
Rung 4: Stretch
Q12. Explain why the nearest-neighbour heuristic can give a poor route, using the idea of a greedy choice.
Worked solution to Q12
Nearest neighbour is greedy: it always takes the shortest next step without looking ahead. Taking short steps early can leave distant towns until last, forcing long legs at the end, as in Figure 23.2.
Q13. A van must visit 10 towns. How many different closed routes are there, and is checking them all practical?
Worked solution to Q13
There are 9! ÷ 2 = 181,440 routes, which a computer can check in well under a second. So for 10 towns an exact search is practical, though the count explodes for a few more towns.
Q14. A data-mining study finds that people who buy umbrellas often buy soup. Explain why the shop should not conclude that umbrellas make people want soup.
Worked solution to Q14
The pattern shows the items are bought together, not that one causes the other. A third factor, cold rainy weather, could explain both, so the shop should look for an explanation before acting.
Exam practice
Exam technique and worked answer workshop
For testing questions, always give the expected result with every test value, and say what kind of data it is. "Test 100, boundary, expected to be accepted" earns the mark; "test 100" alone often does not.
For computational methods, name the method and tie it to the problem. "Backtracking, because a partial timetable with a clash can be abandoned at once" is far stronger than a definition alone. When comparing a heuristic with an exact method, give the trade-off: speed against the guarantee of the best answer.
For calculations, show the formula, such as k + n − 1 steps or the ratio of growth functions, then substitute.
Exam question 1 (4 marks · Paper 02 · about 5 minutes)
A student's program runs but gives the wrong total. Describe two features of an IDE that would help the student find the error.
Mark scheme for exam question 1
- B1 a breakpoint, which pauses the program at a chosen line
- B1 so the values of variables can be inspected at that point
- B1 stepping, or a watch window, which runs one line at a time or shows chosen variables
- B1 so the student sees exactly where the total first goes wrong
Exam question 2 (5 marks · Paper 02 · about 7 minutes)
A cinema's booking program accepts between 1 and 10 tickets per order.
(a) Give one normal, one boundary and one erroneous test value, with the expected result of each. [3]
(b) Explain why boundary data should be tested. [2]
Mark scheme for exam question 2
- B1 normal, such as 5, accepted
- B1 boundary, such as 1 or 10, accepted
- B1 erroneous, such as 11, 0 or "two", rejected
- B1 many errors occur at the edges of a range, such as using < instead of <=
- B1 normal data passes either way, so only boundary tests expose these errors
Exam question 3 (5 marks · Paper 01 · about 7 minutes)
A software house tests every program it writes in several different ways.
(a) Explain the difference between black-box and white-box testing. [2]
(b) Explain the difference between alpha and beta testing. [2]
(c) State the purpose of acceptance testing. [1]
Mark scheme for exam question 3
- B1 black-box testing chooses inputs from the requirements and checks outputs without looking at the code
- B1 white-box testing uses the code, choosing inputs that exercise every branch and path
- B1 alpha testing is done inside the developing company
- B1 beta testing is done by real users outside the company, in real conditions
- B1 the client checks that the program meets the agreed requirements before accepting it
Exam question 4 (4 marks · Paper 02 · about 5 minutes)
A library's catalogue holds 1,000,000 titles, sorted alphabetically.
(a) Calculate the largest number of comparisons binary search needs to find a title. [2]
(b) Explain why binary search is an example of divide and conquer. [2]
Mark scheme for exam question 4
- M1 2²⁰ = 1,048,576, which is at least 1,000,000
- A1 20 comparisons
- B1 it splits the problem into a smaller problem of the same kind, searching half the list
- B1 and repeats until the title is found or no items remain
Exam question 5 (6 marks · Paper 02 · about 9 minutes)
A delivery company plans routes for 200 vans every morning. Each van visits about 40 addresses. Discuss whether the company should use an exact method or a heuristic to plan the routes.
Mark scheme for exam question 5
Level 3 (5–6 marks): a balanced discussion of exact and heuristic methods, linked to the company's routes. It explains why the exact method is intractable here and weighs speed against the quality of the routes. The answer reaches a justified conclusion. It is well organised and uses technical terms accurately.
Level 2 (3–4 marks): explains some features of each method with some link to the company. The discussion is one-sided or the conclusion is limited.
Level 1 (1–2 marks): some relevant points, such as that heuristics are faster, with little development. The answer may lack structure.
0 marks: no response or no response worthy of credit.
Indicative content:
- an exact method checks every possible route, so it is guaranteed to find the shortest
- for 40 addresses there are about 39! ÷ 2 routes, far too many to check in a lifetime
- so the exact method is intractable here, and could not finish before the vans leave
- a heuristic, such as nearest neighbour, finds a good route in a fraction of a second
- its routes may be longer than the best, wasting fuel, time and money every day
- the heuristic can be improved, for example by swapping pairs of stops to shorten the route
- its routes can be compared with the best on small test cases, to measure how far off they are
- conclusion: a heuristic is the only practical choice, with improvements and testing to keep routes short
Annotated model answer: exam question 5
"An exact method would check every possible route for each van, so it would always find the shortest. But a van with 40 addresses has about 39! ÷ 2 possible routes. That is so many that no computer could check them before the vans leave, so the exact method is intractable here." (Exact method explained and shown to be intractable.)
"A heuristic such as nearest neighbour drives to the closest unvisited address each time. It finds a route for each van in a fraction of a second, so all 200 routes are ready in time." (Heuristic explained, tied to the company.)
"But a heuristic's route may be longer than the best one. Over 200 vans every day, a few extra kilometres each wastes a great deal of fuel and time. The company could improve its routes by swapping pairs of stops, and test the heuristic against exact answers for small cases." (Drawback weighed, with ways to reduce it.)
"So the company should use a heuristic, because the exact method cannot finish in time, but should improve and test it to keep the routes short." (Justified conclusion.)
This answer reaches Level 3 and scores 6 marks. It explains both methods, shows why one is impractical and reaches a judgement grounded in the scenario.
Exam question 6 (5 marks · Paper 02 · about 7 minutes)
Four queens must be placed on a 4 × 4 board so that none attack each other.
(a) Describe how backtracking would solve this problem. [3]
(b) Brute force checks every complete board with one queen in each row. Calculate how many boards it checks, and state why backtracking needs far fewer tries. [2]
Mark scheme for exam question 6
- B1 place a queen in each row in turn, trying each column
- B1 if the new queen is attacked, try the next column in that row
- B1 if no column works, go back to the previous row and move its queen on
- B1 4⁴ = 256 boards
- B1 backtracking abandons a partial board as soon as it clashes, ruling out every board that starts that way
Exam question 7 (5 marks · Paper 01 · about 7 minutes)
A shop records five baskets: {bread, milk}, {bread, butter, milk}, {milk, eggs}, {bread, butter} and {bread, butter, milk, eggs}.
(a) Calculate the support of {bread, butter}. [2]
(b) Calculate the confidence of the rule "if bread then butter". [2]
(c) Give one reason the shop should be careful about acting on such a rule. [1]
Mark scheme for exam question 7
- M1 3 of the 5 baskets contain both
- A1 0.6
- M1 3 of the 4 baskets with bread also contain butter
- A1 0.75
- B1 the pattern shows items bought together, not that one causes the other, or it may arise by chance in a small sample
Exam question 8 (6 marks · Paper 02 · about 9 minutes)
In a queens solver, the array cols holds the column of the queen in each of rows 0 to row − 1. Write a function safe(cols, row, c) that returns true if a queen at row row, column c, is not attacked by any queen already placed.
Mark scheme for exam question 8
- B1 a function header with the three parameters
- B1 a loop over every earlier row, from 0 to row − 1
- B1 a check for a queen in the same column, cols[r] == c
- M1 a check for a shared diagonal, the difference in columns equal to the difference in rows
- B1 returning false as soon as either check is true
- A1 returning true after the loop, when no queen attacks
Annotated model answer: exam question 8
function safe(cols, row, c)
for r = 0 to row - 1
if cols[r] == c then
return false
endif
if abs(cols[r] - c) == row - r then
return false
endif
next r
return true
endfunction
The header earns the first mark, and the loop over the earlier rows earns the second. The same-column test earns the third, and the diagonal test, comparing the column difference with the row difference, earns the method mark. Returning false on a clash earns the fifth, and returning true only after the loop earns the last.
Connections
Synoptic link
Divide and conquer is the method behind binary search and merge sort in Searching and sorting algorithms. Its log₂ n levels are why those algorithms are fast, as Algorithm analysis and Big O notation shows. Backtracking is written with the recursion of Subroutines and recursion, and depth-first search in Graph traversal and shortest paths backtracks in the same way.
The heuristic in A* search, taught in Graph traversal and shortest paths, is the straight-line distance to the goal. Pipelining in processors is taught in Processor architecture and performance, and data mining must respect the laws of Legal, moral, ethical and cultural issues.
Synoptic question 1. A processor has a five-stage pipeline. How many clock cycles does it need for 100 instructions, if nothing stalls?
Answer to synoptic question 1
The first instruction takes 5 cycles to pass through every stage, and then one instruction finishes each cycle. So 100 instructions take 5 + 100 − 1 = 104 cycles, against 500 without a pipeline.
Recap
Recap and next step
- An IDE helps to write code with highlighting and completion, and to debug it with breakpoints, stepping and watches; only testing finds logic errors.
- Test data should be normal, boundary and erroneous, with expected results; boundary tests on both sides of each edge find off-by-one bugs.
- Black-box and white-box testing find different bugs; unit, integration and system testing are followed by alpha, beta and acceptance testing.
- A problem suits computation if it is precise and has an algorithm; intractable problems need too long, and divide and conquer gives log₂ n levels.
- Backtracking abandons dead ends early; heuristics give good answers quickly, but not always the best.
- Data mining finds patterns, measured by support and confidence; performance models predict run times; pipelines take k + n − 1 steps; visualisation shows patterns.
Next chapter: Algorithm analysis and Big O notation measures how the time and memory of an algorithm grow with its input.
For your exam board
OCR A Level Computer Science (H446): this chapter covers section 2.2.1, Programming techniques, for the use of an IDE to develop and debug a program, and section 2.2.2, Computational methods, in Component 02: problem recognition, decomposition, divide and conquer, abstraction, backtracking, data mining, heuristics, performance modelling, pipelining and visualisation, with the testing of section 1.2.3.
AQA A Level Computer Science (7517): the fundamentals of programming and the systematic approach to problem solving sections cover design, testing and evaluation, and the theory of computation covers tractable and intractable problems and heuristics, assessed on Papers 1 and 2.