OCR A-Level · thinka 原創模擬試題

2025 OCR A-Level Computer Science - H446 模擬試題連答案詳解

Thinka Jun 2025 OCR A Level-Style Mock — Computer Science - H446

280 分300 分鐘2025
An original Thinka practice paper modelled on the structure and difficulty of the Jun 2025 OCR A Level Computer Science - H446 paper. Not affiliated with or reproduced from OCR.

H446/01 — unsectioned paper

Answer every question. No calculator. Extended evaluative responses are asterisked. Structured questions with compulsory subparts.
42 題目 · 142 分
題目 1 · Code writing, completion or correction
3 分
A teacher stores the test scores for a class in a zero-indexed array named scores. The function meanAtLeast is intended to return the mean of only those scores that are greater than or equal to the value of the parameter limit. If no score is greater than or equal to limit, the function must return 0.

The function contains three errors.

```
01 function meanAtLeast(scores, limit)
02 total = 0
03 count = 0
04 for i = 0 to scores.length
05 if scores[i] > limit then
06 total = total + scores[i]
07 count = count + 1
08 endif
09 next i
10 return total / count
11 endfunction
```

Identify the line number of each of the three errors and write a corrected version of that line.

You may answer in pseudocode or in a high-level programming language of your choice.

Line number: ........ Correction: ................................................
Line number: ........ Correction: ................................................
Line number: ........ Correction: ................................................

[3]
查看答案詳解

解題

Line 4: the array is zero-indexed, so the last valid index is scores.length - 1. The loop as written accesses scores[scores.length], which is out of bounds. Correct to: for i = 0 to scores.length - 1.

Line 5: the specification requires scores greater than or equal to limit, but the condition uses > and so omits scores equal to limit. Correct to: if scores[i] >= limit then.

Line 10: if no score qualifies, count is 0 and the division fails (division by zero). The function must return 0 in that case. Correct to: if count == 0 then return 0 else return total / count endif (or equivalent, placed in place of line 10).

評分準則

1 mark per correct error identified AND corrected (max 3):
- Line 4: loop upper bound must be scores.length - 1 (e.g. for i = 0 to scores.length - 1). Allow scores.length - 1 expressed as a while loop with i < scores.length. DNA changing the start to 1.
- Line 5: comparison changed to >= (e.g. if scores[i] >= limit then). Allow NOT (scores[i] < limit).
- Line 10: guard against count being 0 so that 0 is returned, e.g. if count == 0 then return 0 else return total / count endif. Allow the check being inserted before line 10 provided line 10 only executes when count > 0. Allow count > 0 test.

The line number and a correct correction are both required for the mark. Award the mark for a correct correction if the line number is clearly implied by the position of the amendment. Do not award a mark where the correction is given for a line that was already correct. Max 3.
題目 2 · Code writing, completion or correction
4 分
A weather station stores hourly temperature readings in a one-dimensional array named temps. The first element has index 0.

The function highReadings is intended to return the number of readings in temps that are strictly greater than the value of the parameter limit.

Complete the function by writing the missing code for each of the four gaps, labelled (1) to (4). Answers may be written in pseudocode or in a high-level programming language.

```
function highReadings(temps, limit)
count = ........(1)........
for i = 0 to ........(2)........
if temps[i] ........(3)........ limit then
count = count + 1
endif
next i
return ........(4)........
endfunction
```

Gap (1): ____________________
Gap (2): ____________________
Gap (3): ____________________
Gap (4): ____________________

[4]
查看答案詳解

解題

The counter must start at zero so that only readings above the limit are counted. The loop must visit every index from 0 to the last valid index, which is temps.length - 1 because the array is 0-indexed and the for loop is inclusive of both ends. The comparison must be strictly greater than, so the operator is >. The function returns the counter, count.

Completed function:

function highReadings(temps, limit)
count = 0
for i = 0 to temps.length - 1
if temps[i] > limit then
count = count + 1
endif
next i
return count
endfunction

評分準則

1 mark per correct gap, maximum 4:
- (1) 0 [1]
- (2) temps.length - 1 [1]. Allow any equivalent expression, e.g. len(temps) - 1 or the literal final index if the array size is stated. Do not accept temps.length (it causes an out-of-range index) or temps.length - 2.
- (3) > [1]. Do not accept >=, < or ==.
- (4) count [1]. Do not accept i or temps[i].
Allow equivalent syntax from any high-level language. Each gap is marked independently; there is no follow through.
題目 3 · Code writing, completion or correction
5 分
A teacher stores the test scores of a class in a one-dimensional array named scores. The function averageAbove is intended to return the mean of all scores that are greater than or equal to a given value, limit. If no score meets this condition, the function must return 0.

The function contains three errors.

1 function averageAbove(scores, limit)
2 total = 0
3 count = 0
4 for i = 0 to scores.length
5 if scores[i] > limit then
6 total = total + scores[i]
7 count = count + 1
8 endif
9 next i
10 return total / count
11 endfunction

Identify the line number of each of the three errors and write a corrected version of that line (or lines). You may use pseudocode or program code.

Error 1, line number: ........ Correction: ..............................

Error 2, line number: ........ Correction: ..............................

Error 3, line number: ........ Correction: ..............................

[5]
查看答案詳解

解題

Line 4: the loop is inclusive of both ends, so scores[scores.length] is outside the array. The upper bound must be scores.length - 1.
Line 5: the specification says 'greater than or equal to', so > must become >=.
Line 10: if count is 0 the division fails (division by zero). A check is needed so that 0 is returned when no score qualifies.
Corrected code:
function averageAbove(scores, limit)
total = 0
count = 0
for i = 0 to scores.length - 1
if scores[i] >= limit then
total = total + scores[i]
count = count + 1
endif
next i
if count == 0 then
return 0
endif
return total / count
endfunction

評分準則

Error 1 (2 marks):
- Identifies line 4 (1)
- Upper bound corrected to scores.length - 1 (or < scores.length with equivalent loop) (1)
Error 2 (1 mark):
- Line 5 comparison changed to >= (1) (identification and correction required together)
Error 3 (2 marks):
- Identifies line 10 / the division by count when count is 0 (1)
- Adds a selection that returns 0 when count == 0 (before the division) and otherwise returns total / count (1)
Allow the zero check placed before line 10 as a new line. Allow the identification mark for a correction placed at the correct location without the line number quoted. Do not accept changes that alter correct lines, or a correction that returns 0 after the division has been attempted. Maximum 5.
題目 4 · Code writing, completion or correction
5 分
A program uses a stack to store the names of up to five files that a user has opened most recently. The stack is implemented as a class using an array. The attribute top holds the index of the item at the top of the stack. When the stack is empty, top is -1.

1 class FileStack
2 private items = array[5]
3 private top = -1
4
5 public function push(name)
6 if top == ........[A]........ then
7 return false
8 endif
9 top = ........[B]........
10 items[top] = name
11 return true
12 endfunction
13
14 public function pop()
15 if ........[C]........ then
16 return ""
17 endif
18 name = items[top]
19 top = ........[D]........
20 return name
21 endfunction
22 endclass

(a) Complete the four gaps, labelled [A] to [D], in the code. You may use pseudocode or program code.

[A] ......................................
[B] ......................................
[C] ......................................
[D] ......................................

[4]

(b) Write a method isEmpty for the class FileStack. The method must return true if the stack contains no items and false otherwise.

..............................................................

[1]
查看答案詳解

解題

(a) The array has five elements, indexed 0 to 4, so the stack is full when top is 4. Pushing first increments top, then stores the item. Popping is not possible when top is -1 (empty stack). After reading the item, top is decremented.
(b) public function isEmpty()
return top == -1
endfunction

評分準則

(a) One mark per correct gap:
- [A] 4 or items.length - 1 or items.length - 1 equivalent (1). Do not accept 5.
- [B] top + 1 (1). Allow top++ style equivalents only if the result is assigned correctly.
- [C] top == -1 (1). Allow top < 0, or a call to isEmpty() if consistent with (b).
- [D] top - 1 (1). Do not accept top = top - 1 written inside the gap if it duplicates the assignment on line 19 and makes the line invalid.
(b) 1 mark for a correctly formed method that returns true when top == -1 and false otherwise, e.g. return top == -1 (1). Allow an if/else version returning true/false. Do not accept a method that outputs rather than returns the value.
Maximum 5.
題目 5 · Description or explanation
2 分
A procedure named addBonus is called as follows:

score = 40
addBonus(score)
print(score)

The procedure header is:

procedure addBonus(byRef points)

Explain what would happen to the value stored in score if the parameter were passed byVal instead of byRef. [2]
查看答案詳解

解題

With byVal, the procedure receives a copy of the value 40. Changes to points affect only the copy, which is discarded when the procedure ends. The variable score therefore keeps its original value of 40. With byRef, the change would alter score itself.

評分準則

- A copy of the value of score is passed to the procedure / the procedure works on a local copy (1)
- so score is not changed by the procedure / still holds 40 after the call (1)

Allow: the original variable is not altered.
Do not accept: 'the value is not passed' or 'the program crashes'.
Max 2.
題目 6 · Description or explanation
2 分
A programmer stores 5000 unsorted customer reference numbers in an array. They propose using a binary search to find a given reference number.

Explain why a binary search cannot be used on the array in its current state. [2]
查看答案詳解

解題

Binary search compares the target with the middle item and discards one half of the list. This only works if the items are in order, so that the target must lie in the retained half. In an unsorted array the target could be in the discarded half, so the search could fail to find an item that is present.

評分準則

- Binary search requires the data to be sorted / in order (1)
- because the midpoint comparison is used to discard half of the data; in unsorted data the item could be in the discarded half / the result would be unreliable (1)

Allow: a linear search would be needed instead (not credited alone).
Do not accept: 'binary search is slower' or 'the array is too large'.
Max 2.
題目 7 · Description or explanation
2 分
A computer has less RAM than the total size of the programs that a user wishes to run at the same time. The operating system uses virtual memory to allow this.

Describe how virtual memory allows the programs to run. [2]
查看答案詳解

解題

The operating system reserves an area of secondary storage to act as additional memory. Sections (pages) of programs that are not currently in use are moved out of RAM to this area, freeing space in RAM. When a moved page is needed, it is swapped back into RAM, so only the parts of programs in use need to be in RAM at one time.

評分準則

- Part of secondary storage / the hard disk is used as an extension of RAM (1)
- Pages / sections of programs not currently needed are swapped out of RAM and swapped back in when required (1)

Allow: 'swap space' or 'page file'.
Do not accept: 'RAM is made bigger' without reference to secondary storage.
Max 2.
題目 8 · Description or explanation
2 分
A stack is implemented using an array named data and an integer variable top. The variable top holds the index of the item at the top of the stack, and is -1 when the stack is empty.

Describe the steps needed to carry out a pop operation on this stack. [2]
查看答案詳解

解題

First check top != -1, because popping an empty stack is an underflow error. Then copy the value held at index top in data, decrement top by 1 so that the next item becomes the top, and return the copied value.

評分準則

- Check the stack is not empty / top is not -1 (1)
- Return the item at data[top] and decrement top by 1 (1)

Allow: steps in either order for the second point provided the item is read before it is lost.
Do not accept: setting top to 0 or deleting the whole array.
Max 2.
題目 9 · Description or explanation
3 分
A programmer writes a procedure that updates a player's score in a quiz program. The procedure is shown below.

01 procedure addBonus(byRef score, byVal bonus)
02 score = score + bonus
03 bonus = 0
04 endprocedure
05
06 total = 40
07 extra = 10
08 addBonus(total, extra)

Describe the difference between passing a parameter by value and passing a parameter by reference. Refer to the variables total and extra in your answer. [3]
查看答案詳解

解題

The parameter bonus is passed by value, so the procedure receives a copy of the value of extra. Setting bonus to 0 on line 03 changes only the copy, so extra is still 10 after the call. The parameter score is passed by reference, so it refers to the same memory location as total. Line 02 therefore changes total itself, and total is 50 after the call.

評分準則

Award 1 mark for each point, maximum 3:
- By value: a copy of the value is passed to the procedure / the procedure works on its own copy (1)
- ...so changing it (bonus = 0) does not change the original variable; extra remains 10 (1)
- By reference: the address of / a pointer to the original variable is passed, so the parameter refers to the same memory location (1)
- ...so changes made in the procedure affect the original variable; total becomes 50 (1)

Allow 'alias' for reference. Do not accept 'by value cannot be changed' without reference to the original being unaffected. Do not accept answers that only define the terms without any reference to total or extra for the application mark; a maximum of 2 marks is available if neither variable is referred to.
題目 10 · Description or explanation
4 分
A programmer writes a procedure called addBonus that receives a score and increases it by 10.

procedure addBonus(score)
score = score + 10
endprocedure

points = 50
addBonus(points)
print(points)

The parameter is passed by value.

(a) State the value that is output when this program is run. [1]

(b) Describe what happens to the variable points and the parameter score when addBonus is called. [2]

(c) Describe one change that would make the program output 60. [1]
查看答案詳解

解題

Passing by value copies the value 50 into the local parameter score. The addition changes only the copy, which is discarded when the procedure ends. points stays 50. Passing by reference gives the procedure access to the original variable, so the change affects points and 60 is output.

評分準則

(a) 50 (1)
(b) Max 2:
- The value of points (50) is copied into score (1)
- score becomes 60 / is changed, but only locally within the procedure (1)
- points is not altered / keeps the value 50 (1)
(c) Pass score by reference / declare the parameter as byRef score (1). Allow: returning the new value from a function and assigning it to points; making points global and modifying it directly. DNA: just 'use a different variable'.
題目 11 · Description or explanation
4 分
A shop stores 1000 product codes in an array. The codes are held in ascending order. A binary search is used to find whether a code is present.

(a) Describe how a binary search finds a given code in the array. [3]

(b) State the Big O time complexity of a binary search. [1]
查看答案詳解

解題

Binary search repeatedly halves the search area by comparing the target with the midpoint of a sorted list. This needs at most about 10 comparisons for 1000 items, giving logarithmic complexity, O(log n).

評分準則

