Chapter 15: Thinking abstractly
Second layer of abstraction – pathfinding Now that the problem has been represented in a more simplified manner, the task of performing the pathfinding will commence. At this stage, no consideration has been given to how the grid (level) will be displayed or stored. In Chapter 8 you will be introduced to Dijkstra’s and A* pathfinding algorithms. It is worth reading over these algorithms to help give context to the following explanation. As we have abstracted the method travelToDestination, we can pick and choose which pathfinding algorithm we use. In fact, should we wish, we could swap them at a later date. For this example we will use Dijkstra’s algorithm: 1
Add the start position to a list with a counter initialised to zero.
2
For each valid move: take the current counter and add one to it
b
add the move to the list if it is not there already with the new counter.
e
3
a
Move on to the next item in the list until the destination has been reached.
10
13
14
15
16
17
18
19
1
9
12
13
14
15
16
17
2
8
11
12
13
14
15
3
7
10
11
5 6 7 8 9
18
19
20
21
16
17
18
19
20
14
15
16
17
18
19
15
16
17
18
6
7
8
9
10
13
14
5
6
7
8
9
12
13
18
19
4
5
6
7
8
11
12
19
20
3
4
5
6
7
10
11
20
21
2
3
4
5
6
7
8
9
10
21
22
1
2
3
4
5
6
7
8
9
22
23
1
2
3
4
5
6
7
8
24
25
1
2
3
4
5
6
7
8
12
13
10 (0,10) 11
21 (13,0)
Sa m
4
20
pl
0
0
10
11
Figure 15.8: Grid with all path costs shown.
Figure 15.8 shows the calculated distance costs for each square based on the proposed algorithm. The shortest path takes 22 steps and there is more than one solution with the same number of steps (path cost). At this level of abstraction it is not important which path is chosen, as all solutions are a potential shortest path. This algorithm takes an undirected approach to pathfinding and is not the most efficient way of doing it. We could, for example, use A* pathfinding using the Manhattan heuristic (see Chapter 8). The key point to note here is that our choice of algorithm will only impact the efficiency of the solution, not whether it is correct. The ability to swap algorithms in and out without changing the solution is one of the key ideas behind abstraction.
Activity 15.1 You have been asked to create a flash card program to help A Level students study for their exams. Design a possible solution using computational methods.
© Cambridge University Press 2017 The third party copyright material that appears in this sample may still be pending clearance and may be subject to change.
303