A Level Computer Science · Chapter 19 · Component 02: Algorithms and programming
Computational thinking turns a messy real problem into one a computer can solve, by abstracting, planning ahead, breaking it down, reasoning about decisions and finding parallel work.
This chapter teaches the six habits of mind behind every good program: thinking abstractly, thinking ahead, caching and reuse, thinking procedurally, thinking logically and thinking concurrently. Each habit is practised on real problems, and the numbers show why it matters, from the paths through a program to the time saved by a cache.
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:
- explain abstraction, choose which details of a real problem to keep, and devise an abstract model
- identify the inputs, outputs and preconditions of a problem or subroutine
- explain caching and reusable components, and calculate the average time of a cached system
- decompose a problem into sub-problems and put dependent steps in a workable order
- identify the decision points in a solution and count the paths through it
- identify parts of a problem that can be solved at the same time, and calculate the time taken by several workers
Time: three sessions, about 4 hours, plus the programming task.
You need first: selection, iteration and subroutines from Programming constructs and Subroutines and recursion.
The big picture
The big picture
A computer can only follow precise instructions about precise data. The real world is neither precise nor tidy. A school timetable involves people with preferences, rooms of odd shapes, buses that run late and rules that contradict each other. Before any code is written, someone has to turn that mess into a problem a computer can solve. The ways of thinking that do this are called computational thinking.
Computational thinking is not only for programmers. A nurse planning a ward round, a chef running a busy kitchen and a coach planning a training week all use the same habits. They ignore what does not matter and plan for what they will need. They break big jobs into small ones, decide what to do in each case and share out work that can happen at once. Computer science gives these habits names and makes them precise.
The habits work together rather than one at a time. To build a sat-nav, you abstract the road network into a graph of junctions and roads. You think ahead about the inputs, a start and a destination, and the output, a route. You cache routes that are often asked for. You decompose the program into map loading, route finding and display. You reason about decisions, such as which road to try next. You might search several possible routes at once on different processor cores.
None of these habits produces code by itself. They produce a clear understanding of the problem and a plan for solving it. That plan is what makes the code short, correct and fast. Programmers who skip this stage tend to write long programs that solve the wrong problem, or solve the right one very slowly.
The exam tests these habits in two ways. Some questions ask you to explain a habit, such as what abstraction means or why a precondition helps. Others give you a scenario and ask you to apply a habit to it. You might name the details to remove, the inputs needed, the parts that can run at once, or the order of the steps. The second kind earns most of the marks. Every answer should be tied to the scenario in the question, not given in general terms.
The habits also connect to the rest of the course. Abstraction is behind every data structure and every class in object-oriented programming. Thinking ahead is behind the preconditions of algorithms such as binary search. Thinking logically is behind selection and Boolean algebra. Thinking concurrently is behind multi-core processors and the parallel parts of an operating system. Each time you meet one of those topics, you are using a habit from this chapter.
Section 1
Thinking abstractly
What abstraction is
Abstraction means removing the details of a problem that do not matter, so you can concentrate on the details that do. The result is an abstract model: a simpler version of reality that keeps just enough to solve the problem. What counts as unnecessary depends entirely on the problem being solved.
The London Underground map is the classic example. It shows stations, the lines between them and where you can change trains. It leaves out the real distances, the bends in the tunnels, the streets above and the depth of each station. For a passenger planning a journey, those details do not matter. For an engineer digging a new tunnel, they matter enormously, and the passenger's map would be useless.
The graph above is an even more abstract model. Each station becomes a node and each connection becomes an edge, with a weight for the number of stops. A route-finding algorithm such as Dijkstra's can now work on it. The graph has thrown away almost everything about the real railway, and that is exactly why a computer can solve the problem quickly.
Levels of abstraction
Abstraction happens in layers. A programmer writing in Python does not think about the machine code that the interpreter runs. The person writing the interpreter does not think about the transistors that run the machine code. Each layer hides the details of the layer below and offers a simpler view to the layer above.
Data structures and classes are abstractions too. A stack offers push and pop, and hides whether it is built from an array or a linked list. A class called Account offers deposit and withdraw, and hides how the balance is stored. This is called data abstraction: the user of the structure needs to know what it does, not how it does it.
Layers of abstraction let large teams build large systems. Each team needs to understand only its own layer and the interface to the layers next to it. A change inside one layer, such as a faster way of storing the stack, does not affect anything above it, as long as the interface stays the same.
Abstraction and reality
An abstract model is always different from reality, and the differences matter. A model that leaves out something important gives wrong answers. A sat-nav that models roads but not traffic sends drivers into jams. A weather model that uses a coarse grid misses a storm that forms between grid points. Good abstraction means choosing what to leave out with care, and knowing the limits of the model.
The right level of detail also depends on who will use the answer. A city planner deciding where to build a new station needs passenger numbers and walking times, which the passenger's map leaves out. The same railway can need several different models, each made for its own question. Choosing the model to fit the question is the heart of thinking abstractly.
Common mistake: thinking a good model must include every real detail. A model with every detail is as complicated as reality and no easier to solve. The skill is to keep only the details that affect the answer, and to know which questions the model can and cannot answer.
Worked example 1: abstracting a delivery problem
A bakery wants a program to plan the route of its delivery van around twelve cafés. Decide which details to keep and which to remove.
| Working | Reason |
|---|---|
| Keep each café's location and the road distances between them | The route length depends on these |
| Keep each café's opening time | The van must arrive while it is open |
| Remove the colour of the van and the names of the café owners | These do not affect the route at all |
| Remove the exact shape of each road | Only the distance or driving time matters |
| Model the cafés as nodes and the roads as weighted edges | A graph lets a routing algorithm work |
Worked example 2: modelling a supermarket queue
A supermarket wants to simulate its checkouts to decide how many to open. Devise an abstract model.
| Working | Reason |
|---|---|
| Represent each checkout as a queue | Customers are served in the order they arrive |
| Represent customers by arrival time and number of items | These decide how long each customer is served |
| Use an average rate for scanning items | Each cashier's exact speed varies too much to model |
| Ignore what each customer buys | The type of item does not change the time much |
| Output the average waiting time for each number of checkouts | That is the figure the manager must decide on |
The model ignores many real details: customers who leave the queue, cashiers who chat, a card machine that fails. Those omissions are the model's limits. If the manager finds that real waits are much longer than the model predicts, one of the missing details probably matters and should be added.
Abstraction also appears in the way problems are described. "Find the shortest route between two places" is an abstraction of thousands of real problems: delivering parcels, routing network packets, planning a walk. Once a problem is recognised as an example of a known abstract problem, a known algorithm can solve it. Recognising the abstract problem behind a real one is one of the most valuable skills in computing.
Check yourself. A school's model of its car park records each space as free or taken, and nothing else. Give one question the model can answer and one it cannot.
Show the answer
It can answer how many spaces are free right now, because it records each space's state. It cannot answer whether a large van will fit, because the size of each space has been abstracted away.
Section 2
Thinking ahead
Inputs and outputs
Thinking ahead means working out, before you start, what a solution will need and what it must produce. The first step is to identify the inputs and outputs. The inputs are the data the solution is given. The outputs are the results it must give back. Everything else in the solution exists to turn the inputs into the outputs.
Writing down inputs and outputs first fixes the boundaries of the problem. It shows what data must be collected or passed in, what format it arrives in, and what form the answer must take. It also exposes questions early. If a program must output a delivery time, does it need traffic data as an input? It is far cheaper to find that out before coding than after.
Preconditions
A precondition is something that must be true before a subroutine is called, for it to work correctly. Binary search has the precondition that the list is sorted. A square root function might have the precondition that its input is not negative. A function that removes the top of a stack needs the stack not to be empty.
Stating preconditions is part of thinking ahead. It tells anyone using the subroutine what they must guarantee. The subroutine itself can then be simpler, because it does not need to check for, or handle, every possible bad input. It also makes the subroutine easier to reuse, because its requirements are written down rather than buried in the code.
Common mistake: thinking a precondition is something the subroutine checks and fixes. A precondition is a promise the caller must keep. The subroutine may simply assume it is true, so if a caller breaks it, the result can be wrong without any warning.
That does not mean validation is never needed. Data that comes from a user or a file should be validated when it enters the program, because users make mistakes. But once data has been validated, the subroutines inside the program can rely on preconditions rather than checking again and again.
Worked example 3: planning a search
A program must find a pupil's record by candidate number in a list of 2,000 records. Think ahead about the inputs, the output and the preconditions.
| Working | Reason |
|---|---|
| Inputs: the list of records and the candidate number | These are what the search is given |
| Output: the matching record, or a message if there is none | The caller needs to know either way |
| To use binary search, the list must be sorted by candidate number | That is binary search's precondition |
| Binary search then needs at most 11 comparisons, against 2,000 for linear search | It halves the list at every step |
| If the list arrives unsorted, sort it once first, or use linear search | The precondition must be met somehow |
| State the precondition in the subroutine's comments | Later programmers then know what to guarantee |
Worked example 4: an average function
A function returns the mean of a list of exam marks. What precondition should it state, and why?
| Working | Reason |
|---|---|
| The mean is the total divided by the number of marks | The definition of the mean |
| An empty list has zero marks | There is nothing to count |
| Dividing by 0 would crash the program or give no answer | Division by zero is undefined |
| Precondition: the list must contain at least one mark | The caller must check this before calling |
Thinking ahead about the future
Thinking ahead also means planning for how a program will be used and changed. Will the number of users grow? Will new kinds of data arrive? A program designed so that new features can be added without rewriting it is called maintainable. Choosing clear names, splitting the program into subroutines and writing comments are all ways of thinking ahead for the programmer who comes next.
Check yourself. A subroutine takes a person's date of birth and returns their age in years. State its inputs, its output and one precondition.
Show the answer
The inputs are the date of birth and today's date, and the output is the age in whole years. One precondition is that the date of birth is not after today's date, since a negative age makes no sense.
Section 3
Caching and reusable components
Caching
A cache stores the results of recent work so they can be reused instead of being worked out or fetched again. Your web browser caches pages and images, so a page you visit twice loads faster the second time. A processor caches recently used data from main memory. A program can cache the results of a slow calculation, which is called memoisation.
When a request arrives, the system first looks in the cache. If the answer is there, a cache hit, it is returned quickly. If it is not, a cache miss, the system does the slow work and usually stores the result in the cache for next time. The share of requests that are hits is the hit rate.
The average time per request depends on the hit rate. If a fraction h of requests are hits, taking time t_hit, and the rest are misses, taking t_miss, the average is h × t_hit + (1 − h) × t_miss. A high hit rate brings the average close to the hit time.
Derivation: the average time of a cached system
Let a fraction h of requests be hits and the rest misses. Over many requests, the average time is the weighted mean of the two times.
To reach a target average T, rearrange for the hit rate needed.
For a hit time of 2 ms, a miss time of 50 ms and a target of 10 ms, the hit rate needed is 40 ÷ 48, about 0.83. The cache must answer about five requests in every six.
Worked example 5: a cached database
A web server answers a request in 2 ms if the result is in its cache, and in 50 ms if it must query the database. Its hit rate is 90%. Find the average time per request.
| Working | Reason |
|---|---|
| Hits: 0.9 × 2 = 1.8 ms | Nine in ten requests are fast |
| Misses: 0.1 × 50 = 5 ms | One in ten requests is slow |
| Average = 1.8 + 5 = 6.8 ms | Add the two weighted contributions |
| Without the cache, every request takes 50 ms | So the cache makes the server about seven times faster |
Common mistake: thinking a cache makes every request as fast as a hit. Misses still take the full time, and because a miss is so much slower than a hit, even a few misses dominate the average. A 90% hit rate here gives 6.8 ms, more than three times the hit time.
Caches have costs too. They use memory, and they can return stale data if the original changes after it was cached. A browser may show yesterday's version of a news page. Deciding how long to keep each item, and what to throw away when the cache is full, are central design questions. A common rule is to throw out the item that was least recently used.
Memoisation
The recursive Fibonacci function shows why caching matters inside a program. To work out fib(5), it calls fib(4) and fib(3). But fib(4) calls fib(3) again, and both call fib(2) several times. The same work is repeated over and over.
With memoisation, the function stores each answer in a dictionary the first time it is worked out. Before doing any work, it looks in the dictionary. Now fib(n) needs only about n calls that do real work, instead of a number that grows exponentially. This is thinking ahead in action: the programmer foresaw that the same values would be needed again.
Reusable components
A reusable component is a piece of a solution that can be used again, in the same program or in others. Subroutines, classes and libraries are all reusable components. A well-tested sort routine can be used by every program that needs sorting. Nobody needs to write it again or test it again.
Thinking ahead means spotting, during design, which parts of a problem are general enough to reuse. A booking system for a cinema and one for a dentist both need to check whether a time slot is free. If that check is written as a general component, both systems can use it. Reuse saves time, and it reduces errors, because a component used in many places has been tested in many situations.
Worked example 6: is a cache worth it?
A price lookup takes 1 ms from a cache and 100 ms from a remote server. Find the average time with a 95% hit rate.
| Working | Reason |
|---|---|
| Hits: 0.95 × 1 = 0.95 ms | Nineteen in twenty lookups are fast |
| Misses: 0.05 × 100 = 5 ms | One in twenty lookups is slow |
| Average = 0.95 + 5 = 5.95 ms | Add the weighted contributions together |
| Speed-up = 100 ÷ 5.95, about 17 times | Compared with no cache at all |
Check yourself. A cache answers in 5 ms and a miss takes 80 ms. With a hit rate of 80%, what is the average time per request?
Show the answer
Hits contribute 0.8 × 5 = 4 ms and misses contribute 0.2 × 80 = 16 ms. So the average is 4 + 16 = 20 ms, four times the hit time, because the misses still dominate.
Section 4
Thinking procedurally
Decomposition
Thinking procedurally means working out the steps needed to solve a problem and the order they must happen in. The first part is decomposition: breaking a large problem into smaller sub-problems, each of which is easier to understand and solve. Each sub-problem can be broken down again until every part is small enough to write as a single subroutine.
This approach is called top-down design. It starts with the whole problem at the top and works downwards. The result can be drawn as a structure diagram, a tree with the whole problem at the root and the smallest parts at the leaves. The leaves are the parts that are actually programmed. Everything above them is put together from the leaves.
Decomposition has many benefits. Each sub-problem is small enough to understand in full. Different programmers can work on different parts at the same time. Each part can be tested on its own before the parts are joined. Parts that appear in several places, such as reading input, can be written once and reused.
Worked example 7: decomposing a quiz app
A teacher wants an app where pupils log in, answer ten questions and see their score. Decompose the problem.
| Working | Reason |
|---|---|
| Top level: log in, run quiz, show results | The three main things the app must do |
| Log in: read details, check password | Logging in needs both of these steps |
| Run quiz: pick questions, ask question, mark answer | Repeated for each of the questions |
| Show results: work out score, save score | The pupil and the teacher both need it |
| Each leaf becomes one subroutine | Small enough to write and test alone |
The order of steps
Decomposition finds the parts; thinking procedurally also means putting them in an order that works. Some steps depend on others. You cannot mark an answer before the question is asked, or save a score before it is worked out. Other steps are independent, and can be done in either order or even at the same time.
A dependency means one step must finish before another can start. First list the dependencies of each step. Then keep choosing a step whose dependencies are all done. This always gives a workable order, as long as no steps depend on each other in a loop. The project plan below shows dependencies as a chart.
Common mistake: thinking the steps can be done in any order once the problem is decomposed. Decomposition finds the parts but not their order. A step that depends on another must come after it, so the dependencies must be listed and respected, or the program uses data that does not exist yet.
Worked example 8: ordering dependent steps
A recipe has five steps. Chop needs wash first; cook needs chop and boil; serve needs cook. Wash and boil depend on nothing. Find a workable order, taking steps alphabetically when there is a choice.
| Working | Reason |
|---|---|
| Ready at the start: boil and wash, so take boil | Neither depends on any other step |
| Then wash, the only other step ready | It still depends on nothing |
| Then chop, now that wash is done | Its only dependency has finished |
| Then cook, now that chop and boil are done | Both of its dependencies have finished |
| Then serve; order: boil, wash, chop, cook, serve | Every step comes after its dependencies |
Sub-procedures
Each leaf of a decomposition becomes a sub-procedure: a subroutine with its own name, inputs and outputs. The main program then reads almost like the top of the structure diagram: logIn, runQuiz, showResults. Someone reading it can see the whole plan at once, and look inside each subroutine only when they need the detail.
Decomposition also guides how a team shares the work. Once the structure diagram is agreed, each programmer can take one branch, as long as everyone agrees the inputs and outputs of each part. Those agreements are the interfaces between the parts. If they are clear, the parts fit together first time; if they are vague, joining the parts exposes mismatches that are slow to fix.
Good sub-procedures do one job each, have clear inputs and outputs, and avoid global variables. That makes them easy to test on their own and easy to reuse. Take a sub-procedure called markAnswer, which takes a question and an answer and returns true or false. It can be tested with a handful of cases before it is joined to the rest of the program.
Check yourself. In a decomposition, why are only the leaves of the structure diagram written as code?
Show the answer
The leaves are the parts small enough to solve directly. Each higher part is just the leaves below it called in order, so it is built from them rather than written separately.
Section 5
Thinking logically
Decision points
Thinking logically means identifying the points in a solution where a decision is made, the conditions that decide it, and how each decision changes the flow of the program. In code, decisions are selection statements, IF and CASE, and the conditions that end loops. Getting the conditions exactly right is one of the hardest parts of programming.
A condition is a Boolean expression: it is either true or false. Conditions can be combined with AND, OR and NOT. The condition for a child's ticket might be age < 16 OR isStudent. The condition for a valid exam mark might be mark >= 0 AND mark <= 100. Writing a condition precisely means thinking through every case, including the edge cases, such as exactly 16 or exactly 100.
Paths through a program
Each two-way decision splits the program into two paths. If decisions follow one another, every path so far splits again at the next one. So a program with n independent two-way decisions in sequence has 2ⁿ possible paths. Figure 19.1 shows the tree of paths. Move the slider, then switch on the wrong model.
How decisions multiply the paths through a program
- Paths through the program
- 2³ = 8
- Tests to try every path
- 8
Common mistake: thinking each extra decision adds just one more path. Each decision doubles the paths, because every existing path can now go either way. Ten decisions in sequence give 1,024 paths, not 11, which is why testing every path quickly becomes impossible.
Derivation: the number of paths through n decisions
Let P(n) be the number of paths through n two-way decisions in sequence. With no decisions there is one path, and each new decision doubles the paths so far.
Applying the rule n times from P(0) gives a power of two.
Nested decisions follow the same rule along each branch. Decisions that cannot both be true, such as the branches of one CASE statement, add paths instead of multiplying them.
Worked example 9: counting paths
A program checks four separate conditions, one after another, each with an IF and an ELSE. How many paths does it have, and how many if a fifth check is added?
| Working | Reason |
|---|---|
| Each IF ... ELSE has two outcomes | The condition is either true or false |
| Four in sequence: 2 × 2 × 2 × 2 = 16 paths | Each decision doubles the paths so far |
| A fifth check: 2⁵ = 32 paths | Doubling again for the new decision |
| Testing every path needs at least 32 tests | One test for each route through the code |
Worked example 10: writing a precise condition
A cinema charges the child price to anyone under 16, and to anyone aged 60 or over. Write the condition and check it at the edges.
| Working | Reason |
|---|---|
| Condition: age < 16 OR age >= 60 | Either case gives the child price |
| Age 15: true, so child price | Fifteen is below the age limit |
| Age 16: false, so adult price | 16 is not under 16 and not 60 or over |
| Age 60: true, so child price | 60 meets the second part of the condition |
| Age 59: false, so adult price | 59 meets neither part of the condition |
The flow of a program depends on its decisions. A loop's condition decides how many times its body runs. A wrong condition can make a loop run one time too many or too few, or never stop. Thinking logically means tracing what happens at each decision, especially at the first and last values, before trusting the program.
Conditions can often be written in more than one way. NOT (age < 16) means the same as age >= 16, and De Morgan's laws turn NOT (a AND b) into NOT a OR NOT b. Choosing the clearest form makes a program easier to check. A condition that a reader must puzzle over is a condition where bugs hide.
Logic also shapes the order of conditions. In an IF ... ELSEIF chain, the first true condition wins. A grading program that tests mark >= 40 before mark >= 70 gives a grade 70 pupil the lower grade, because the first test is already true. Ordering conditions from the most to the least specific avoids this.
Check yourself. A program has six IF statements, one after another, and no ELSE parts. How many paths does it have?
Show the answer
Each IF without an ELSE still has two outcomes: its body runs or it is skipped. So six in sequence give 2⁶ = 64 paths through the program.
Section 6
Thinking concurrently
Doing things at the same time
Thinking concurrently means spotting the parts of a problem that can be tackled at the same time. A kitchen does not cook a meal one dish at a time: the potatoes boil while the meat roasts and the sauce is stirred. A computer with several processor cores can likewise run several parts of a program at once. Even a single core can switch rapidly between tasks, so that they appear to run together.
Parts can run at the same time only if they do not depend on each other. Rendering the frames of an animation is a good example: each frame can be drawn without waiting for any other. Totalling a list can be split too: each core totals one part, and then the part totals are added. But steps that need the result of an earlier step must wait for it. That is why thinking procedurally comes first: the dependencies decide what can be concurrent.
Sharing the work
When independent jobs are shared between workers, the time taken is set by the worker who finishes last. A simple, effective rule is to give the longest job left to the worker who becomes free first. Figure 19.2 shares jobs between workers in this way. Change the number of workers and the set of jobs, then switch on the wrong model.
Sharing jobs between workers
- Time with one worker
- 32 min
- Time with 2
- 17 min
- Speed-up
- 1.88 times
Common mistake: thinking k workers always finish in 1/k of the time. Work can only be shared job by job, so the slowest worker sets the time. A single long job cannot be split at all, and once there are more workers than jobs, the extra workers sit idle.
Worked example 11: six jobs on two workers
Six independent jobs take 8, 7, 6, 5, 4 and 2 minutes. They are shared between two workers, longest job first, each to the worker free first. When does the work finish?
| Working | Reason |
|---|---|
| 8 to worker 1 and 7 to worker 2 | Both workers start free, so take turns |
| 6 to worker 2, now at 13; 5 to worker 1, now at 13 | Each goes to the worker free first |
| 4 to worker 1, now at 17; 2 to worker 2, now at 15 | Again to whichever worker is free first |
| Finish time = 17 minutes, against 32 for one worker | The slower worker sets the finish time |
| Speed-up = 32 ÷ 17, about 1.9, not 2 | The work does not split perfectly evenly |
Worked example 12: one long job
Four jobs take 12, 3, 3 and 2 minutes. How long do three workers take, and why does a fourth worker not help?
| Working | Reason |
|---|---|
| 12 to worker 1; 3 to worker 2; 3 to worker 3 | Longest jobs first, one per free worker |
| 2 to worker 2, now at 5 minutes | Worker 2 and worker 3 are free first |
| Finish time = 12 minutes | The long job cannot be split |
| The wrong model predicts 20 ÷ 3, about 6.7 minutes | It assumes perfectly even sharing |
| A fourth worker still gives 12 minutes | The long job still sets the time |
Benefits and drawbacks
Concurrent processing can finish a task much sooner, and it makes better use of hardware that would otherwise sit idle. A web server that handles many requests at once serves far more users than one that handles them one by one. A game can load the next level while the player finishes the current one.
But concurrency has costs. Splitting the work and combining the results take time of their own. Parts that share data must be coordinated, or two parts may change the same value at once and leave it wrong. This is the same problem as two transactions updating one bank balance. Concurrent programs are harder to design, test and debug, because the order in which their parts run can change from one run to the next.
Concurrency also changes how a program must be tested. A bug may appear only when two parts happen to run in a particular order, which might occur once in a thousand runs. Such bugs are hard to reproduce, so concurrent designs try to keep the shared data small and protect it carefully.
The chart shows the limit. If only part of a task can run concurrently, the rest still runs at the old speed, and it soon dominates. A task that is 80% parallel can never run more than five times faster, even with a thousand cores. So the first question is always which parts are independent, and how big they are.
Check yourself. A photo app must load an image, apply a filter to each of its four quarters, then save it. Which steps can run at the same time?
Show the answer
The four filter steps can run at the same time, because each quarter can be processed without the others. Loading must happen before them and saving after them, because those steps depend on all of the image.
Reference
Key algorithms and definitions
| Term or algorithm | What it means | Example | Cost or rule to learn |
|---|---|---|---|
| Abstraction | Removing detail that does not affect the problem | A tube map, a graph of stations | Keep only what changes the answer |
| Abstract model | A simplified version of reality | A queue model of checkouts | Know what it leaves out |
| Precondition | What must be true before a subroutine runs | Binary search needs a sorted list | The caller guarantees it |
| Cache | A store of recent results for reuse | Browser cache, memoisation | h × t_hit + (1 − h) × t_miss |
| Reusable component | A part used again in other places | A tested sort routine | Write once, test once |
| Decomposition | Breaking a problem into sub-problems | A structure diagram | Leaves become subroutines |
| Dependency order | Steps placed after what they need | Design before coding | No step before its dependencies |
| Decision point | A place where a condition chooses the path | IF age >= 18 | n decisions give 2ⁿ paths |
| Concurrency | Parts of a problem tackled at once | Rendering frames on several cores | The slowest worker sets the time |
Programming task
Programming task: a job scheduler
Aim
Write a Python program that shares independent jobs between a number of workers. It gives the longest job left to the worker who becomes free first, then reports when the last worker finishes and which worker does each job.
Design
The program keeps a list of loads, one for each worker, starting at 0. It sorts the jobs from longest to shortest. For each job in turn, it finds the worker with the smallest load, adds the job to that worker's load and records the choice. The finish time is the largest load.
Running the program for one, two, three and four workers shows how much each extra worker helps. Comparing the finish time with the total time divided by the number of workers shows how far the real speed-up falls short of the ideal.
Code
def schedule(jobs, workers):
loads = [0] * workers
plan = []
for job in sorted(jobs, reverse=True):
free = loads.index(min(loads))
loads[free] = loads[free] + job
plan.append((job, free + 1))
return max(loads), plan
jobs = [8, 7, 6, 5, 4, 2]
total = sum(jobs)
for k in range(1, 5):
finish, plan = schedule(jobs, k)
print(k, "workers finish at", finish, "minutes; ideal", round(total / k, 2))
print(" plan:", plan)
Sorting with reverse=True puts the longest jobs first. The index of the smallest load identifies the worker free first, and on a tie it picks the lowest-numbered worker. Each entry in the plan pairs a job with the worker who does it, numbered from 1 for the output.
Testing
| Test | Input | Expected output | Why this test |
|---|---|---|---|
| 1 | jobs 8, 7, 6, 5, 4, 2 on 1 worker | 32 minutes | One worker does everything |
| 2 | jobs 8, 7, 6, 5, 4, 2 on 2 workers | 17 minutes | Matches worked example 11 |
| 3 | jobs 8, 7, 6, 5, 4, 2 on 3 workers | 11 minutes | One more worker helps again |
| 4 | jobs 12, 3, 3, 2 on 3 workers | 12 minutes | Matches worked example 12 |
| 5 | jobs 5, 5 on 4 workers | 5 minutes | More workers than jobs |
| 6 | no jobs on 2 workers | 0 minutes | An empty list must not crash |
| 7 | jobs 4, 4, 4, 4 on 2 workers | 8 minutes | Equal jobs share perfectly |
Evaluation
The scheduler gives the expected finish time in every test, including the edge cases of an empty list and more workers than jobs. The output shows clearly why extra workers help less and less. The finish time falls from 32 to 17 to 11 minutes, while the ideal falls from 32 to 16 to about 10.7.
The longest-first rule is a heuristic: it is quick and usually gives a good plan, but not always the best possible one. An improvement would try every way of sharing the jobs for small inputs and compare. Another would let jobs depend on each other, so that a job could start only when the jobs it needs have finished.
Practice
Practice ladder
Rung 1: Recall and fluency
Q1. Define abstraction, and give one example from everyday life.
Worked solution to Q1
Abstraction means removing the details of a problem that do not matter, keeping only what is needed to solve it. A tube map is an example: it keeps stations and connections but removes distances and streets.
Q2. Explain the term precondition, giving an example.
Worked solution to Q2
A precondition is something that must be true before a subroutine is called for it to work correctly. For example, binary search requires the list to be sorted before it is called.
Q3. Describe what happens on a cache hit and on a cache miss.
Worked solution to Q3
On a cache hit, the result is already in the cache, so it is returned quickly. On a miss, the system must do the slow work or fetch the data, and it usually stores the result in the cache for next time.
Rung 2: Application
Q4. A cache answers in 3 ms and a miss takes 60 ms. Find the average time per request with a hit rate of 75%.
Worked solution to Q4
The hits contribute 0.75 × 3 = 2.25 ms and the misses contribute 0.25 × 60 = 15 ms. So the average time per request is 2.25 + 15 = 17.25 ms.
Q5. A program contains seven separate IF ... ELSE statements in sequence. How many paths are there through it?
Worked solution to Q5
Each decision doubles the number of paths, so seven decisions in sequence give 2⁷ paths. That is 128 different routes through the program, each needing its own test to cover them all.
Q6. Jobs of 9, 7, 5, 4 and 3 minutes are shared between two workers, longest first, each to the worker free first. Find the finish time.
Worked solution to Q6
Nine goes to worker 1 and 7 to worker 2. Then 5 goes to worker 2 (12), 4 to worker 1 (13) and 3 to worker 2 (15). The finish time is 15 minutes, against 28 for one worker.
Q7. A game must load a level, then place the enemies and the items, then start. Placing the enemies and placing the items are independent. Give a workable order and say which steps could run at the same time.
Worked solution to Q7
One workable order is load, place enemies, place items, start. Placing the enemies and placing the items could run at the same time, because neither needs the other, but both must wait for loading.
Rung 3: Analysis
Q8. A sat-nav models roads as a graph with distances but ignores traffic. Explain one problem this abstraction causes and how to fix it.
Worked solution to Q8
The shortest route by distance may be slow if it is jammed, so drivers can arrive late. Adding live journey times as the edge weights, instead of distances, would fix this at the cost of collecting traffic data.
Q9. Explain why a function that returns the largest item in a list should state a precondition.
Worked solution to Q9
An empty list has no largest item, so the function cannot return a sensible answer. Stating the precondition that the list is not empty tells callers to check this, so the function itself can stay simple.
Q10. A cache's hit time is 2 ms and its miss time is 50 ms. Using the derivation, find the hit rate needed for an average of 10 ms.
Worked solution to Q10
The hit rate needed is (t_miss − T) ÷ (t_miss − t_hit), which is (50 − 10) ÷ (50 − 2) = 40 ÷ 48. That is about 0.83, so roughly five requests in six must be hits.
Q11. Jobs of 8, 7, 6, 5, 4 and 2 minutes run on three workers. Find the finish time and explain why it is not 32 ÷ 3.
Worked solution to Q11
Longest first gives worker 1 the jobs of 8 and 2, worker 2 those of 7 and 4, and worker 3 those of 6 and 5. The finish time is 11 minutes, not about 10.7, because jobs cannot be split between workers.
Rung 4: Stretch
Q12. A program has three IF ... ELSE decisions in sequence, followed by a CASE statement with four branches. How many paths are there?
Worked solution to Q12
The three decisions give 2³ = 8 paths, and each path then meets the CASE statement and takes one of its four branches. So there are 8 × 4 = 32 paths through the program.
Q13. Explain why memoisation makes the recursive Fibonacci function far faster, and state one cost of it.
Worked solution to Q13
Without a cache, the same values are worked out again and again, so the number of calls grows exponentially. Memoisation stores each value once, so each is computed only once; without it, fib(5) makes 15 calls. The cost is the memory used by the stored values.
Q14. A task is 90% parallel. Explain why 100 cores cannot make it 100 times faster.
Worked solution to Q14
The 10% that cannot run in parallel still takes its full time, however many cores there are. Even if the parallel part took no time at all, the task could only be ten times faster.
Exam practice
Exam technique and worked answer workshop
When a question gives a scenario, every point must name something from it. "Remove the colour of the van, because it does not affect the route" earns marks. "Remove unnecessary details" earns nothing, because it could be said about any problem.
For thinking ahead, list inputs, outputs and preconditions separately and precisely. For concurrency, say which parts are independent and why, and give a drawback as well as a benefit. For calculations, write the formula, substitute and give units.
Extended questions on computational thinking often ask you to discuss how the habits apply to a system. Organise your answer by habit, tie each one to the scenario, and finish with a judgement about which matter most.
Exam question 1 (4 marks · Paper 02 · about 5 minutes)
A council wants a program that plans the route of its bin lorries around the town.
(a) Explain what is meant by abstraction. [2]
(b) Identify two details the program should ignore and one it must keep. [2]
Mark scheme for exam question 1
- B1 removing details that are not needed to solve the problem
- B1 so that the problem is simpler and the important details can be focused on
- B1 two details to ignore, such as the colour of the lorries or the names of the residents
- B1 one detail to keep, such as the road distances, the locations of the bins or one-way streets
Exam question 2 (5 marks · Paper 02 · about 7 minutes)
A subroutine binarySearch(names, target) finds a name in an array of names.
(a) State the inputs and the output of the subroutine. [2]
(b) State one precondition of binarySearch, and explain why it is needed. [2]
(c) Explain one benefit of stating preconditions. [1]
Mark scheme for exam question 2
- B1 inputs: the array of names and the target name
- B1 output: the position of the target, or a value showing it is not present
- B1 the array must be sorted
- B1 because binary search discards half the array by comparing with the middle item, which only works if it is in order
- B1 the subroutine need not check its inputs, so it is simpler and easier to reuse
Exam question 3 (5 marks · Paper 01 · about 7 minutes)
A web server answers a request in 2 ms when the result is in its cache and in 50 ms when it must query a database.
(a) Calculate the average time per request when 90% of requests are cache hits. [3]
(b) Calculate the hit rate needed for an average of 10 ms. [2]
Mark scheme for exam question 3
- M1 0.9 × 2 = 1.8 ms from hits
- M1 0.1 × 50 = 5 ms from misses
- A1 6.8 ms
- M1 (50 − 10) ÷ (50 − 2)
- A1 about 0.83, or 83%
Exam question 4 (5 marks · Paper 02 · about 7 minutes)
A sports club wants a program that lets members book courts, pay online and see their bookings.
(a) Explain how decomposition would help the club's programmers. [2]
(b) Decompose the program into at least three sub-problems, and break one of them down further. [3]
Mark scheme for exam question 4
- B1 breaking the problem into smaller sub-problems that are each easier to solve
- B1 so that parts can be written and tested separately, by different programmers, and reused
- B1 three sub-problems, such as book a court, take payment and show bookings
- B1 one broken down further, such as book a court into choose date, check free and confirm
- B1 the sub-problems are small enough to write as single subroutines
Exam question 5 (6 marks · Paper 02 · about 9 minutes)
A film studio is writing software to render the frames of an animated film on a network of computers. Discuss how thinking concurrently should be applied to this problem, and the benefits and drawbacks of doing so.
Mark scheme for exam question 5
Level 3 (5–6 marks): a balanced discussion that identifies which parts of rendering can run concurrently and which cannot. It gives benefits and drawbacks, each linked to the studio. The answer reaches a justified conclusion. It is well organised and uses technical terms accurately.
Level 2 (3–4 marks): identifies some concurrent parts with a benefit or drawback. The discussion is one-sided or not well linked to the studio.
Level 1 (1–2 marks): some relevant points, such as that it is faster, with little development. The answer may lack structure.
0 marks: no response or no response worthy of credit.
Indicative content:
- each frame can be rendered independently, so frames can be shared between computers
- parts of one frame, such as tiles or layers, may also be processed at once
- steps that depend on each other, such as combining the finished frames into the film, must wait
- the film is finished much sooner, and the studio's hardware is used fully
- the work must be shared out and the results collected, which takes time and network traffic
- frames that take very different times leave some computers idle, so the speed-up is less than the number of computers
- the software is harder to write, test and debug, and a failed computer's frames must be reassigned
- conclusion: rendering is well suited to concurrency because frames are independent, so the benefits outweigh the costs
Annotated model answer: exam question 5
"Each frame of the film can be rendered without knowing about any other frame. So the frames can be shared between the computers and rendered at the same time. Within a frame, separate tiles could also be rendered at once." (Identifies the independent parts, tied to the studio.)
"Some steps cannot be concurrent. Joining the frames into the finished film needs every frame first, so it must wait until rendering is done." (Identifies a dependency.)
"The main benefit is speed: a film that would take months on one computer might take days on hundreds. But sharing out the frames and collecting the results takes time. Some frames, such as explosions, take far longer than others, so some computers sit idle. The speed-up is less than the number of computers." (Benefit and drawback, with a reason.)
"The software is also harder to write and debug, and must cope with a computer failing mid-frame. Even so, because frames are independent, rendering is ideal for concurrency, and the benefits clearly outweigh the costs." (A further drawback and a justified conclusion.)
This answer reaches Level 3 and scores 6 marks. It identifies concurrent and non-concurrent parts, weighs benefits against drawbacks and reaches a judgement grounded in the scenario.
Exam question 6 (5 marks · Paper 02 · about 7 minutes)
A validation program contains five IF ... ELSE statements, one after another.
(a) Calculate how many paths there are through the program. [1]
(b) Explain why testing every path becomes impractical as decisions are added. [2]
(c) A price is valid if it is greater than 0 and no more than 500. Write this condition. [2]
Mark scheme for exam question 6
- B1 2⁵ = 32 paths
- B1 each extra decision doubles the number of paths
- B1 so the number of tests grows exponentially, such as over a million for 20 decisions
- B1 price > 0
- B1 AND price <= 500
Exam question 7 (4 marks · Paper 01 · about 5 minutes)
Six independent jobs take 8, 7, 6, 5, 4 and 2 minutes. They are shared between two processor cores, the longest job first, each going to the core that is free first.
(a) Calculate when the last job finishes. [2]
(b) Calculate the speed-up compared with one core. [1]
(c) Explain why the speed-up is less than 2. [1]
Mark scheme for exam question 7
- M1 core 1 takes 8, 5 and 4; core 2 takes 7, 6 and 2
- A1 17 minutes
- B1 32 ÷ 17, about 1.9
- B1 the jobs cannot be split evenly, so one core is idle while the other finishes
Exam question 8 (6 marks · Paper 02 · about 9 minutes)
Write a function finishTime(jobs, n, k) that takes an array of n job times and returns when the last of k workers finishes. Assume the array is already sorted from longest to shortest, and give each job to the worker with the smallest load.
Mark scheme for exam question 8
- B1 a function header with the three parameters
- B1 an array of k loads, each set to 0
- B1 a loop over all n jobs
- B1 finding the worker with the smallest load
- M1 adding the job's time to that worker's load
- A1 returning the largest load at the end
Annotated model answer: exam question 8
function finishTime(jobs, n, k)
array loads[k]
for w = 0 to k - 1
loads[w] = 0
next w
for i = 0 to n - 1
free = 0
for w = 1 to k - 1
if loads[w] < loads[free] then free = w endif
next w
loads[free] = loads[free] + jobs[i]
next i
largest = loads[0]
for w = 1 to k - 1
if loads[w] > largest then largest = loads[w] endif
next w
return largest
endfunction
The header and the array of zero loads earn the first two marks, and the loop over the jobs earns the third. The inner loop that finds the smallest load earns the fourth. Adding the job to that load earns the method mark, and returning the largest load earns the last.
Connections
Synoptic link
Abstraction is behind the data structures of Arrays, records, stacks and queues and the classes of Object-oriented programming, which hide how they work behind a simple interface. Thinking ahead about preconditions is why binary search in Searching and sorting algorithms needs a sorted list.
Caching appears in hardware too: Processor architecture and performance shows how a processor's cache hides the slowness of main memory, using the same average-time formula. Thinking concurrently connects to multi-core processors there, and to the scheduling of processes in Operating systems and applications.
Synoptic question 1. A processor finds data in its cache in 1 ns and in main memory in 80 ns. With a 97% hit rate, what is the average time to fetch data?
Answer to synoptic question 1
The hits contribute 0.97 × 1 = 0.97 ns and the misses contribute 0.03 × 80 = 2.4 ns. So the average fetch time is 0.97 + 2.4 = 3.37 ns, much closer to the cache's speed than to memory's.
Recap
Recap and next step
- Abstraction removes detail that does not affect the problem, giving an abstract model that is simpler than reality; every model has limits.
- Thinking ahead identifies the inputs, outputs and preconditions before coding, and plans for how the program will change.
- A cache reuses recent results: the average time is h × t_hit + (1 − h) × t_miss. Memoisation and reusable components avoid repeating work.
- Decomposition breaks a problem into sub-problems, drawn as a structure diagram, and dependent steps must be ordered after what they need.
- Thinking logically finds the decision points and their conditions; n two-way decisions in sequence give 2ⁿ paths.
- Thinking concurrently finds independent parts that can run at once; the slowest worker sets the time, so the speed-up is less than the number of workers.
Next chapter: Programming constructs turns these habits into code, with sequence, selection and iteration.
For your exam board
OCR A Level Computer Science (H446): this chapter covers section 2.1, Elements of computational thinking, in Component 02: thinking abstractly, thinking ahead (inputs, outputs, preconditions, caching and reusable components), thinking procedurally, thinking logically and thinking concurrently.
AQA A Level Computer Science (7517): the theory of computation section covers abstraction and automation, including representational abstraction, procedural and functional abstraction, data abstraction, problem abstraction and decomposition, assessed on Paper 1.