(a) Max 3:
- Find the middle item of the (sorted) array (1)
- Compare the target with the middle item; if equal the item is found (1)
- If the target is smaller, discard the middle and everything above it / if larger, discard the middle and everything below it (1)
- Repeat with the remaining half until the item is found or no items remain (1)
(b) O(log n) (1). Allow O(log2 n). DNA O(n) or O(n log n).
題目 12 · Description or explanation
4 分
A text editor stores each change a user makes in a stack so that the most recent change can be undone.

(a) Describe how the stack behaves when the user makes a change and then selects undo. [2]

(b) The stack is implemented using an array of size 5 and a pointer called top. Describe what the program should do before adding a new change to the stack, and explain why. [2]
查看答案詳解

解題

A stack is last in, first out, so push adds at the top and pop removes the latest change. With a fixed-size array, pushing when full would exceed the array bounds, so the full condition must be tested first.

評分準則

(a) Max 2:
- A change is pushed / added to the top of the stack (1)
- Undo pops / removes the item from the top, which is the most recent change (LIFO) (1)
(b) Max 2:
- Check whether the stack is full / top points to the last position of the array (1)
- To avoid stack overflow / an error from adding beyond the array bounds / overwriting data (1)
Allow: increment top then store the value as part of the push description.
題目 13 · Description or explanation
4 分
A computer has less physical memory than the total needed by the programs that are running. The operating system uses virtual memory and paging to cope with this.

(a) Describe what is meant by paging. [2]

(b) Explain why the computer may become noticeably slower when too many programs are open. [2]
查看答案詳解

解題

Paging splits programs into equal-sized pages so only the needed pages sit in RAM, the rest being on disk as virtual memory. If too many programs compete for RAM, pages are repeatedly swapped in and out; because secondary storage is far slower than RAM, performance drops.

評分準則

(a) Max 2:
- Memory / programs are divided into fixed-size blocks called pages (frames in RAM) (1)
- Pages not currently needed are stored on secondary storage and loaded into RAM when required (1)
(b) Max 2:
- There is not enough RAM, so pages are swapped between RAM and secondary storage frequently / thrashing (1)
- Secondary storage is much slower than RAM, so the processor spends time waiting for pages to load (1)
DNA: 'the CPU overheats'.
題目 14 · Diagram, table or algorithm trace
3 分
A programmer stores the lengths of eight cable offcuts, in centimetres, in a sorted array named `data`. The array is indexed from 0.

| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| data | 4 | 9 | 15 | 22 | 31 | 38 | 47 | 56 |

The following algorithm searches the array. The variable `target` has the value 47.

```
01 low = 0
02 high = 7
03 found = false
04 while low <= high AND found == false
05 mid = (low + high) DIV 2
06 if data[mid] == target then
07 found = true
08 elseif data[mid] < target then
09 low = mid + 1
10 else
11 high = mid - 1
12 endif
13 endwhile
```

Complete the trace table for this algorithm. Each row represents one pass through the loop. Record the values of `low`, `high` and `mid` at the moment line 05 has just been executed, and the value of `found` after line 12 has been executed. The first row has been completed for you.

| Pass | low | high | mid | data[mid] | found |
|---|---|---|---|---|---|
| 1 | 0 | 7 | 3 | 22 | false |
| 2 | | | | | |
| 3 | | | | | |

[3]
查看答案詳解

解題

Pass 1: mid = 3, data[3] = 22 < 47, so low = 4.
Pass 2: low = 4, high = 7, mid = (4 + 7) DIV 2 = 5, data[5] = 38 < 47, so low = 6. found remains false.
Pass 3: low = 6, high = 7, mid = (6 + 7) DIV 2 = 6, data[6] = 47 == target, so found = true. The loop then ends.

| Pass | low | high | mid | data[mid] | found |
|---|---|---|---|---|---|
| 1 | 0 | 7 | 3 | 22 | false |
| 2 | 4 | 7 | 5 | 38 | false |
| 3 | 6 | 7 | 6 | 47 | true |

評分準則

- 1 mark: pass 2 low = 4, high = 7 and mid = 5 (all three correct)
- 1 mark: pass 3 low = 6, high = 7 and mid = 6 (all three correct)
- 1 mark: data[mid] and found correct in both rows 2 and 3 (38, false, 47, true)

Maximum 3.

Allow follow through (FT) from an incorrect mid in the data[mid] column, using the candidate's own mid value and the array above, and in the later low/high/found values where they follow correctly from the candidate's earlier values.
Accept 'F'/'T' or 0/1 for found.
Do not accept a row marked as correct if any of its three marked values is missing.
題目 15 · Diagram, table or algorithm trace
4 分
1 A program stores nine whole numbers in a one-dimensional array named stock, in ascending order. The array is indexed from 0.

stock = [3, 8, 12, 17, 21, 26, 34, 40, 55]

The following algorithm performs a binary search for the value target.

01 low = 0
02 high = 8
03 found = false
04 while low <= high AND found == false
05 mid = (low + high) DIV 2
06 if stock[mid] == target then
07 found = true
08 elseif stock[mid] < target then
09 low = mid + 1
10 else
11 high = mid - 1
12 endif
13 endwhile

The algorithm is run with target set to 26.

Complete the trace table below to show the values of low, high, mid and stock[mid] each time line 06 is reached. Add rows as necessary. Then state the final value of mid.

| Iteration | low | high | mid | stock[mid] |
|---|---|---|---|---|
| 1 | 0 | 8 | | |
| 2 | | | | |
| 3 | | | | |

Final value of mid: ........................ [4]
查看答案詳解

解題

Iteration 1: low = 0, high = 8, mid = 8 DIV 2 = 4, stock[4] = 21. 21 < 26 so low = 5.
Iteration 2: low = 5, high = 8, mid = 13 DIV 2 = 6, stock[6] = 34. 34 > 26 so high = 5.
Iteration 3: low = 5, high = 5, mid = 5, stock[5] = 26. Equal, so found = true and the loop ends.
Final value of mid is 5.

評分準則

- Iteration 1: mid = 4 and stock[mid] = 21 (1)
- Iteration 2: low = 5, high = 8 (1)
- Iteration 2: mid = 6 and stock[mid] = 34 (1)
- Iteration 3: low = 5, high = 5, mid = 5, stock[mid] = 26 AND final value of mid stated as 5 (1)

Allow follow through from an incorrect mid in a previous row for the following low/high/mid values, provided the algorithm is applied correctly. Do not accept the final answer given as 26 (this is the value, not the index). Max 4.
題目 16 · Diagram, table or algorithm trace
4 分
2 A binary search tree is built by inserting the following values, one at a time, in the order shown. The tree is initially empty.

45, 28, 61, 33, 17, 52, 70

(a) Draw the binary search tree that results. [2]

(b) State the order in which the nodes are visited in a post-order traversal of the tree. [2]
查看答案詳解

解題

45 becomes the root. 28 < 45 goes left. 61 > 45 goes right. 33 < 45, > 28 so right child of 28. 17 < 28 so left child of 28. 52 > 45, < 61 so left child of 61. 70 > 61 so right child of 61.
Post-order visits left subtree, right subtree, then the node: left subtree of 28 gives 17, 33, 28; right subtree of 61 gives 52, 70, 61; then root 45.

評分準則

(a)
- Root 45 with 28 as left child and 61 as right child (1)
- 17 and 33 as left and right children of 28, and 52 and 70 as left and right children of 61 (1)
Allow follow through for a tree with structure consistent with the BST rule if one value is misplaced (max 1).

(b)
- Left subtree visited before right subtree, with each node after its children (1)
- 17, 33, 28, 52, 70, 61, 45 (1)
Award follow through on the candidate's tree from (a) for a correct post-order traversal of that tree (1 mark for the correct method; 2 if fully correct). Max 4 in total.
題目 17 · Diagram, table or algorithm trace
4 分
3 The recursive function mystery is shown below.

01 function mystery(n)
02 if n == 0 then
03 return 0
04 elseif n MOD 2 == 0 then
05 return n + mystery(n - 1)
06 else
07 return mystery(n - 1) - 1
08 endif
09 endfunction

The statement print(mystery(5)) is executed.

Complete the table to show the value returned by each call to mystery. Work from the call with the smallest argument upwards.

| Call | Value returned |
|---|---|
| mystery(0) | |
| mystery(1) | |
| mystery(2) | |
| mystery(3) | |
| mystery(4) | |
| mystery(5) | |

State the value that is output. [4]
查看答案詳解

解題

mystery(0) = 0 (base case). mystery(1) = mystery(0) - 1 = -1. mystery(2) = 2 + mystery(1) = 1. mystery(3) = mystery(2) - 1 = 0. mystery(4) = 4 + mystery(3) = 4. mystery(5) = mystery(4) - 1 = 3. Output: 3.

評分準則

- mystery(0) = 0 and mystery(1) = -1 (1)
- mystery(2) = 1 and mystery(3) = 0 (1)
- mystery(4) = 4 (1)
- mystery(5) = 3 and output stated as 3 (1)

Award follow through from an earlier incorrect value where the correct rule is applied to it. Max 4.
題目 18 · Diagram, table or algorithm trace
4 分
4 A security light circuit has three inputs, A, B and C. The output Q is described by the Boolean expression below.

Q = \u00ac(A \u0245 B) \u0245 (B \u02c5 C)

Complete the truth table for this expression. Columns P and R are provided for intermediate working.

| A | B | C | P = \u00ac(A \u0245 B) | R = B \u02c5 C | Q |
|---|---|---|---|---|---|
| 0 | 0 | 0 | | | |
| 0 | 0 | 1 | | | |
| 0 | 1 | 0 | | | |
| 0 | 1 | 1 | | | |
| 1 | 0 | 0 | | | |
| 1 | 0 | 1 | | | |
| 1 | 1 | 0 | | | |
| 1 | 1 | 1 | | | |

[4]
查看答案詳解

解題

P is the NAND of A and B: 0 only when A and B are both 1, so 1,1,1,1,1,1,0,0. R is B OR C: 0,1,1,1,0,1,1,1. Q = P AND R row by row: 0,1,1,1,0,1,0,0.

評分準則

- Column P fully correct: 1,1,1,1,1,1,0,0 (1)
- Column R fully correct: 0,1,1,1,0,1,1,1 (1)
- Column Q correct for P AND R: 0,1,1,1,0,1,0,0 (2); award 1 mark if only one or two rows are incorrect

Award follow through for Q from incorrect P or R columns. Max 4.
題目 19 · Extended evaluative response
9 分
1 * A software team is writing a program for a museum. The program stores exhibits in a hierarchical catalogue. Each category can contain exhibits and further sub-categories, to any depth. The program must calculate the total number of exhibits held within any given category, including all of its sub-categories.

A developer proposes a recursive subroutine. A second developer argues that an iterative solution should be used.

Discuss whether a recursive or an iterative approach is more suitable for this program.

You should include:
- how each approach would work for this catalogue
- the benefits and drawbacks of each approach, referring to the program described
- a justified conclusion.

[9]
查看答案詳解

解題

Recursive approach: a subroutine countExhibits(category) starts with the exhibits directly in the category and then calls itself for each sub-category, adding the returned totals. The base case is a category with no sub-categories, which returns its own exhibit count. Each call has its own local variables held on the call stack.

Iterative approach: a loop with an explicit stack or queue of categories still to be processed. Pop a category, add its exhibit count to a running total, push its sub-categories, and repeat until the stack is empty.

Benefits of recursion: matches the self-similar structure of the catalogue, so the code is short, easy to read and easier to maintain; depth need not be known in advance. Drawbacks: each call adds a stack frame, so a very deep catalogue could cause stack overflow; function call overhead makes it slower; it is harder to trace and debug.

Benefits of iteration: no risk of stack overflow from call depth, less memory overhead, usually faster. Drawbacks: needs an explicit stack structure, so the code is longer and harder to understand, and more likely to contain errors.

Conclusion: museum catalogues have limited depth, so recursion's drawbacks are small and its clarity is valuable; recursion is more suitable. A justified alternative is acceptable.

評分準則

Level 3 (7-9 marks): Thorough knowledge of both recursion and iteration, accurately applied to the catalogue throughout. Benefits and drawbacks of both approaches are discussed in balance, with reasoned evaluation leading to a fully justified conclusion. Few or no errors.
Level 2 (4-6 marks): Good knowledge of both approaches with some application to the catalogue. Some benefits and drawbacks given, but evaluation may be unbalanced or the conclusion only partly justified.
Level 1 (1-3 marks): Basic knowledge of recursion and/or iteration, with little or no reference to the catalogue. Points listed, with no real evaluation or conclusion.
0 marks: No creditworthy response.

Indicative content (not exhaustive):
- Recursion: subroutine calls itself for each sub-category; base case is a category with no sub-categories; totals combined as calls return
- Iteration: loop with explicit stack/queue of unprocessed categories; running total
- Recursion matches the hierarchical structure / depth unknown; short and readable code
- Recursion: stack frames per call, risk of stack overflow for deep nesting; slower due to call overhead; harder to debug
- Iteration: less memory, no stack overflow, faster; but longer, more complex code needing an explicit stack
- Conclusion with justification linked to the expected depth of the catalogue, maintainability or memory
Allow either conclusion if justified. Do not accept a conclusion with no justification above Level 2. Missing base case described as 'recursion stops' alone should not be credited as a separate point.
題目 20 · Extended evaluative response
9 分
2 * A weather charity stores 2 000 000 temperature readings in an array. New readings are added to the array several times a day, and the readings must be sorted into ascending order before analysis. Users also frequently search the sorted array for a particular reading.

The charity is choosing between a bubble sort and a merge sort for sorting, and between a linear search and a binary search for searching.

Discuss the suitability of these algorithms for the charity.

You should include:
- how each of the sorting and searching algorithms works
- the time and space complexity of each algorithm, using Big O notation
- a justified recommendation of which algorithms the charity should use.

[9]
查看答案詳解

解題

Bubble sort: repeatedly compares adjacent items and swaps them if out of order, making passes until a pass has no swaps. Time \(O(n^2)\) in the worst case, space \(O(1)\). For 2 000 000 items this is of the order of \(4 \times 10^{12}\) operations, which is impractical.

Merge sort: divide and conquer. The array is repeatedly split in half until single items remain, then the sublists are merged in order. Time \(O(n \log n)\), about 42 000 000 operations for this data. Space \(O(n)\) for the temporary lists.

Linear search: checks each item in turn until the target is found or the end is reached. Time \(O(n)\), space \(O(1)\). Works on unsorted data.

Binary search: requires sorted data. Compares the target with the middle item and discards half of the remaining data each time. Time \(O(\log n)\), about 21 comparisons for 2 000 000 items; space \(O(1)\) iteratively.

Recommendation: the data is large, is sorted repeatedly and searched often, so merge sort and binary search are most suitable. The extra memory of merge sort is acceptable. Because new readings are added, the array must be kept sorted (or re-sorted) for binary search to remain valid. Linear search would only be justified if the data were small or rarely searched.

評分準則

Level 3 (7-9 marks): Accurate and detailed description of all four algorithms with correct complexities. Reasoning is applied to the size of the data set, the repeated sorting and the frequent searching. Both time and space trade-offs are evaluated, and a fully justified recommendation is made. Few or no errors.
Level 2 (4-6 marks): Reasonable description of most algorithms and some correct complexities. Some application to the scenario. Evaluation partial, or the recommendation only partly justified.
Level 1 (1-3 marks): Basic description of one or more algorithms or isolated complexities, little application to the scenario, and no or minimal recommendation.
0 marks: No creditworthy response.

Indicative content (not exhaustive):
- Bubble sort: adjacent comparisons and swaps over repeated passes; O(n^2) time; O(1) space
- Merge sort: split into halves, merge in order (divide and conquer); O(n log n) time; O(n) space
- Linear search: check each item in order; O(n); works on unsorted data
- Binary search: needs sorted data; halves the search area each time; O(log n)
- Application: 2 000 000 items makes O(n^2) impractical; frequent searches favour O(log n); new readings added mean data must be re-sorted/kept sorted
- Trade-off: merge sort's extra memory vs speed
- Justified recommendation, e.g. merge sort and binary search
Allow 'n squared' and 'n log n' written in words. Do not accept 'bubble sort is slow' without reference to complexity or data size as a Level 3 point. Allow an alternative recommendation (e.g. linear search for small or unsorted data) only if justified.
題目 21 · Extended evaluative response
12 分
1* A hospital uses one multi-tasking server to run three kinds of process at the same time:

- a patient-monitoring process that must react to sensor data within a fixed number of milliseconds
- short database look-up requests from nurses, each needing a very small amount of processor time
- a nightly back-up process that needs a large amount of processor time but has no urgent deadline

The systems administrator is deciding which scheduling algorithm the operating system should use. The options being considered are round robin, shortest job first and a multi-level feedback queue.

Discuss the suitability of these scheduling algorithms for the server. You should include:

- how each algorithm decides which process runs next
- the benefits and drawbacks of each algorithm when applied to the processes described
- the role of the operating system in switching between processes, including the use of interrupts
- a justified conclusion stating which algorithm you would recommend.

[12]
查看答案詳解

解題

Round robin: each process receives a fixed time slice in turn from a queue; when the slice expires a timer interrupt occurs, the ISR saves the process state (registers, PC) and the next process is loaded. Benefits: fair, no starvation, simple, short look-ups get a turn quickly. Drawbacks: monitoring process has no priority so may wait behind many others and miss its deadline; context-switch overhead if the slice is small; the back-up is repeatedly interrupted.

Shortest job first: the process with the smallest estimated run time is chosen next. Benefits: look-ups complete quickly and average waiting time is minimised. Drawbacks: needs estimates of run time; the long back-up could be starved while short jobs keep arriving; it does not consider deadlines, so the monitoring process is not guaranteed to run promptly.

Multi-level feedback queue: several queues of differing priority; new processes enter the highest queue; a process that uses its whole time slice moves down a queue, while processes that block for I/O stay high. Benefits: the monitoring process can be given top priority; short look-ups finish in the upper queues; the back-up drifts to the lowest queue and runs when the others are idle. Drawbacks: more complex to implement and tune; the back-up may be delayed for a long time unless processes are promoted after waiting (ageing).

Operating system role: the scheduler decides which ready process gets the processor. A timer interrupt (or an I/O or sensor interrupt) is detected at the end of the fetch-decode-execute cycle; the interrupt service routine runs, the current process's register contents are stored in its process control block, and the scheduler loads the state of the chosen process so it resumes. A high-priority sensor interrupt can pre-empt a lower-priority process.

Conclusion: multi-level feedback queue is best because it combines priority for the time-critical monitoring process with quick completion of short jobs and eventual completion of the back-up.

評分準則

Extended response, 12 marks, levels of response. Award the level from the overall quality of the reasoning, then position the mark within the level. Indicative content is not exhaustive.

Indicative content (AO1 knowledge):
- Round robin: fixed time slice, processes served in turn, pre-emption by timer interrupt.
- Shortest job first: shortest (estimated) run time chosen next.
- Multi-level feedback queue: several queues with priorities; processes move between queues depending on behaviour; each queue may use a different algorithm.
- Scheduler selects the next process; interrupt causes the ISR to run; registers/PC saved and restored (context switch); interrupts are checked at the end of the fetch-decode-execute cycle.
- Allow priority-based interrupts pre-empting lower-priority work.

Indicative content (AO2 application to the hospital server):
- Round robin: fair to look-ups; monitoring process not guaranteed to meet its deadline; back-up repeatedly interrupted; context-switch overhead.
- Shortest job first: look-ups favoured; back-up may starve; run times must be estimated; no deadline handling.
- Multi-level feedback queue: monitoring in the top queue; look-ups finish quickly; back-up in the lowest queue runs when the system is idle; complexity.

Indicative content (AO3 evaluation):
- Weighing the algorithms against the time-critical requirement and starvation risk.
- A justified recommendation (multi-level feedback queue expected; accept any other choice supported by valid reasoning, e.g. round robin with a short slice, but a real-time requirement must be addressed).
- Allow mention of ageing or a real-time operating system as a further point.

Level 3 (10-12 marks): Thorough knowledge of all three algorithms and of the interrupt/context-switch role. Applies knowledge consistently to the three processes. Balanced evaluation of benefits and drawbacks leading to a well-justified conclusion. Reasoning is logical and fully supported. Top of the level: all four checklist bullets addressed with specific, correct detail.

Level 2 (5-9 marks): Good knowledge of at least two algorithms, some correct reference to interrupts or the scheduler. Some application to the context, but not for every process. Some evaluation; the conclusion may be partly justified or the discussion unbalanced.

Level 1 (1-4 marks): Basic knowledge, e.g. a description of one or two algorithms with little accuracy. Limited or generic application to the scenario. Little or no evaluation; any conclusion is unsupported.

0 marks: no creditable response.

Do not accept: definitions that merely restate the algorithm name; confusing scheduling with memory management (paging). Do not award Level 3 if no conclusion is given. No follow through applies to this question; the conclusion is credited for the quality of its justification, not for which algorithm is chosen.
題目 22 · Numerical or bitwise calculation
1 分
Convert the hexadecimal value 7B into denary. [1]
查看答案詳解

解題

7B in hexadecimal: \(7 \times 16 + 11 \times 1 = 112 + 11 = 123\).

評分準則

• 123 (1 mark)
Do not accept 123 with a base subscript other than 10.
題目 23 · Numerical or bitwise calculation
1 分
Show the denary number -45 as an 8-bit two's complement binary integer. [1]
查看答案詳解

解題

45 in 8-bit binary is 00101101. Invert the bits to give 11010010. Add 1 to give 11010011. Check: \(-128 + 64 + 16 + 2 + 1 = -45\).

評分準則

• 11010011 (1 mark)
Do not accept sign and magnitude answers (10101101). Do not accept fewer or more than 8 bits.
題目 24 · Numerical or bitwise calculation
1 分
A programmer applies a mask to the 8-bit pattern 10110110 using the XOR operation with the mask 11110000. State the resulting 8-bit pattern. [1]
查看答案詳解

解題

Compare bit by bit; XOR gives 1 only when the bits differ.
10110110
11110000
--------
01000110

評分準則

• 01000110 (1 mark)
Do not accept the result of AND (10110000) or OR (11110110).
題目 25 · Numerical or bitwise calculation
2 分
A program stores the 8-bit value 11010110 in a register. The program performs an XOR of this value with the mask 01100101. It then performs a logical shift right of two places on the result.

Show the final 8-bit binary value in the register. Use the working area to show your steps.

Working area:



Final value: ........................ [2]
查看答案詳解

解題

Step 1: XOR bit by bit.
11010110 XOR 01100101 = 10110011 (bits differ in positions 1, 3, 4, 7, 8 from the left, giving 1,0,1,1,0,0,1,1).
Step 2: Logical shift right by two places: drop the two least significant bits (11) and insert two 0s at the left.
10110011 >> 2 = 00101100.
Final value: 00101100 (2C in hexadecimal).

評分準則

- 1 mark (method/accuracy): correct result of the XOR, 10110011 (may be shown in working only).
- 1 mark (accuracy): correct logical shift right of two places applied to the XOR result, giving 00101100.

Follow through: award the second mark for a correct two-place logical shift right of an incorrect 8-bit XOR result shown in the working area.
Allow: the final answer given without working for both marks if it is 00101100.
Do not accept: an answer of fewer than 8 bits, e.g. 101100, unless leading zeros are clearly implied; an arithmetic shift or a shift in the wrong direction.
題目 26 · Numerical or bitwise calculation
6 分
A weather station stores each reading as an 8-bit binary value. Negative values are stored using two's complement.

(a) Convert the denary value -45 into an 8-bit two's complement binary integer. Show your working. [2]

(b) The station adds the two 8-bit two's complement integers shown below.

01101110
+ 00110111

Calculate the 8-bit result of this addition. State what has occurred and explain why. [2]

(c) The 8-bit value 10110110 is processed in two steps.

Step 1: a bitwise XOR is applied with the mask 11110000.
Step 2: a logical shift right of two places is applied to the result of Step 1.

Give the 8-bit value after Step 1 and after Step 2. [2]
查看答案詳解

解題

(a) 45 in binary is 00101101. Invert the bits: 11010010. Add 1: 11010011.
(b) 01101110 is 110 and 00110111 is 55. Adding the bits gives 10100101. The sign bit is now 1, so the result would be read as -91, but 110 + 55 = 165, which exceeds 127. Overflow has occurred.
(c) Step 1: 10110110 XOR 11110000 = 01000110. Step 2: shifting 01000110 right by two places and filling with zeros gives 00010001.

評分準則

(a) Max 2
- 1 mark: correct method, e.g. 45 = 00101101 and invert/add 1 (or 256 - 45); allow for a correct intermediate such as 11010010.
- 1 mark: 11010011.
- Award both marks for the correct answer without working.

(b) Max 2
- 1 mark: 10100101.
- 1 mark: overflow identified, with a valid reason, e.g. the result 165 is outside the range -128 to 127 / two positive numbers have produced a result with sign bit 1 (negative).
- Do not accept 'carry' alone. Do not award the reason mark without 'overflow' or an equivalent description.

(c) Max 2
- 1 mark: 01000110 after Step 1.
- 1 mark: 00010001 after Step 2.
- FT: award the Step 2 mark for a correct logical right shift by two of the candidate's Step 1 value, provided that value is 8 bits.
題目 27 · Short comparison
2 分
A programmer passes a variable to a procedure. The procedure changes the value of its parameter.

Compare passing a parameter by value with passing a parameter by reference. Refer to the effect on the original variable in your answer. [2]
查看答案詳解

解題

When a parameter is passed by value, the procedure receives a copy of the data, so any change is made to the copy only and the original variable keeps its value. When a parameter is passed by reference, the procedure receives a reference (the memory location) to the original variable, so any change made inside the procedure is also seen in the original variable.

評分準則

Max 2. One mark for each matching statement:
- By value: a copy of the value is passed / the original variable is not changed by the procedure (1)
- By reference: the address / a reference to the original variable is passed, so the original variable is changed by the procedure (1)

Allow: 'the original value is overwritten' for by reference.
Do not accept: statements that only describe one method with no contrast, unless both methods are covered. Do not accept 'by reference copies the variable'.
A response that gives only the two descriptions without mention of the effect on the original variable can earn a maximum of 1 mark.
題目 28 · Short comparison
4 分
A programmer needs a subroutine that calculates the sum of the digits of a positive integer. For example, the sum of the digits of 4721 is 14.

The programmer can write the subroutine using recursion or using iteration.

Compare the use of recursion with the use of iteration for this subroutine.

You should refer to how each approach repeats the calculation and to the use of memory. [4]
查看答案詳解

解題

Recursive version (pseudocode):

function digitSum(n)
if n < 10 then
return n
else
return (n MOD 10) + digitSum(n DIV 10)
endif
endfunction

Iterative version:

function digitSum(n)
total = 0
while n > 0
total = total + (n MOD 10)
n = n DIV 10
endwhile
return total
endfunction

The recursive version repeats by calling itself with n DIV 10 until the base case n < 10 is met. The iterative version repeats using a while loop which ends when n reaches 0. Each recursive call is stored on the call stack with its own parameters and return address, so memory use grows with the number of digits. The iterative version only needs the variables n and total, so memory use is constant. The recursive version is usually shorter and closer to the mathematical definition; the iterative version is usually faster as there is no call overhead.

評分準則

Max 4. Award one mark per point, up to 2 marks for each approach, or for matched comparison points.

Repetition:
- Recursion repeats by the subroutine calling itself (with a smaller/modified argument) (1)
- ... until a base case/stopping condition is met (1)
- Iteration repeats using a loop (for/while/do...until) (1)
- ... until a loop condition becomes false/is met (1)

Memory:
- Recursion creates a new stack frame for each call (holding parameters/return address/local variables) (1)
- ... so memory use increases with the number of digits/depth of recursion; risk of stack overflow (1)
- Iteration reuses the same variables so memory use is constant/lower (1)

Other valid points (max 1): recursive code is shorter/more elegant; recursion has function-call overhead so is slower.

Allow 'function calls itself'. Do not accept 'recursion is faster' or 'iteration is more efficient' without a reason. Do not accept a description of only one approach for more than 2 marks. Comparison points may be paired in a table; a pair of matched statements earns 2 marks.
題目 29 · Short comparison
4 分
A school stores the 50 000 scores recorded in a quiz website in an array. The scores must be sorted into ascending order.

Compare the use of an insertion sort with the use of a merge sort for this task.

You should refer to the time complexity and the memory requirements of each algorithm. [4]
查看答案詳解

解題

Insertion sort takes each item in turn and shifts it left into its correct position in the sorted part of the array. In the worst and average cases this needs about \(n^2\) comparisons, so the time complexity is \(O(n^2)\). It works in the original array so it needs only constant extra memory, \(O(1)\).

Merge sort repeatedly divides the array into halves and merges the sorted halves. It has \(O(n \log n)\) time complexity in all cases, but the merge step needs extra arrays so it needs \(O(n)\) additional memory.

For 50 000 items, \(n^2\) is about 2.5 billion operations, compared with roughly 800 000 for \(n \log n\), so merge sort is much faster at the cost of more memory.

評分準則

Max 4. One mark per point.

Time complexity:
- Insertion sort is \(O(n^2)\) (polynomial) in the worst/average case (1)
- Merge sort is \(O(n \log n)\) (1)
- Merge sort is faster/scales better for large data sets such as 50 000 items; insertion sort becomes slow (1)
- Insertion sort is \(O(n)\) in the best case (already sorted data) (1)

Memory:
- Insertion sort is in place / needs no (significant) additional array, \(O(1)\) extra space (1)
- Merge sort needs additional arrays/space for the sub-lists when merging, \(O(n)\) (1)

Allow 'quadratic' for \(O(n^2)\) and 'linearithmic' for \(O(n \log n)\). Allow 'uses more RAM' for extra memory. Do not accept 'merge sort is faster' without reference to complexity or data size, unless a different mark point is credited. Each comparison point must be stated for both algorithms or as a clear contrast; a single-algorithm statement earns 1 mark only if the contrast is implied.
題目 30 · Short identification or recall
1 分
A procedure named showTotal is called with a variable passed to it. When the procedure changes the value of its parameter, the value of the original variable in the calling program also changes.

Identify the method of parameter passing being used. [1]
查看答案詳解

解題

If changing the parameter alters the caller's original variable, the procedure must have received a reference to the variable's memory location rather than a copy of its value. The method is therefore passing by reference.

評分準則

- By reference / byRef (1)

Allow: 'pass by address'.
Do not accept: 'by value', 'global variable'.
題目 31 · Short identification or recall
1 分
State the name of the standard searching algorithm that repeatedly compares the target with the middle item of a sorted list and discards half of the remaining items each time. [1]
查看答案詳解

解題

Comparing with the middle item of a sorted list and halving the search space on each comparison describes a binary search. It has logarithmic time complexity, \(O(\log n)\).

評分準則

- Binary search (1)

Allow: 'binary chop'.
Do not accept: 'linear search', 'divide and conquer' on its own.
題目 32 · Short identification or recall
2 分
A procedure is called with an argument that is a variable named total.

State two differences in what happens when total is passed by value compared with when it is passed by reference. [2]
查看答案詳解

解題

Passing by value gives the subroutine its own copy of the data, so changes are local. Passing by reference gives access to the original memory location, so changes affect the caller's variable.

評分準則

Any two from (1 mark each):
- By value, a copy of the value is passed; by reference, the address/reference of the variable is passed
- By value, changes inside the procedure do not alter the original variable; by reference, they do
- By value, the original variable is protected/unaffected; by reference, the original can be modified
Do not accept answers that describe only one method. Max 2.
題目 33 · Short identification or recall
2 分
A programmer writes a recursive function.

State two features that the function must contain so that it will terminate correctly. [2]
查看答案詳解

解題

Without a stopping condition, or without progress towards it, the function would call itself indefinitely and cause a stack overflow.

評分準則

- A base case / terminating condition that returns without a further recursive call (1)
- A recursive call (to itself) using modified argument(s) that progress towards the base case (1)
Allow 'stopping condition'. Do not accept 'a loop'. Max 2.
題目 34 · Short identification or recall
2 分
A binary search is used to find a value in an array of 1 000 000 items.

State the time complexity of a binary search using Big O notation, and state one condition that the array must meet before the search can be used. [2]
查看答案詳解

解題

Each comparison halves the remaining search space, giving logarithmic time complexity. The halving only works if the data is ordered.

評分準則

- O(log n) / logarithmic (1)
- The data/array must be sorted / in order (1)
Allow O(log2 n). Do not accept O(n) or 'ascending only' being required as the sole detail unless sorted is implied. Max 2.
題目 35 · Short identification or recall
2 分
An empty stack has the values 4, 9 and 2 pushed onto it in that order. A single pop operation is then performed.

(a) State the value returned by the pop operation. [1]
(b) State the value that is now at the top of the stack. [1]
查看答案詳解

解題

A stack is last in, first out. The last value pushed, 2, is removed first, leaving 9 at the top.

評分準則

(a) 2 (1)
(b) 9 (1)
Follow through: award (b) if the candidate's (a) is a value from the list and (b) is the correct next top for that answer only where consistent with LIFO behaviour. Max 2.
題目 36 · Short identification or recall
2 分
A school database has a Student table and a Form table. The Student table includes the field FormID.

Identify the type of key that FormID is in the Student table, and state its purpose. [2]
查看答案詳解

解題

FormID in Student refers to the primary key of Form, so it is a foreign key. It creates the relationship and supports referential integrity.

評分準則

- Foreign key (1)
- Links/relates the Student table to the Form table by matching the primary key of Form / enforces referential integrity (1)
Do not accept 'primary key' or 'secondary key'. Max 2.
題目 37 · Short identification or recall
2 分
A processor receives an interrupt while a program is running.

State what is meant by an Interrupt Service Routine (ISR), and state when the processor checks for interrupts in the fetch-decode-execute cycle. [2]
查看答案詳解

解題

After finishing the current instruction, the processor checks for interrupts of higher priority. If one is present, the current register contents are saved and the ISR is executed.

評分準則

- A (section of) code/subroutine that is executed to handle/respond to a specific interrupt (1)
- Checked at the end of each fetch-decode-execute cycle / after the current instruction has completed (1)
Do not accept 'at the start of the cycle'. Max 2.
題目 38 · Short identification or recall
2 分
Use De Morgan's laws to write an expression that is equivalent to

NOT (P AND Q)

that does not use brackets. Then state the name of the logic gate whose output is the same as NOT (P AND Q). [2]
查看答案詳解

解題

De Morgan: NOT (P AND Q) = (NOT P) OR (NOT Q). The expression NOT (P AND Q) is the output of a NAND gate.

評分準則

- NOT P OR NOT Q (any accepted notation, e.g. ¬P ˅ ¬Q, P-bar + Q-bar) (1)
- NAND (1)
Do not accept expressions that retain brackets around AND. Max 2.
題目 39 · Short identification or recall
2 分
Represent the denary value -5 as an 8-bit binary integer using two's complement. [2]
查看答案詳解

解題

+5 is 00000101. Invert the bits to give 11111010, then add 1 to give 11111011.

評分準則

- Correct 8-bit representation 11111011 (2)
If incorrect, award 1 mark for 00000101 shown as the starting value with bits inverted (11111010), or for a correct method of invert and add 1 with one arithmetic slip. Max 2.
題目 40 · Short identification or recall
3 分
A desktop computer is running a spreadsheet while a document is being sent to a printer.

(a) State what is meant by an interrupt. [1]

(b) State two different events that could cause an interrupt to be generated in this computer. [2]
查看答案詳解

解題

(a) An interrupt is a signal from hardware or software that tells the processor an event needs attention, so the processor pauses its current task and runs an Interrupt Service Routine.
(b) Two events from different sources, for example a key press on the keyboard and the printer reporting that it is out of paper.

評分準則

(a) 1 mark: a signal (sent to the processor) indicating that an event requires attention / that causes the current task to be paused. Allow: causes an ISR to run. Do not accept: 'a error' or 'the computer stops' with no reference to a signal or to attention.
(b) 1 mark per valid, distinct event, max 2. e.g. a key press / mouse click; printer out of paper or job complete; a hardware failure; a timer expiring; a software error such as division by zero. Do not accept two answers that are the same event worded differently. Do not accept vague answers such as 'the printer'.
題目 41 · Short identification or recall
3 分
A research team uses a computer with a graphics processing unit (GPU) to run a simulation of weather patterns. The simulation is not used to produce images.

(a) State two characteristics of a GPU that make it suitable for this task. [2]

(b) Identify one other non-graphics use of a GPU. [1]
查看答案詳解

解題

(a) A GPU contains very many simple cores, so the same calculation can be applied to a large number of data values simultaneously. Weather simulation repeats similar calculations across many points, which suits this.
(b) For example training machine learning models.

評分準則

(a) 1 mark per point, max 2:
- has many cores / thousands of processing units
- can process many data items at the same time / parallel processing
- optimised for repeated, similar calculations (e.g. matrix or floating point operations)
- high throughput of data
Do not accept: 'faster' or 'better' with no reason. Do not accept 'higher clock speed'.
(b) 1 mark for one valid use, e.g. machine learning / neural network training; data mining; password cracking; cryptocurrency mining; physics or scientific modelling. Do not accept 'gaming' or 'video editing' (graphics uses).
題目 42 · Short identification or recall
4 分
1 A programmer writes a procedure that adds a bonus to a player's score in a game. The program is written in the OCR pseudocode style.

```
01 procedure addBonus(byRef score, byVal bonus)
02 score = score + bonus
03 bonus = 0
04 endprocedure
05
06 points = 10
07 extra = 5
08 addBonus(points, extra)
09 print(points)
10 print(extra)
```

(a) State the value output by line 09 and the value output by line 10. [2]

line 09: ........................

line 10: ........................

(b) State two benefits of using local variables, rather than global variables, inside a subroutine such as addBonus. [2]
查看答案詳解

解題

(a) The parameter score is passed by reference, so the change made in the procedure alters points: points becomes 10 + 5 = 15. The parameter bonus is passed by value, so the procedure works on a copy; setting it to 0 does not change extra, which remains 5. (b) Local variables exist only inside their subroutine, so they cannot be altered unintentionally elsewhere, names can be reused without clashes, and the memory they use is released when the subroutine finishes.

評分準則

(a) Maximum 2
- 15 for line 09 (1)
- 5 for line 10 (1)
Allow each mark independently. Do not accept 0 for line 10.

(b) Maximum 2, one mark per valid benefit
- Cannot be changed accidentally / unintentionally by other parts of the program, so fewer side effects (1)
- Same identifier can be reused in different subroutines without conflict (1)
- Memory is released when the subroutine ends / uses less memory (1)
- Subroutine is self-contained so it is easier to reuse, test and debug (1)
Do not accept 'faster' or 'easier' without a reason. Do not accept two statements that make the same point.

準備好測試自己了嗎?

將這些筆記轉化為考試練習。獲取此課題的無限量AI題目,即時批改及詳細解析。

練習此課題

H446/02 — 甲部

Answer every question. No calculator. Extended evaluative responses are asterisked. Structured questions with compulsory subparts.
29 題目 · 102 分
題目 1 · Code writing, completion or correction
2 分
A weather station stores one rainfall reading, in millimetres, for each day of a month in a one-dimensional array named readings.

The function countWet should return the number of days on which the reading is greater than the value passed in as limit.

Complete the two gaps, labelled (A) and (B), in the pseudocode below. You may answer in pseudocode or in a high-level programming language.

```
function countWet(readings, limit)
total = 0
for i = 0 to readings.length - 1
if readings[i] ........ (A) ........ then
........ (B) ........
endif
next i
return total
endfunction
```

(A) ................................................

(B) ................................................

[2]
查看答案詳解

解題

The loop visits every element of the array. The condition must test whether the current reading is strictly greater than limit, so gap (A) is > limit. When the condition is true the counter total must increase by one, so gap (B) is total = total + 1. For example, with readings [0, 5, 2, 9] and limit 2, the function returns 2.

評分準則

(A) 1 mark: > limit
- Allow > limit in any equivalent notation for a high-level language.
- Do not accept >= limit or == limit.

(B) 1 mark: total = total + 1
- Allow total += 1 or total++ or equivalent increment by one.
- Do not accept total = 1 or total + 1 on its own (no assignment).

Maximum 2 marks. Each gap is marked independently.
題目 2 · Code writing, completion or correction
4 分
A programmer writes a function to count how many readings in a 0-indexed array are greater than or equal to a given limit. The function contains four errors.

```
01 function countAtLeast(readings, limit)
02 total = 0
03 for i = 1 to readings.length
04 if readings[i] > limit then
05 count = count + 1
06 endif
07 next i
08 return total
09 endfunction
```

Identify each of the four errors by line number and write the corrected line. Pseudocode or program code is accepted.

Line number: ______ Corrected line: ______
(repeat for each error) [4]
查看答案詳解

解題

The counter used on line 05 is 'count', so line 02 must initialise count (not total) and line 08 must return count. The array is 0-indexed, so the loop must run from 0 to readings.length - 1 (line 03). The specification says 'greater than or equal to', so line 04 needs >= rather than >.

評分準則

One mark per correct error identified with a valid correction, maximum 4:
- Line 02: count = 0 (initialise count instead of total) (1)
- Line 03: for i = 0 to readings.length - 1 (start at 0 and end at length - 1; both parts needed) (1)
- Line 04: if readings[i] >= limit then (1)
- Line 08: return count (1)
Allow equivalent corrections, e.g. renaming count to total on line 05 together with the return on line 08 stays as total (award the marks for lines 02 and 08 together if the renamed variable is consistent across lines 02, 05 and 08 and the line 05 change is shown). Allow readings.length - 1 written as an equivalent expression, e.g. 'for i = 0 to readings.length-1'. Do not accept a correct line number with an unchanged line. Do not accept a rewrite of the whole function without line numbers unless each change is clearly identifiable. If more than four lines are given, mark only the first four.
題目 3 · Code writing, completion or correction
4 分
A recursive function searches a sorted array of strings, indexed from 0, using a binary search. It returns the index of the target, or -1 if the target is not present.

```
function findName(names, target, low, high)
if ____________(1)____________ then
return -1
endif
mid = (low + high) DIV 2
if names[mid] == target then
return mid
elseif names[mid] < target then
return findName(names, target, ____(2)____, high)
else
return findName(names, target, low, ____(3)____)
endif
endfunction
```

(a) Complete gaps (1), (2) and (3) in the code. [3]

(b) Write a statement that searches the whole of an array called club, which holds 12 names, for the name "Rowan" and stores the result in a variable called position. [1]
查看答案詳解

解題

The base case is an empty search range, which occurs when low > high. If the middle item is less than the target, the target must lie in the upper half, so the new low is mid + 1. Otherwise it lies in the lower half, so the new high is mid - 1. The array has 12 items indexed 0 to 11, so the initial call uses low = 0 and high = 11 (or club.length - 1).

評分準則

(a) Maximum 3:
- (1) low > high (1) Allow high < low. Do not accept low >= high.
- (2) mid + 1 (1)
- (3) mid - 1 (1)
(b) Maximum 1:
- position = findName(club, "Rowan", 0, 11) (1) Allow club.length - 1 or 12 - 1 for 11. Both 0 and the upper bound must be correct, and the argument order must match the function definition. Do not accept 12 as the high value.
題目 4 · Code writing, completion or correction
5 分
A library system stores the number of times each book was borrowed in a one-dimensional array named `loans`. The array is 0-indexed and `loans.length` gives the number of elements it contains.

The function `lastIndexOf` is intended to return the index of the last element in the array that is equal to the value `target`. If no element is equal to `target`, the function must return -1.

```
01 function lastIndexOf(loans, target)
02 position = -1
03 for i = [GAP 1] to [GAP 2]
04 if loans[i] [GAP 3] target then
05 position = [GAP 4]
06 endif
07 next i
08 return [GAP 5]
09 endfunction
```

Complete the function by writing the missing code for each of the five gaps. You may answer in pseudocode or in a high-level programming language.

GAP 1: ........................
GAP 2: ........................
GAP 3: ........................
GAP 4: ........................
GAP 5: ........................ [5]
查看答案詳解

解題

The loop must visit every index from 0 to loans.length - 1 inclusive (the for loop is inclusive of both ends). Each element is tested for equality with target using ==. When a match is found, position is overwritten with the current index i, so after the loop position holds the index of the last match. If there is no match, position keeps its initial value of -1. The function then returns position.

評分準則

1 mark per gap, maximum 5:
- GAP 1: 0 (allow any equivalent expression evaluating to 0)
- GAP 2: loans.length - 1 (allow loans.length - 1 written as a correct equivalent, e.g. len(loans)-1). DNA loans.length alone, as this would access an index outside the array.
- GAP 3: == (allow = if used as the comparison in the candidate's chosen language; allow 'equals'). DNA != or any other operator.
- GAP 4: i
- GAP 5: position

Allow correct alternative loop forms only if all gaps remain consistent with a working function (e.g. loop running from loans.length - 1 down to 0 is not accepted here, as the structure of the code is given). Each gap is marked independently; no follow through is needed.
題目 5 · Code writing, completion or correction
6 分
A weather station stores hourly temperature readings, in whole degrees, in a zero-indexed array named readings. The array always contains at least one value.

A programmer is writing a function named longestRise. It returns the length of the longest run of consecutive readings in which each reading is strictly greater than the reading immediately before it. A single reading counts as a run of length 1.

The function is incomplete. The gaps are labelled (1) to (5).

```
01 function longestRise(readings)
02 best = 1
03 current = 1
04 for i = 1 to readings.length - 1
05 if readings[i] ______(1)______ readings[i - 1] then
06 current = ______(2)______
07 else
08 current = ______(3)______
09 endif
10 if current > best then
11 best = ______(4)______
12 endif
13 next i
14 return ______(5)______
15 endfunction
```

1. (a) Complete the function by writing the missing code for each of the gaps (1) to (5). Pseudocode or program code may be used. [5]

(1) ......................................
(2) ......................................
(3) ......................................
(4) ......................................
(5) ......................................

(b) The completed function is called with the following array.

readings = [4, 6, 7, 3, 5, 8, 9, 10, 2]

State the value returned by the function. [1]
查看答案詳解

解題

The loop compares each reading with the one before it. If it is greater, the current run grows by one; otherwise a new run of length 1 starts. Whenever current exceeds best, best is updated. After the loop, best holds the longest run.

(a) (1) > (2) current + 1 (3) 1 (4) current (5) best

(b) The runs are 4,6,7 (length 3), 3,5,8,9,10 (length 5) and 2 (length 1). The longest is 5, so the function returns 5.

評分準則

(a) One mark per correct gap, maximum 5:
- (1) > (strictly greater than). Do not accept >= . Allow readings[i - 1] < readings[i] only if the whole condition is rewritten consistently; otherwise DNA.
- (2) current + 1. Allow current = current + 1 or equivalent (e.g. current += 1).
- (3) 1. DNA 0.
- (4) current.
- (5) best. DNA current.
Allow any equivalent syntax that a competent programmer could interpret. Each gap is marked independently.

(b) 1 mark: 5.
Award follow through for (b) only if the candidate's trace of their own answer to (a) is correct for the logic they wrote; otherwise award the mark for 5 only.
題目 6 · Description or explanation
2 分
A procedure called resetScore is passed an integer variable named score.

Describe the effect on the original variable if score is passed to resetScore by reference rather than by value. [2]
查看答案詳解

解題

By reference, the procedure receives the address of the original variable, so any assignment to score inside resetScore changes the caller's variable. By value, a copy is made, so the original is unaffected.

評分準則

Max 2:
- The parameter refers to / is the address of the original variable (1)
- Any change made in the procedure persists in / alters the original variable after the procedure ends (1)
Allow: contrast with by value where a copy is changed and the original is unchanged, for either mark.
DNA: 'the variable is global' without reference to the original being changed.
題目 7 · Description or explanation
2 分
A program must search a list of 1 000 000 customer surnames that is already stored in alphabetical order.

Explain why a binary search is more suitable than a linear search for this task. [2]
查看答案詳解

解題

Binary search needs sorted data, which is already the case. Each comparison discards half of the remaining items, giving logarithmic time complexity, about 20 comparisons for 1 000 000 items, whereas a linear search may need up to 1 000 000.

評分準則

Max 2:
- The data is already sorted, which binary search requires (1)
- Binary search halves the remaining items on each comparison / has O(log n) complexity (1)
- Linear search may need to check every item / has O(n) complexity, so binary search needs fewer comparisons (1)
Allow: 'faster' only when supported by one of the above points.
題目 8 · Description or explanation
2 分
A stack is implemented using a one-dimensional array and a variable named top that holds the index of the item at the top of the stack.

Describe the steps needed to carry out a pop operation on this stack. [2]
查看答案詳解

解題

First check that the stack is not empty (top is not -1). Then read the value at array[top] to return, and decrement top so that the next item becomes the top.

評分準則

Max 2:
- Check that the stack is not empty / underflow check (1)
- Return / copy the item at position top AND decrement top by 1 (1)
Allow: the order of reading and decrementing if the correct item is returned.
DNA: removing items from the bottom of the stack.
題目 9 · Description or explanation
2 分
A program finds a route through a maze by moving along one path at a time.

Describe how backtracking would be used by this program when it reaches a dead end. [2]
查看答案詳解

解題

On meeting a dead end, the program undoes its most recent moves until it reaches the last decision point that still has an unexplored option, and then tries that option instead.

評分準則

Max 2:
- Return / go back along the path to the most recent decision point / junction (1)
- Choose / try a different, previously untried route from there (1)
Allow: 'abandon the failed path and try another' for one mark only.
DNA: restarting from the beginning of the maze.
題目 10 · Description or explanation
2 分
A database has a table Pupil and a table Club. The table Pupil contains the field ClubID, which is the primary key of Club.

Explain how referential integrity is maintained between these two tables. [2]
查看答案詳解

解題

ClubID in Pupil acts as a foreign key. The database system only accepts a ClubID value in Pupil if the same value exists in Club, and prevents deletion of a Club record that is still referenced, so no orphan records occur.

評分準則

Max 2:
- Values in the foreign key field (ClubID in Pupil) must match an existing primary key value in Club (1)
- A record in Club cannot be deleted / changed while records in Pupil refer to it, so no orphan records exist (1)
Allow: 'cascading delete' for second mark.
題目 11 · Description or explanation
2 分
An operating system uses a round robin scheduling algorithm.

Describe how this algorithm shares processor time between processes. [2]
查看答案詳解

解題

Processes wait in a queue. The process at the front runs for a fixed time slice (quantum). If it has not finished, it is placed at the back of the queue and the next process is given the processor.

評分準則

Max 2:
- Each process is allocated a fixed time slice / quantum in turn (1)
- An unfinished process is moved to the back of the queue when its time slice ends (1)
Allow: processes finishing early release the processor.
DNA: processes run in order of priority or length.
題目 12 · Description or explanation
2 分
A programmer defines a class Vehicle. A second class, Lorry, inherits from Vehicle.

Explain what is meant by inheritance, using Vehicle and Lorry in your answer. [2]
查看答案詳解

解題

Inheritance allows the subclass Lorry to reuse the attributes and methods defined in the superclass Vehicle without rewriting them, while also defining extra attributes or methods or overriding existing ones.

評分準則

Max 2:
- Lorry (subclass) gains / reuses the attributes and methods of Vehicle (superclass) (1)
- Lorry can have additional attributes / methods of its own or override those from Vehicle (1)
DNA: Vehicle inheriting from Lorry.
題目 13 · Description or explanation
2 分
A programmer writes a program in a high-level language and uses a compiler to translate it.

Describe one difference between how a compiler and an interpreter translate and run a program. [2]
查看答案詳解

解題

A compiler translates the complete source code into an executable file before execution begins, so the program can run without the translator. An interpreter translates and runs the source line by line each time the program is run.

評分準則

Max 2, for one matched difference:
- Compiler translates the whole program before it is run / produces an executable (1)
- Interpreter translates and executes line by line / statement by statement, and does not produce a separate executable (1)
Allow: other valid differences, e.g. errors reported for the whole program versus at the line reached.
Both halves are required for 2 marks.
題目 14 · Description or explanation
2 分
A company uses software that automatically decides whether job applicants are shortlisted.

Describe one ethical concern about using automated decision making in this way. [2]
查看答案詳解

解題

One concern is bias. If the decision rules or training data reflect past discrimination, qualified applicants from particular groups may be unfairly rejected, and the lack of transparency makes it hard to challenge the outcome.

評分準則

Max 2:
- Identifies a valid concern, e.g. bias / discrimination in the rules or training data / lack of transparency or accountability (1)
- Development of the impact on applicants, e.g. suitable applicants unfairly rejected / cannot challenge the decision (1)
DNA: 'it is not fair' without development.
題目 15 · Description or explanation
2 分
A programmer is writing a program to manage bookings for a sports centre. The procedure applyDiscount receives a variable named price and reduces it by ten per cent.

The programmer is deciding whether price should be passed to applyDiscount by value or by reference.

Explain the difference between passing a parameter by value and passing a parameter by reference, using applyDiscount as your example. [2]
查看答案詳解

解題

When passed by value, a copy of the contents of price is given to applyDiscount. Any reduction is made to the copy, so the original price in the calling code keeps its old value. When passed by reference, applyDiscount works on the original variable (it receives its memory location), so the ten per cent reduction is still in effect after the procedure ends.

評分準則

Max 2 from:
- By value: a copy of the value of price is passed to the procedure (1)
- ...so changes made inside applyDiscount do not affect the original variable / the original price is unchanged after the call (1)
- By reference: the address / a pointer to the original variable is passed (1)
- ...so changes made inside applyDiscount alter the original variable / the discounted price is kept after the call (1)

Award 1 mark for the by value description and 1 mark for the by reference description if both are linked to the example. Allow 'reference' described as 'the procedure uses the same variable'.
Do not accept a response that only says 'one is a copy and the other is not' without stating the effect on the original variable.
Do not award marks for definitions that are not applied to price or applyDiscount, apart from one mark maximum for correct general statements.
題目 16 · Description or explanation
3 分
A programmer is writing a procedure that records the scores of players in a quiz game. The procedure receives an array called scores as a parameter and must change the values stored in that array.

Describe the difference between passing a parameter by value and passing a parameter by reference. Refer to the array scores in your answer. [3]
查看答案詳解

解題

Passing by value gives the procedure its own copy of the argument, so any change is made to the copy and the original array is unchanged when the procedure ends. Passing by reference gives the procedure the memory location of the original array, so changes made inside the procedure alter the original array. To change the stored scores, scores should therefore be passed by reference (byRef).

評分準則

Max 3 from:
- By value, a copy of the data/argument is passed to the procedure (1)
- ... so changes made in the procedure do not affect the original/calling variable, e.g. the original scores array stays unchanged (1)
- By reference, the address/memory location of the original variable is passed (1)
- ... so changes made in the procedure change the original data, e.g. the scores array in the calling program is updated (1)
- Application: scores must be passed by reference for the procedure to change its values (1)

Allow 'pointer' for address. Do not accept 'by value cannot be used' or answers that only define the terms without any difference. Maximum 2 marks if the array scores is not referred to.
題目 17 · Description or explanation
3 分
A single-core computer is running a word processor, a music player and a virus scan at the same time. The operating system uses a round robin scheduling algorithm.

Describe how the operating system uses round robin scheduling to share the processor between these three processes. [3]
查看答案詳解

解題

The three processes are held in a ready queue. The process at the front is given the processor for a fixed time slice (quantum). When the time slice ends, an interrupt occurs, the process's state is saved and it is placed at the back of the queue. The next process is then taken from the front and run. This repeats until each process completes, so every process receives an equal share of processor time.

評分準則

Max 3 from:
- Processes are held in a (ready) queue (1)
- Each process is allocated a fixed/equal time slice (quantum) of processor time (1)
- When the time slice expires, an interrupt/timer causes the process to stop, and its state/registers are saved (1)
- ... the process is moved to the back of the queue (1)
- The next process at the front of the queue is then run / this repeats in a cycle until processes complete (1)
- A process that finishes before its slice ends is removed from the queue / leaves early (1)

Do not accept 'processes run at the same time'. Do not accept 'the most important process runs first'.
題目 18 · Description or explanation
5 分
A programmer writes a procedure to apply a voucher to the price of an item in an online shop. The program uses pseudocode.

```
01 procedure applyVoucher(byVal price, byRef basket)
02 price = price - 5
03 basket = basket + price
04 endprocedure
05
06 basket = 0
07 cost = 20
08 applyVoucher(cost, basket)
09 print(cost)
10 print(basket)
```

(a) State the values that are output by lines 09 and 10. [2]

(b) Explain why the value of cost output by line 09 is different from the value of price at the end of the procedure, but the value of basket is not lost when the procedure ends. Your answer must refer to how each parameter is passed. [3]
查看答案詳解

解題

(a) cost is passed by value, so price starts as a copy of 20. Line 02 makes price 15. basket is passed by reference and starts at 0, so line 03 sets basket to 0 + 15 = 15. Line 09 outputs 20 and line 10 outputs 15.

(b) By value: a copy of the value of cost is placed in the local variable price. Changing price alters only the copy, which is discarded when the procedure ends, so cost remains 20. By reference: basket refers to the address of the original variable, so line 03 changes the original and the new value 15 remains after the procedure ends.

評分準則

(a) Max 2
- 20 output by line 09 (1)
- 15 output by line 10 (1)
Allow outputs in the correct order if line numbers are not given. Accept 20 then 15 only.

(b) Max 3
- cost/price is passed by value (1)
- ...so price is a (local) copy of the value / changes affect only the copy, not the original variable cost (1)
- basket is passed by reference, so the procedure receives the address/memory location of the original variable (1)
- ...so changes made to basket inside the procedure change the original variable and persist after the procedure ends (1)
Do not accept 'global' or 'local' as the sole explanation of the difference. Do not accept a bare statement that 'by reference is permanent' without reference to the original variable or its address. Mark the best three points.
題目 19 · Description or explanation
6 分
A programmer is writing a program for a greenhouse. The main program stores the current temperature readings in an array named readings. The programmer writes the following procedure.

1 procedure addOffset(list, offset)
2 for i = 0 to list.length - 1
3 list[i] = list[i] + offset
4 next i
5 endprocedure

The main program contains the statement:

addOffset(readings, 2)

(a) Describe the difference between passing a parameter by value and passing a parameter by reference. [2]

(b) Explain what effect the call addOffset(readings, 2) would have on the array readings if the parameter list is passed by value, and what effect it would have if list is passed by reference. [2]

(c) Describe two benefits of writing the offset calculation as a procedure rather than repeating the code each time it is needed in the main program. [2]
查看答案詳解

解題

(a) With pass by value the subroutine receives a copy of the value, so changes made to the parameter inside the subroutine are lost when it ends and the original variable is unchanged. With pass by reference the subroutine receives the address of the original variable, so changes made inside the subroutine alter the original.
(b) By value: the procedure works on a copy of the array, so readings keeps its original values. By reference: line 3 changes the elements of the original array, so each value in readings is increased by 2.
(c) The code can be reused by calling it many times without rewriting it; a fault or change need only be corrected in one place, which improves maintainability and testing; the main program is shorter and easier to read.

評分準則

(a) Max 2:
- Value: a copy of the data is passed / original not changed by the subroutine (1)
- Reference: the memory address/reference to the original is passed / original can be changed by the subroutine (1)
Do not accept 'value is passed' without reference to a copy. Allow one mark for a correct but undeveloped statement only if both methods are addressed.

(b) Max 2:
- By value: readings is unchanged / copy is altered only (1)
- By reference: all elements of readings are increased by 2 (1)
Allow 'each temperature goes up by 2'. Do not accept 'the array is changed' without stating how.

(c) Max 2, one mark per benefit (benefit must be linked to a reason where indicated):
- Reusable: code written once and called many times (1)
- Maintainable: a change/fix needs to be made in one place only (1)
- Easier to test or debug in isolation (1)
- Main program shorter / more readable (1)
Do not accept 'quicker to run' or 'uses less memory' on their own.
題目 20 · Diagram, table or algorithm trace
2 分
A programmer writes a function to search a sorted array.

```
01 function findItem(values, target)
02 low = 0
03 high = values.length - 1
04 while low <= high
05 mid = (low + high) DIV 2
06 if values[mid] == target then
07 return mid
08 elseif values[mid] < target then
09 low = mid + 1
10 else
11 high = mid - 1
12 endif
13 endwhile
14 return -1
15 endfunction
```

The array `stock` contains the following values. The index of each value is shown above it.

| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| Value | 3 | 8 | 12 | 19 | 25 | 31 | 44 | 58 |

The function is called with the statement `findItem(stock, 31)`.

Complete the trace table below to show the values of the variables each time line 06 is reached. Stop when the function returns a value.

| low | high | mid | values[mid] |
|---|---|---|---|
| 0 | 7 | | |
| | | | |
| | | | |

(You may not need to use every row.) [2]
查看答案詳解

解題

First iteration: low = 0, high = 7, so mid = 7 DIV 2 = 3 and values[3] = 19. 19 is not equal to 31 and is less than 31, so low becomes 4.
Second iteration: low = 4, high = 7, so mid = 11 DIV 2 = 5 and values[5] = 31. This equals the target, so the function returns 5. No third row is needed.

評分準則

- 1 mark: first row completed correctly: mid = 3 and values[mid] = 19.
- 1 mark: second row completed correctly: low = 4, high = 7, mid = 5, values[mid] = 31.

Allow follow through only if the first row is wrong but the second row is consistent with the candidate's own first row. Do not accept extra rows after the row containing 31. Mark each row as a whole. Do not award the second mark if the low value is not 4 (unless following through from a wrong first row).
題目 21 · Diagram, table or algorithm trace
3 分
A program stores the ages of eight members of a club in a 0-indexed array called `ages`. The values are held in ascending order.

```
ages = [4, 9, 15, 22, 31, 40, 58, 63]
target = 15
low = 0
high = ages.length - 1
found = false
while low <= high AND found == false
mid = (low + high) DIV 2
if ages[mid] == target then
found = true
elseif ages[mid] < target then
low = mid + 1
else
high = mid - 1
endif
endwhile
```

Complete the trace table below for the algorithm. Each row represents one iteration of the `while` loop. Record the values of `low` and `high` at the start of the iteration, followed by the values of `mid` and `ages[mid]` calculated during that iteration.

Add rows only if they are needed. Not every row may be required.

| Iteration | low | high | mid | ages[mid] |
|---|---|---|---|---|
| 1 | | | | |
| 2 | | | | |
| 3 | | | | |
| 4 | | | | |

[3]
查看答案詳解

解題

Iteration 1: low = 0 and high = 7, so mid = 7 DIV 2 = 3 and ages[3] = 22. As 22 > 15, high becomes 2.
Iteration 2: low = 0 and high = 2, so mid = 1 and ages[1] = 9. As 9 < 15, low becomes 2.
Iteration 3: low = 2 and high = 2, so mid = 2 and ages[2] = 15. This equals the target, so found becomes true and the loop ends. A fourth iteration is not needed.

評分準則

One mark per correctly completed row (whole row marked together), maximum 3:
- Row 1: 0, 7, 3, 22
- Row 2: 0, 2, 1, 9
- Row 3: 2, 2, 2, 15

Do not award a mark for a row containing any incorrect value. Row 4 must be blank or crossed through; if row 4 contains values, do not award the mark for row 3. Allow follow through only if an earlier row is wrong but the later row is correct for the candidate's previous values (low and high consistent with the algorithm), up to a maximum of 2 marks in that case.
題目 22 · Diagram, table or algorithm trace
4 分
A programmer writes a procedure that sorts a list of whole numbers into ascending order. The pseudocode is shown below.

```
01 procedure arrange(items)
02 size = items.length
03 changed = true
04 rounds = 0
05 while changed == true
06 changed = false
07 rounds = rounds + 1
08 for k = 0 to size - 2
09 if items[k] > items[k + 1] then
10 temp = items[k]
11 items[k] = items[k + 1]
12 items[k + 1] = temp
13 changed = true
14 endif
15 next k
16 endwhile
17 print(rounds)
18 endprocedure
```

The procedure is called with the array `items` holding the values `[4, 6, 2, 5, 1]`.

Complete the trace table below. For each pass of the while loop (lines 05 to 16), write the contents of `items` and the number of swaps made at the end of that pass. Then state the value output by line 17.

| Pass | Contents of items at the end of the pass | Number of swaps |
|------|-------------------------------------------|-----------------|
| 1 | | |
| 2 | | |
| 3 | | |
| 4 | | |
| 5 | | |

Value output by line 17: ............................ [4]
查看答案詳解

解題

Pass 1: 4<6 no swap; 6>2 swap -> 4,2,6,5,1; 6>5 swap -> 4,2,5,6,1; 6>1 swap -> 4,2,5,1,6. 3 swaps.
Pass 2: 4>2 swap -> 2,4,5,1,6; 4<5 no swap; 5>1 swap -> 2,4,1,5,6; 5<6 no swap. 2 swaps.
Pass 3: 2<4 no swap; 4>1 swap -> 2,1,4,5,6; 4<5, 5<6 no swaps. 1 swap.
Pass 4: 2>1 swap -> 1,2,4,5,6; remaining comparisons need no swap. 1 swap.
Pass 5: no swaps, so changed stays false and the loop ends. rounds = 5, which is output by line 17.

評分準則

4 marks in total, one mark per bullet:
- Pass 1 row correct: [4,2,5,1,6] and 3 swaps (both needed) (1)
- Pass 2 row correct: [2,4,1,5,6] and 2 swaps (both needed) (1)
- Passes 3 and 4 rows both correct: [2,1,4,5,6] with 1 swap; [1,2,4,5,6] with 1 swap (1)
- Pass 5 row correct: [1,2,4,5,6] with 0 swaps AND output value 5 (1)

Allow: follow through for the swap counts and final output if the array contents are consistent with an earlier error in the trace (output must equal the number of passes the candidate has shown until a pass with 0 swaps).
Do not accept: array contents written with missing values or in the wrong order for the mark.
DNA: a sixth pass row or an output other than the number of passes completed.
題目 23 · Diagram, table or algorithm trace
5 分
A warehouse system stores the weights, in kilograms, of nine parcels in a one-dimensional array named weights. The values are held in ascending order.

weights = [4, 9, 15, 22, 27, 31, 38, 44, 50]

The array is indexed from 0. The function find searches the array, where n is the number of items in the array.

01 function find(arr, n, target)
02 low = 0
03 high = n - 1
04 steps = 0
05 while low <= high
06 mid = (low + high) DIV 2
07 steps = steps + 1
08 if arr[mid] == target then
09 return mid
10 elseif arr[mid] < target then
11 low = mid + 1
12 else
13 high = mid - 1
14 endif
15 endwhile
16 return -1
17 endfunction

a) The function is called using find(weights, 9, 20).

Complete the trace table below. The first row has been completed for you. Add one row for each further iteration of the while loop, then give the value returned by the function.

| low | high | mid | arr[mid] | steps |
|-----|------|-----|----------|-------|
| 0 | 8 | 4 | 27 | 1 |
| | | | | |
| | | | | |
| | | | | |

Value returned: ........................ [4]

b) State the Big O time complexity of this algorithm in terms of n, in the worst case. [1]
查看答案詳解

解題

Row 1 (given): low 0, high 8, mid 4, arr[4] = 27. 27 > 20, so high = 3.
Row 2: low 0, high 3, mid = 3 DIV 2 = 1, arr[1] = 9, steps 2. 9 < 20, so low = 2.
Row 3: low 2, high 3, mid = 5 DIV 2 = 2, arr[2] = 15, steps 3. 15 < 20, so low = 3.
Row 4: low 3, high 3, mid = 3, arr[3] = 22, steps 4. 22 > 20, so high = 2.
Now low (3) > high (2), so the loop ends and -1 is returned (20 is not present).
The algorithm is a binary search, which halves the search space each iteration, so the complexity is logarithmic: O(log n).

評分準則

a) Maximum 4 marks.
- Row 2 correct: 0, 3, 1, 9, 2 (1 mark; whole row marked together)
- Row 3 correct: 2, 3, 2, 15, 3 (1 mark; whole row marked together)
- Row 4 correct: 3, 3, 3, 22, 4 (1 mark; whole row marked together)
- Value returned is -1 (1 mark)
FT: award follow through for a row if it is correct for the candidate's previous row. Do not accept additional rows after row 4 unless the candidate's earlier error causes them (FT applies). Allow blank cells to be filled with the values only; no need to restate the condition.

b) 1 mark
- O(log n) / O(log2 n) / logarithmic complexity
DNA O(n) or O(n log n) or 'log n' without the O notation if the candidate does not mention complexity at all.
題目 24 · Diagram, table or algorithm trace
7 分
A programmer writes a procedure that sorts an array using an insertion sort. The procedure is shown below. Line numbers are included for reference.

```
01 procedure insertionSort(byRef a)
02 for i = 1 to a.length - 1
03 key = a[i]
04 j = i - 1
05 while j >= 0 AND a[j] > key
06 a[j + 1] = a[j]
07 j = j - 1
08 endwhile
09 a[j + 1] = key
10 next i
11 endprocedure
```

The array `scores` is declared and then passed to the procedure:

```
scores = [7, 3, 9, 2, 5]
insertionSort(scores)
```

1 (a) Complete the trace table below to show the state of the array at the end of each iteration of the `for` loop. The row for i = 1 has been completed for you.

| i | key | Contents of scores at the end of the iteration |
|---|-----|-----------------------------------------------|
| 1 | 3 | [3, 7, 9, 2, 5] |
| 2 | | |
| 3 | | |
| 4 | | |

[4]

1 (b) State the number of times line 06 is executed during the whole of this trace (including i = 1).

[1]

1 (c) The time complexity of insertionSort is described using Big O notation.

(i) State the Big O time complexity of insertionSort in the worst case. [1]

(ii) Describe the initial order of the data that produces this worst case. [1]
查看答案詳解

解題

i = 2: key = 9. a[1] = 7 is not greater than 9, so nothing moves and the array is unchanged: [3, 7, 9, 2, 5].
i = 3: key = 2. 9, 7 and 3 are each greater than 2 so each shifts one place right (three executions of line 06). 2 is placed at index 0: [2, 3, 7, 9, 5].
i = 4: key = 5. 9 and 7 are shifted right (two executions of line 06); 3 is not greater than 5, so the loop stops. 5 is placed at index 2: [2, 3, 5, 7, 9].
Line 06 executions: i=1 gives 1, i=2 gives 0, i=3 gives 3, i=4 gives 2, total 6.
Worst case: every element must be compared with and shifted past every element before it, so the work grows with the square of n: O(n^2). This occurs when the data starts in reverse order.

評分準則

1 (a) [4 marks]
- 1 mark: key column correct for all three rows (9, 2, 5). Do not accept if any key is wrong.
- 1 mark: i = 2 array [3, 7, 9, 2, 5]
- 1 mark: i = 3 array [2, 3, 7, 9, 5]
- 1 mark: i = 4 array [2, 3, 5, 7, 9]
- Each array mark is awarded independently, but the whole array must be correct. Award FT for an array mark if it is a correct application of the algorithm to the candidate's own previous row. Allow arrays written without brackets or commas if clearly in order.

1 (b) [1 mark]
- 6. Award FT from the candidate's own trace table only if the answer is consistent with the shifts shown in it.

1 (c) [2 marks]
- (i) 1 mark: O(n^2). Allow O(n squared), quadratic or polynomial. Do not accept O(n) or O(n log n).
- (ii) 1 mark: data in reverse order / descending order / largest value first. Allow 'in the opposite order to the one required'. Do not accept 'unsorted' or 'random' without further detail.
題目 25 · Extended evaluative response
9 分
*1 A weather-station program stores hourly temperature readings in a one-dimensional array named readings. The array can hold several million values. A programmer must write a subroutine that finds the highest value in the array.

The programmer is considering a recursive approach or an iterative approach. The recursive version is shown below.

01 function findMax(readings, position)
02 if position == readings.length - 1 then
03 return readings[position]
04 else
05 rest = findMax(readings, position + 1)
06 if readings[position] > rest then
07 return readings[position]
08 else
09 return rest
10 endif
11 endif
12 endfunction

Discuss whether the programmer should use a recursive or an iterative approach for this subroutine.

You should include:
- how each approach works, with reference to the code shown
- the advantages and disadvantages of each approach for this task
- a justified conclusion.

[9]
查看答案詳解

解題

Recursive version: findMax calls itself with position + 1 until the base case (line 02) is met at the last element. Each call waits for the result of the next (line 05), so the calls build up on the call stack and values are compared as the calls return. An iterative version would use a loop with a local variable holding the highest value so far, comparing each element once.

Both approaches examine each element once, so time complexity is linear, O(n). The recursive version uses O(n) stack space because one stack frame is created per element; with millions of readings this is likely to cause a stack overflow error. The iterative version uses O(1) extra space and avoids the overhead of repeated subroutine calls. Recursion can be shorter and closer to the mathematical definition of the problem, but here the code is not noticeably easier to follow. Conclusion: use iteration, because the array is very large and there is no benefit from recursion.

評分準則

Indicative content (not exhaustive):

Knowledge / understanding:
- Recursion: a subroutine calls itself with a changed argument until a base case is reached
- Base case in the code is when position is the last index (line 02); the recursive call is on line 05
- Iteration uses a loop (e.g. for/while) and a variable holding the current maximum
- Each recursive call creates a stack frame holding parameters, local variables and the return address

Application to the scenario:
- Several million readings gives several million nested calls; the call stack may overflow
- Both approaches are O(n) in time; the recursive version is O(n) in space, the iterative version O(1)
- Function call overhead makes recursion slower in practice
- Recursive code is short and its structure is clear, but no real benefit for a simple linear scan
- Iterative code is easier to trace/debug for large inputs

Evaluation:
- A reasoned conclusion, e.g. iteration is preferable for this task because of the array size; recursion would be acceptable for small arrays or if the stack depth were limited (e.g. divide and conquer which halves the depth)

Level 3 (7-9 marks): Thorough knowledge of both approaches, accurately linked to the code and the large data size. Advantages and disadvantages are fully developed, with correct reference to stack use and complexity. A justified conclusion follows logically from the points made. Well structured, with no significant errors.

Level 2 (4-6 marks): Good knowledge of recursion and iteration. Some application to the scenario, e.g. mentions stack or memory use for a large array. Some balanced discussion, but the conclusion may be limited or only partly justified.

Level 1 (1-3 marks): Basic, generic statements about recursion and/or iteration with little or no link to the code or scenario. Points may be one-sided or listed. Any conclusion is unsupported.

0 marks: No creditable response.

Allow stack overflow, running out of memory for the call stack. Do not accept 'recursion is slower' without a reason. Do not accept 'iteration uses no memory'. Position within a level is decided by the quality of reasoning.
題目 26 · Extended evaluative response
9 分
*2 A community library holds the records of 200 000 books. Each record contains an ISBN, a title and a shelf location. The records are stored in an array and are currently unsorted. Staff search the records by ISBN many times each day, but new books are added only about once a week.

The library's developer is considering two options:
- Option A: keep the array unsorted and use a linear search for every query.
- Option B: sort the array by ISBN using a merge sort, then use a binary search for every query.

Discuss which option the developer should choose.

You should include:
- how each algorithm works
- a comparison of the time and space complexity of the algorithms, using Big O notation
- the effect of the way the library uses its records
- a justified conclusion.

[9]
查看答案詳解

解題

Linear search checks each record in turn until the ISBN is found or the end is reached: O(n) per search, about 200 000 comparisons in the worst case, no extra space and no need for sorted data.

Merge sort divides the array into halves repeatedly, then merges the sorted halves: O(n log n) time and O(n) extra space. Binary search compares the target with the middle item and discards half of the remaining records each time: O(log n), about 18 comparisons for 200 000 records, but it requires sorted data.

The sort is performed once, so its cost is shared over many searches. With only weekly additions, the array can be re-sorted or new items inserted into position infrequently. If many searches are made each day, the total cost of Option A is far greater. Option A would be better only if very few searches were made, or if the data changed constantly. Conclusion: Option B.

評分準則

Indicative content (not exhaustive):

Knowledge / understanding:
- Linear search: checks items one at a time from the start; works on unsorted data; O(n)
- Binary search: needs sorted data; compares with middle item and discards half; O(log n)
- Merge sort: divide and conquer; splits the list, sorts the parts, merges them; O(n log n) time
- Merge sort needs O(n) additional space; linear and binary searches need O(1) extra space (iterative binary search)

Application to the scenario:
- Sorting is a one-off cost; searching occurs many times a day, so the cost of the sort is spread across many searches
- 200 000 records: linear search up to 200 000 comparisons; binary search around 18
- Weekly additions mean the data is rarely changed, so re-sorting (or inserting) is infrequent and affordable
- Extra memory for the merge sort is acceptable on a modern system / the sort can be run when the system is quiet
- Option A would be preferable if the data changed frequently or there were very few searches

Evaluation:
- A conclusion that is justified using the complexities and the usage pattern

Level 3 (7-9 marks): Accurate and detailed description of all three algorithms. Complexities are correct and are compared. The usage pattern is explicitly used to weigh up the options, with both sides considered. A clear justified conclusion.

Level 2 (4-6 marks): Good knowledge of at least two of the algorithms and some correct use of Big O notation. Some link to the scenario. Limited balance or a conclusion that is only partly justified.

Level 1 (1-3 marks): Basic description of the searches or sort with little or no use of Big O notation or the scenario. Largely unsupported statements.

0 marks: No creditable response.

Allow O(log2 n) for O(log n). Do not accept binary search working on unsorted data. Do not accept 'merge sort is quicker than binary search'. Position within a level is decided by the quality of reasoning.
題目 27 · Short comparison
2 分
A programmer is writing a procedure named adjustScore that receives a player's score from the main program.

Compare passing the score to adjustScore by value with passing the score to adjustScore by reference.

Your answer should describe one difference in how the procedure treats the original variable. [2]
查看答案詳解

解題

When a parameter is passed by value, a copy of the argument is made and the procedure works on that copy, so the original variable keeps its value after the call. When a parameter is passed by reference, the procedure is given the address of the original variable, so any assignment to the parameter changes the original variable in the main program.

評分準則

Max 2 marks, one mark for each point:
- By value: a copy of the value is passed / changes made in the procedure do not affect the original variable (1)
- By reference: the address / location of the original variable is passed / changes made in the procedure do affect the original variable (1)

Allow 'pointer to' or 'reference to' the variable for address.
Do not accept answers that only define the terms without stating the effect on the original variable, e.g. 'by value passes the value'.
A statement that only describes one method scores a maximum of 1 mark unless the contrast with the other method is clear.
題目 28 · Short identification or recall
1 分
A programmer declares a variable inside a procedure so that it can only be used by statements within that procedure.

Identify the term used to describe the scope of this variable. [1]
查看答案詳解

解題

A variable declared inside a subroutine and accessible only within that subroutine has local scope. A global variable would be accessible throughout the program.

評分準則

- Local (1)

Allow: local variable, local scope.
Do not accept: private, global.
題目 29 · Short identification or recall
2 分
A programmer writes a procedure that receives an integer parameter named score. The procedure doubles the value of score.

State two differences in the effect of the procedure on the variable passed to it by the calling program, when the parameter is passed by value compared with when it is passed by reference. [2]
查看答案詳解

解題

When a parameter is passed by value, a copy of the argument's value is made and the procedure doubles only that copy, so the variable in the calling program keeps its original value. When a parameter is passed by reference, the procedure receives the address of the original variable, so doubling score changes the variable in the calling program.

評分準則

Award 1 mark for each point, maximum 2:
- By value: the original variable / value in the calling program is not changed (the procedure changes only a copy) (1)
- By reference: the original variable in the calling program is changed / updated (the procedure uses the memory address of the original) (1)

Allow: by value, a copy of the data is passed; by reference, a pointer / address to the data is passed, as the explanation of the difference.
Do not accept: answers that only say 'by reference is faster' or that give no effect on the calling program's variable.
Both marks require a comparison relating to the calling program's variable; a definition of each term alone, with no effect stated, scores a maximum of 1.

H446/02 — 乙部

Answer every question. No calculator. Extended evaluative responses are asterisked. One sustained structured question.
9 題目 · 40 分
題目 1 · Code writing, completion or correction
2 分
A greenhouse controller stores hourly temperature readings in a 0-indexed array named temps. The function countAbove should return the number of readings that are strictly greater than the value of the parameter limit.

Complete the two gaps, labelled (A) and (B), in the pseudocode below.

```
1 function countAbove(temps, limit)
2 total = 0
3 for i = 0 to ........(A)........
4 if temps[i] ........(B)........ limit then
5 total = total + 1
6 endif
7 next i
8 return total
9 endfunction
```

Gap (A): ______________________

Gap (B): ______________________

[2]
查看答案詳解

解題

The loop must visit every index of a 0-indexed array, from 0 up to temps.length - 1 inclusive, because the for loop is inclusive of both ends. The condition must be a strict comparison, so the operator is >.

評分準則

(A) temps.length - 1 (1 mark). Allow any equivalent expression for the last index, e.g. len(temps) - 1. Do not accept temps.length, as this goes out of bounds.
(B) > (1 mark). Do not accept >=.
Max 2.
題目 2 · Code writing, completion or correction
2 分
The following pseudocode is intended to perform a binary search on the sorted 0-indexed array names, to find the position of the string target. The function should return -1 if target is not found. The code contains two errors.

```
1 function findName(names, target)
2 low = 0
3 high = names.length - 1
4 while low <= high
5 mid = (low + high) DIV 2
6 if names[mid] == target then
7 return mid
8 elseif names[mid] < target then
9 high = mid - 1
10 else
11 low = mid + 1
12 endif
13 endwhile
14 return -1
15 endfunction
```

Identify the two errors and, for each, write a corrected line.

Error 1 (line number and corrected line): ______________________

Error 2 (line number and corrected line): ______________________

[2]
查看答案詳解

解題

If names[mid] is less than target, the target must lie in the upper half, so low must move to mid + 1 (line 9). Otherwise names[mid] is greater than target, so the target is in the lower half and high must become mid - 1 (line 11). The two assignments are swapped.

評分準則

Line 9 changed to low = mid + 1 (1 mark).
Line 11 changed to high = mid - 1 (1 mark).
Allow the correction to be given by swapping the comparison on line 8 to names[mid] > target, if both lines 9 and 11 are then left unchanged; this scores both marks together.
Do not award a mark where the correct line number is given with an incorrect line of code.
Max 2.
題目 3 · Code writing, completion or correction
3 分
A courier company stores the mass, in kilograms, of each parcel on a delivery van in a zero-indexed array named weights. The property weights.length gives the number of elements in the array.

The function heavyTotal is intended to return the total mass of only those parcels whose mass is greater than the value of the parameter limit.

```
01 function heavyTotal(weights, limit)
02 total = 1
03 for i = 0 to weights.length
04 if weights[i] < limit then
05 total = total + weights[i]
06 endif
07 next i
08 return total
09 endfunction
```

The function contains three errors, each on a different line.

Identify each error and write a corrected version of the line. You may use pseudocode or program code.

[3]

Line number: ........ Corrected line: ..............................................

Line number: ........ Corrected line: ..............................................

Line number: ........ Corrected line: ..............................................
查看答案詳解

解題

Line 2: total is initialised to 1, so every result would be 1 too large; it must start at 0.
Line 3: the loop is inclusive of both ends, so i reaches weights.length, which is outside a zero-indexed array; the upper bound must be weights.length - 1.
Line 4: the comparison selects parcels lighter than the limit; it must select parcels heavier, so > is needed.

Corrected function:
function heavyTotal(weights, limit)
total = 0
for i = 0 to weights.length - 1
if weights[i] > limit then
total = total + weights[i]
endif
next i
return total
endfunction

評分準則

Award one mark for each correct line identified and corrected (max 3):
- Line 2: total initialised to 0, e.g. total = 0
- Line 3: upper bound of loop reduced to weights.length - 1, e.g. for i = 0 to weights.length - 1. Allow weights.length - 1 written as an equivalent expression.
- Line 4: comparison changed to greater than, e.g. if weights[i] > limit then

Allow any equivalent correct code, e.g. a while loop on line 3 provided the whole line is rewritten correctly and the loop covers indexes 0 to weights.length - 1.
Do not accept a correction on the wrong line number. Do not accept >= on line 4 (parcels equal to the limit are not heavier than it).
If a candidate changes a correct line (e.g. line 5, 6 or 8) in a way that introduces an error, do not award the mark for that line's change, but this does not remove marks already awarded for the three errors.
One mark per line; each mark is independent.
題目 4 · Code writing, completion or correction
5 分
A weather station records the temperature, in whole degrees, once every hour. The readings for one day are stored in a one-dimensional array named readings.

A function named longestRun must return the greatest number of consecutive readings that are strictly above a given limit.

The function is incomplete. Four gaps are marked [A], [B], [C] and [D].

01 function longestRun(readings, limit)
02 best = 0
03 current = 0
04 for i = 0 to readings.length - 1
05 if readings[i] > limit then
06 current = [A]
07 else
08 current = [B]
09 endif
10 if current > best then
11 [C]
12 endif
13 next i
14 return [D]
15 endfunction

(a) Complete the code by writing the missing code for each of the gaps [A], [B], [C] and [D]. You may use pseudocode or a programming language of your choice.

[A] ______________________
[B] ______________________
[C] ______________________
[D] ______________________
[4]

(b) The array readings contains the values 3, 8, 9, 2, 7, 8, 9, 10.

State the value returned by the call longestRun(readings, 6).
[1]
查看答案詳解

解題

The variable current counts the length of the present run of readings above limit. If the reading is above the limit the run grows by one (A); otherwise the run is broken and resets to zero (B). Whenever the present run exceeds the longest run so far, best is updated (C). After the loop, best holds the longest run (D).

For part (b) the readings above 6 are 8, 9 (run of 2), then 2 breaks the run, then 7, 8, 9, 10 (run of 4). The longest run is 4.

評分準則

(a) Max 4, one mark per gap:
- [A] current + 1 (allow current += 1, 1 + current) (1)
- [B] 0 (1)
- [C] best = current (1)
- [D] best (1)
Do not accept a gap that assigns to the wrong variable, e.g. current = best for [C]. Allow equivalent code in any recognised language.

(b) 4 (1)
Do not accept 2 or 6. Award this mark independently of the answers given in (a).
題目 5 · Code writing, completion or correction
5 分
A print server holds waiting jobs in a circular queue implemented using a global array named queue with five locations, indexed 0 to 4. The global variable front holds the index of the job at the front of the queue. The global variable count holds the number of jobs currently in the queue.

The following subroutines are incomplete. Three gaps are marked [A], [B] and [C].

global queue = array 5
global front = 0
global count = 0

function enqueue(job)
if [A] then
return false
else
rear = (front + count) MOD 5
queue[rear] = job
count = [B]
return true
endif
endfunction

function dequeue()
if count == 0 then
return -1
else
job = queue[front]
front = [C]
count = count - 1
return job
endif
endfunction

(a) Complete the code by writing the missing code for each of the gaps [A], [B] and [C]. You may use pseudocode or a programming language of your choice.

[A] ______________________
[B] ______________________
[C] ______________________
[3]

(b) At one point front has the value 3 and count has the value 4.

(i) State the index of the location in which the next job passed to enqueue will be stored.
[1]

(ii) Give one reason why a circular queue is used instead of a linear queue implemented in an array of the same size.
[1]
查看答案詳解

解題

The queue is full when count equals the array size, 5 (A). Adding a job increases count by one (B). Removing a job moves front on by one, wrapping to 0 after index 4, so (front + 1) MOD 5 (C).

(b)(i) rear = (3 + 4) MOD 5 = 7 MOD 5 = 2.
(ii) Space at the start of the array that is freed by dequeue can be reused by wrapping round, so items do not need shifting and the queue does not report full while empty locations remain.

評分準則

(a) Max 3, one mark per gap:
- [A] count == 5 (allow count >= 5, count == queue.length) (1)
- [B] count + 1 (allow count += 1) (1)
- [C] (front + 1) MOD 5 (1)
Do not accept front + 1 for [C] (no wrap-around).

(b)(i) 2 (1)
Do not accept 7.

(b)(ii) Max 1:
- Freed locations at the front can be reused / the array is used efficiently (1)
- Avoids shifting all items along after a dequeue (1)
- Avoids the queue appearing full when there are empty locations (1)
Do not accept 'it is faster' or 'it uses less memory' without development.
題目 6 · Description or explanation
3 分
A courier company, Harbourline, delivers parcels to up to 40 addresses on each round. A program must produce a route for each driver that visits every address once and returns to the depot.

The programmer decides to use a heuristic approach, rather than checking every possible order of visiting the addresses.

Explain why a heuristic approach is suitable for this problem. Use the context of Harbourline in your answer. [3]
查看答案詳解

解題

With 40 addresses there are around 40! possible orders, far too many to check in a reasonable time, even on a fast computer. A heuristic uses a rule of thumb, for example moving to the nearest unvisited address next. This produces an acceptable route in a short time, although it may not be the shortest possible route. For Harbourline, a reasonably short route available quickly is more useful than a perfect route that takes too long to calculate.

評分準則

Max 3 from:
- Number of possible routes is very large / grows factorially or exponentially as addresses are added (1)
- ... so checking every route (exhaustive search) would take impractical / too much time (1)
- A heuristic uses a rule of thumb / approximation, e.g. nearest unvisited address next (1)
- ... which gives a good / acceptable route quickly (1)
- The route may not be optimal, but this is acceptable for delivery drivers (1)
- Must be applied to Harbourline, e.g. 40 addresses per round / routes needed before drivers start (1)

Allow: 'brute force' for exhaustive search.
DNA: 'faster' or 'easier' without reference to the number of routes or the time taken.
DNA: answers claiming a heuristic always finds the best route.
題目 7 · Description or explanation
5 分
A community boathouse uses a program to manage the hire of kayaks. The program stores the number of kayaks currently available in a variable named available.

A programmer writes the following two procedures. The main program calls one of them each time a kayak is hired.

01 procedure hireA(count)
02 count = count - 1
03 endprocedure
04
05 procedure hireB(byRef count)
06 count = count - 1
07 endprocedure
08
09 available = 12
10 hireA(available)
11 print(available)
12 hireB(available)
13 print(available)

(a) State the values that are output by line 11 and by line 13. [2]

(b) Explain why the two procedures cause different values to be stored in available. Your answer must refer to the way each parameter is passed. [3]
查看答案詳解

解題

(a) hireA is called by value (the default). Parameter count is a local copy of 12; decrementing it does not change available, so line 11 prints 12. hireB uses byRef, so count refers to the same memory location as available. available becomes 11, so line 13 prints 11.
(b) In hireA the value 12 is copied into a local variable, which is discarded when the procedure ends. In hireB the address of available is passed, so count is an alias for it and the subtraction changes the original variable.

評分準則

(a) Max 2
- 12 for line 11 (1)
- 11 for line 13 (1)
Allow follow through for line 13 only if line 11 is given as 12 or the candidate's reasoning is consistent with by value / by reference. Both values must be linked to the correct line.

(b) Max 3
- hireA passes the parameter by value // a copy of the value of available is passed (1)
- ...so changes to count affect only the local copy / the original variable is unchanged (1)
- hireB passes the parameter by reference // the address / memory location of available is passed (1)
- ...so count refers to the same variable and the change updates available (1)
Award a maximum of 3 marks.
Do not accept 'global' or 'local' variable as the sole explanation without reference to copying or addresses. Do not accept a description that does not distinguish the two procedures.
題目 8 · Extended evaluative response
12 分
6* A regional ferry company, Harbourline, is developing a program to plan journeys for passengers. The ferry network is stored as a weighted graph. Each node is a port. Each edge is a direct sailing between two ports and its weight is the sailing time in minutes. The network has 400 ports and about 1 200 direct sailings.

The program must:
- find the quickest route between any two ports chosen by a passenger
- respond within one second on a low-powered kiosk
- use the current sailing times, which change several times a day because of tides and weather.

The developers are considering Dijkstra's shortest path algorithm and the A* algorithm. For A*, the heuristic would be the straight-line distance between two ports divided by the ferry's maximum speed.

Discuss the suitability of Dijkstra's shortest path algorithm and the A* algorithm for this program.

You should include:
- how each algorithm finds a route
- the benefits and drawbacks of each algorithm in this context
- a justified conclusion about which algorithm should be used.

[12]
查看答案詳解

解題

Dijkstra: all nodes start with distance infinity except the start node (0). Repeatedly select the unvisited node with the smallest known distance, update the distances of its neighbours if a shorter path is found via this node, and record the previous node. Stop when the destination is visited (or all nodes are visited). The route is rebuilt by following the previous-node links backwards. It always gives the quickest route when weights are non-negative (sailing times are), needs no extra information, and uses current weights each run. Its drawback is that it explores outwards in every direction, including ports in the wrong direction, so it may process many of the 400 ports. With a priority queue the cost is roughly O((V+E) log V), so for 400 ports and 1 200 edges this is only a few thousand operations, which is likely to be well inside one second even on a low-powered kiosk.

A*: works like Dijkstra but chooses the next node with the lowest f = g + h, where g is the known time from the start and h is the heuristic estimate to the destination. This directs the search towards the destination so fewer nodes are explored. Drawbacks: it needs port coordinates to be stored and a heuristic to be designed; if h overestimates the true time the route may not be the quickest. Straight-line distance divided by maximum speed never overestimates the time (ferries cannot go faster than maximum speed or shorter than a straight line), so it is admissible, and changing sailing times (delays, slower speeds) only make real times longer, so it remains admissible. It is more complex to implement and each node needs extra data (h and f), using slightly more memory. In the worst case, with a poor heuristic, it can behave like Dijkstra.

Conclusion: both are feasible on a small graph. A* is preferable as it reduces explored ports and response time while keeping the quickest route, because the heuristic is admissible. Dijkstra is simpler and could be chosen if simplicity and maintainability matter more, as the graph is small.

評分準則

AO1 (knowledge), AO2 (application to the Harbourline scenario), AO3 (evaluation and judgement). Award the level from the overall quality of the response, then position the mark within the level. Indicative content is not exhaustive.

Level 3 (10-12 marks): Detailed and accurate description of how both algorithms find a route, including the role of distances/priority and, for A*, the heuristic. Benefits and drawbacks of both are clearly applied to the context (graph size, kiosk, changing times). A justified conclusion is reached that follows from the points made. Few or no errors; well structured.

Level 2 (5-9 marks): Reasonable description of how at least one algorithm works, with some description of the other. Some benefits and/or drawbacks are applied to the context, but may be one-sided or lack development. A conclusion is given but may be only partly justified.

Level 1 (1-4 marks): Limited or generic description of one or both algorithms, with little or no reference to the context. Benefits/drawbacks are stated, not developed. Conclusion absent or unsupported.

0 marks: No creditworthy response.

Indicative content (knowledge):
- Dijkstra: initial distances infinity/0 for start; choose unvisited node with smallest distance; update neighbours; record previous node; trace back to give the route
- A* similar but selects by f = g + h; h is an estimate of remaining cost to the destination
- Both use a priority queue/list of open nodes; both need non-negative weights
- Dijkstra and A* with an admissible heuristic both give the quickest route

Indicative content (application):
- 400 ports and 1 200 edges is a small graph so Dijkstra may be fast enough
- Dijkstra explores ports in all directions, including those away from the destination, wasting processing on a low-powered kiosk
- A* explores fewer nodes so is faster/uses less memory for the queue
- Straight-line distance / maximum speed is admissible, so A* remains optimal; delays only increase real times
- A* requires port coordinates to be stored and a heuristic to be designed; extra data per node
- Sailing times change several times a day, so the graph weights must be re-read for each search; neither algorithm needs pre-computed results (unlike caching all routes, which would become out of date)
- Heuristic is only a good guide if sailings are close to straight lines; if routes must go around land/islands, h is a poor estimate and A* gains less

Indicative content (evaluation):
- Judgement on which algorithm, weighing speed against complexity/maintainability
- Valid conclusions include A* (preferred, with justification) or Dijkstra (acceptable if justified by simplicity and the small graph)

Allow: Big O notation used correctly, e.g. O(n^2) for array-based Dijkstra or O((V+E) log V) with a priority queue.
Do not accept: statements that Dijkstra or A* sorts the graph, or that A* is always guaranteed to be faster in the worst case.
Do not accept: a conclusion that A* is optimal without any reference to the heuristic not overestimating.
If the response describes only one algorithm in detail, the maximum is Level 2.
題目 9 · Short identification or recall
3 分
A programmer is testing a procedure that adjusts the scores in a quiz application. The procedure is written in the pseudocode style used by OCR.

```
1 procedure adjust(byVal bonus, byRef score)
2 bonus = bonus * 2
3 score = score + bonus
4 endprocedure
5
6 points = 10
7 extra = 3
8 adjust(extra, points)
9 print(points)
10 print(extra)
```

(a) State the two values output by the program, in the order that they are printed. [2]

(b) Identify the name of the method of parameter passing that causes the value of extra to remain unchanged after line 8. [1]
查看答案詳解

解題

On line 8, extra (3) is passed by value to bonus, so bonus is a copy. Line 2 changes the copy to 6, and the original extra stays 3. points (10) is passed by reference to score, so line 3 changes points to 10 + 6 = 16. Line 9 outputs 16 and line 10 outputs 3. The variable extra is unchanged because it was passed by value.

評分準則

(a) Max 2
- 16 output first (1)
- 3 output second (1)
Allow follow through for the second mark only if the candidate has shown the outputs in the order points then extra. Do not accept 6 for the second value. Accept the two values on separate lines or separated by a comma.

(b) Max 1
- By value / pass by value / byVal (1)
Do not accept by reference.

想知道自己有幾分把握?

thinka 是 DSE 學生用的 AI 練習應用程式,有無限量練習題、即時自動批改和詳細解題步驟。逾 100,000 名學生用它確認自己真的識,而不只是「以為識」。

想練更多類似題型?在 thinka 無限量操練,即時知道答案。

免費開始練習