19.1· 13 questions · 317 marks · 380 min · 2021–2022· Structured questions
Every Cambridge A Level Computer Science Paper 4 question on algorithms, laid out as 29 A4 pages with the mark scheme below. Nothing is left out. Free to read, no account.
14 / 29
25 / 29Answers below. Sit the paper first if you are practising.
Pastlit
Computer Science 9618 · Algorithms — Paper 4
A Level · topical answer key — answer key (teacher use)
Question
Answer
Marks
24
20
24
20
24
20
23
23
31
23
31
23
31| Question | Answer | Marks | From |
|---|---|---|---|
| 1 | see sheet | 24 | 9618/41 May/June 2021 |
| 2 | see sheet | 20 | 9618/41 May/June 2021 |
| 3 | see sheet | 24 | 9618/42 May/June 2021 |
| 4 | see sheet | 20 | 9618/42 May/June 2021 |
| 5 | see sheet | 24 | 9618/43 May/June 2021 |
| 6 | see sheet | 20 | 9618/43 May/June 2021 |
| 7 | see sheet | 23 | 9618/42 May/June 2022 |
| 8 | see sheet | 23 | 9618/41 Oct/Nov 2022 |
| 9 | see sheet | 31 | 9618/41 Oct/Nov 2022 |
| 10 | see sheet | 23 | 9618/42 Oct/Nov 2022 |
| 11 | see sheet | 31 | 9618/42 Oct/Nov 2022 |
| 12 | see sheet | 23 | 9618/43 Oct/Nov 2022 |
| 13 | see sheet | 31 | 9618/43 Oct/Nov 2022 |
1 An unordered linked list uses a 1D array to store the data. Each item in the linked list is of a record type, node, with a field data and a field nextNode. The current contents of the linked list are: startPointer 0 Index data nextNode 0 1 1 emptyList 5 1 5 4 2 6 7 3 7 -1 4 2 2 5 0 6 6 0 8 7 56 3 8 0 9 9 0 -1 (a) The following is pseudocode for the record type node. TYPE node DECLARE data : INTEGER DECLARE nextNode : INTEGER ENDTYPE Write program code to declare the record type node. Save your program as question1. Copy and paste the program code into part 1(a) in the evidence document. [2] (b) Write program code for the main program. Declare a 1D array of type node with the identifier linkedList, and initialise it with the data shown in the table on page 2. Declare the pointers. Save your program. Copy and paste the program code into part 1(b) in the evidence document. [4] (c) The procedure outputNodes() takes the array and startPointer as parameters. The procedure outputs the data from the linked list by following the nextNode values. (i) Write program code for the procedure outputNodes(). Save your program. Copy and paste the program code into part 1(c)(i) in the evidence document. [6] (ii) Edit the main program to call the procedure outputNodes(). Take a screenshot to show the output of the procedure outputNodes(). Save your program. Copy and paste the screenshot into part 1(c)(ii) in the evidence document. [1] (d) The function, addNode(), takes the linked list and pointers as parameters, then takes as input the data to be added to the end of the linkedList. The function adds the node in the next available space, updates the pointers and returns True. If there are no empty nodes, it returns False. (i) Write program code for the function addNode(). Save your program. Copy and paste the program code into part 1(d)(i) in the evidence document. [7] (ii) Edit the main program to: • call addNode() • output an appropriate message depending on the result returned from addNode() • call outputNodes() twice; once before calling addNode() and once after calling addNode(). Save your program. Copy and paste the program code into part 1(d)(ii) in the evidence document. [3] (iii) Test your program by inputting the data value 5 and take a screenshot to show the output. Save your program. Copy and paste the screenshot into part 1(d)(iii) in the evidence document. [1]
24 marks
Mark scheme: 1(a) 1 mark per bullet point • Declaring record/class with name node… • …declaring data and next node (both as Integers) Example code: Visual Basic Structure node Dim Data As Integer Dim nextNode As Integer End Structure Python class node: def __init__(self, theData, nextNodeNumber): self. Data = theData self.nextNode = nextNodeNumber Java class node{ private Integer Data; private Integer nextNode; public node(Integer dataP, Integer nextNodeP){ this.Data = dataP; this.nextNode = nextNodeP; } } Question Answer Marks 1(b) 1 mark per bullet point • Declaring array named linkedList with data type node • Assigning all nodes correctly as record/object nodes … • …with correct values stored • declaring startPointer as 0, emptyList as 5 Example code: Visual Basic Dim linkedList(9) As node linkedList(0).data = 1 linkedList(0).nextNode = 1 linkedList(1).data = 5 linkedList(1).nextNode = 4 linkedList(2).data = 6 linkedList(2).nextNode = 7 linkedList(3).data = 7 linkedList(3).nextNode = -1 linkedList(4).data = 2 linkedList(4).nextNode = 2 linkedList(5).data = 0 linkedList(5).nextNode = 6 linkedList(6).data = 0 linkedList(6).nextNode = 8 linkedList(7).data = 56 linkedList(7).nextNode = 3 linkedList(8).data = 0 linkedList(8).nextNode = 9 linkedList(9).data = 0 linkedList(9).nextNode = -1 Dim startPointer As Integer = 0 Dim emptyList As Integer = 5 4 Question Answer Marks 1(b) Python linkedList = [node(1,1),node(5,4),node(6,7),node(7,-1),node(2,2),node(0,6), node(0,8),node(56,3),node(0,9),node(0,-1)] startPointer = 0 emptyList = 5 Java public static void main(String[] args){ node[] linkedList = new node[10]; linkedList[0] = new node(1,1); linkedList[1] = new node(5, 4); linkedList[2] = new node(6, 7); linkedList[3] = new node(7,-1); linkedList[4] = new node(2,2); linkedList[5] = new node(0,6); linkedList[6] = new node(0,8); linkedList[7] = new node(56, 3); linkedList[8] = new node(0,9); linkedList[9] = new node(0,-1); Integer startPointer = 0; Integer emptyList = 5; } Question Answer Marks 1(c)(i) 1 mark per bullet point • Procedure outputNodes … • …taking linked list and start pointer as parameters • Looping until nextNode/pointer is –1 • Outputting the node data in the correct order, i.e. following pointers • Updating pointer to current node’s nextNode • Using the correct record/class field/properties throughout Example code: Visual Basic Sub outputNodes(ByRef linkedList, ByVal currentPointer) While (currentPointer <> -1) Console.WriteLine(linkedList(currentPointer).data) currentPointer = linkedList(currentPointer).nextNode End While End Sub Python def outputNodes(linkedList, currentPointer): while(currentPointer != -1): print(str(linkedList[currentPointer].data)) currentPointer = linkedList[currentPointer].nextNode Java public static void outputNodes(node[] linkedList, Integer currentPointer){ while(currentPointer != -1){ System.out.println(linkedList[currentPointer].data); currentPointer = linkedList[currentPointer].nextNode; } } 6 Question Answer Marks 1(c)(ii) Screenshot showing: 1 5 2 6 56 7 1 1(d)(i) 1 mark per bullet point to max 7 • Function taking list and both pointers as parameters • Taking (integer) data as input • Checking if list is full … • … and returning False • Insert the input data to the empty list node’s data • Following pointers to find last node in Linked List … • …and updating last node’s pointer to empty list/location where new node is added • Updating empty list to it’s first elements pointer • Returning true when added successfully Example code: Visual Basic Function addNode(ByRef linkedList() As node, ByVal currentPointer As Integer, ByRef emptyList As Integer) Console.WriteLine("Enter the data to add") Dim dataToAdd As Integer = Console.ReadLine() Dim previousPointer As Integer = 0 Dim newNode As node If emptyList < 0 Or emptyList > 9 Then Return False Else newNode.data = dataToAdd newNode.nextNode = -1 7 Question Answer Marks 1(d)(i) linkedList(emptyList) = newNode previousPointer = 0 While (currentPointer <> -1) previousPointer = currentPointer currentPointer = linkedList(currentPointer).nextNode End While Dim valueToWrite As Integer = emptyList linkedList(previousPointer).nextNode = valueToWrite emptyList = linkedList(emptyList).nextNode Return True End If End Function Python def addNode(linkedList, currentPointer, emptyList): dataToAdd = input("Enter the data to add") if emptyList <0 or emptyList > 9: return False else: newNode = node(int(dataToAdd), -1) linkedList[emptyList] = (newNode) previousPointer = 0 while(currentPointer != -1): previousPointer = currentPointer currentPointer = linkedList[currentPointer].nextNode linkedList[previousPointer].nextNode = emptyList emptyList = linkedList[emptyList].nextNode return True Question Answer Marks 1(d)(i) Java public static Boolean addNode(node[] linkedList, Integer currentPointer, Integer emptyList){ Integer dataToAdd; Integer previousPointer; node newNode; Scanner in = new Scanner(System.in); System.out.println("Enter the data to add"); dataToAdd = in.nextInt(); if(emptyList < 0 || emptyList > 9){ return false; }else{ newNode = new node(dataToAdd, -1); linkedList[emptyList] = newNode; previousPointer = 0; while(currentPointer != -1){ previousPointer = currentPointer; currentPointer = linkedList[currentPointer].nextNode; } linkedList[previousPointer].nextNode = emptyList; emptyList = linkedList[emptyList].nextNode; return true; } } Question Answer Marks 1(d)(ii) 1 mark per bullet point • Call addNode() with list, start and empty pointers and store/check return value … • …output appropriate message if True returned and if False returned • Calling outputNodes() with list and start pointer before and after addNode() Example code: Visual Basic Sub Main() Dim linkedList(10) As node linkedList(0).data = 1 linkedList(0).nextNode = 1 linkedList(1).data = 5 linkedList(1).nextNode = 4 linkedList(2).data = 6 linkedList(2).nextNode = 7 linkedList(3).data = 7 linkedList(3).nextNode = -1 linkedList(4).data = 2 linkedList(4).nextNode = 2 linkedList(5).data = -1 linkedList(5).nextNode = 6 linkedList(6).data = -1 linkedList(6).nextNode = 7 linkedList(7).data = 56 linkedList(7).nextNode = 3 linkedList(8).data = -1 linkedList(8).nextNode = 9 linkedList(9).data = -1 linkedList(9).nextNode = -1 Dim startPointer As Integer = 0 Dim emptyList As Integer = 5 outputNodes(linkedList, startPointer) Dim returnValue As Boolean returnValue = addNode(linkedList, startPointer, emptyList) 3 Question Answer Marks 1(d)(ii) If returnValue = True Then Console.WriteLine("Item successfully added") Else Console.WriteLine("Item not added, list full") End If outputNodes(linkedList, startPointer) Console.ReadLine() End Sub Python linkedList = [node(1,1),node(5,4),node(6,7),node(7,-1),node(2,2),node(-1,6), node(-1,7),node(56,3),node(-1,9),node(-1,-1)] startPointer = 0 emptyList = 5 outputNodes(linkedList, startPointer) returnValue = addNode(linkedList, startPointer, emptyList) if returnValue == True: print("Item successfully added") else: print("Item not added, list full") outputNodes(linkedList, startPointer) Java public static void main(String[] args){ node[] linkedList = new node[10]; linkedList[0] = new node(1,1); linkedList[1] = new node(5, 4); linkedList[2] = new node(6, 7); linkedList[3] = new node(7,-1); linkedList[4] = new node(2,2); linkedList[5] = new node(-1,6); linkedList[6] = new node(-1,7); linkedList[7] = new node(56, 3); linkedList[8] = new node(-1,9); Question Answer Marks 1(d)(ii) linkedList[9] = new node(-1,-1); Integer startPointer = 0; Integer emptyList = 5; outputNodes(linkedList, startPointer); Boolean returnValue; returnValue = addNode(linkedList, startPointer, emptyList); if (returnValue == true){ System.out.println("Item successfully added"); }else{ System.out.println("Item not added, list full"); } outputNodes(linkedList, startPointer); } 1(d)(iii) 1 mark for screenshot showing : • Linked list output • 5 input • Message saying Successfully added or equivalent • Linked list output with 5 at the end. Example: 1 5 2 6 56 7 5 (being input) 1 5 2 6 56 7 5 1
2 A program stores the following ten integers in a 1D array with the identifier arrayData. 10 5 6 7 1 12 13 15 21 8 (a) Write program code for a new program to: • declare the global 1D array, arrayData, with ten elements • initialise arrayData in the main program using the data values shown. Save your program as question2. Copy and paste the program code into part 2(a) in the evidence document. [2] (b) (i) A function, linearSearch(), takes an integer as a parameter and performs a linear search on arrayData to find the parameter value. It returns True if it was found and False if it was not found. Write program code for the function linearSearch(). Save your program. Copy and paste the program code into part 2(b)(i) in the evidence document. [6] (ii) Edit the main program to: • allow the user to input an integer value • pass the value to linearSearch() as the parameter • output an appropriate message to tell the user whether the search value was found or not. Save your program. Copy and paste the program code into part 2(b)(ii) in the evidence document. [4] (iii) Test your program with one value that is in the array and one value that is not in the array. Take a screenshot to show the result of each test. Save your program. Copy and paste the screenshots into part 2(b)(iii) in the evidence document. [2] (c) The following bubble sort pseudocode algorithm sorts the data in theArray into descending numerical order. There are five incomplete statements. PROCEDURE bubbleSort() DECLARE temp : INTEGER FOR x 0 to ………………………………… FOR y 0 to ………………………………… IF theArray[y] ………………………………… theArray[y + 1] THEN temp theArray[y] theArray[y] theArray[y + 1] ENDIF NEXT y NEXT x ENDPROCEDURE Write program code for the procedure bubbleSort() to sort the data in arrayData into descending order. Save your program. Copy and paste the program code into part 2(c) in the evidence document. [6]
20 marks
Mark scheme: 2(a) 1 mark per bullet point • Array with identifier arrayData • correct 10 data items added Example code: Visual Basic Dim arrayData(9) As Integer Sub Main() arrayData(0) = 10 arrayData(1) = 5 arrayData(2) = 6 arrayData(3) = 7 arrayData(4) = 1 arrayData(5) = 12 arrayData(6) = 13 arrayData(7) = 15 arrayData(8) = 21 arrayData(9) = 8 End Sub Python arrayData = [10, 5, 6, 7, 1, 12, 13, 15, 21, 8] Java int[] arrayData = new int[]; public static void main(String[] args){ arrayData[0] = 10; arrayData[1] = 5; arrayData[2] = 6; arrayData[3] = 7; arrayData[4] = 1; arrayData[5] = 12; arrayData[6] = 13; Question Answer Marks 2(a) arrayData[7] = 15; arrayData[8] = 21; arrayData[9] = 8; } 2(b)(i) 1 mark per bullet point • function linearSearch with correct identifier • …taking integer search value as a parameter • Searching 10 times/through all array elements … • …comparing each element to search value • returning True if found • returning False if not found Example code: Visual Basic Function linearSearch(ByRef searchValue As Integer) For x = 0 To 9 If arrayData(x) = searchValue Then Return True End If Next Return False End Function 6 Question Answer Marks 2(b)(i) Python def linearSearch(searchValue): for x in range(0, 10): if arrayData[x] == searchValue: return True return False Java public static Boolean linearSearch(Integer searchValue){ for (int x = 0; x < 10; x++){ if(arrayData[x] == searchValue){ return true; } } return false; } Question Answer Marks 2(b)(ii) 1 mark per bullet point to max 4 • Taking value as input… • …checking/casting to Integer • Calling linearSearch and sending input as parameter • Storing and checking return value… • …outputting appropriate message if found and if not found Example code: Visual Basic Dim arrayData(10) As Integer Sub Main() arrayData(0) = 10 arrayData(1) = 5 arrayData(2) = 6 arrayData(3) = 7 arrayData(4) = 1 arrayData(5) = 12 arrayData(6) = 13 arrayData(7) = 15 arrayData(8) = 12 arrayData(9) = 8 Console.WriteLine("Enter a number to search for") Dim searchValue As Integer = Console.ReadLine() Dim returnValue As Boolean = linearSearch(searchValue) If returnValue = True Then Console.WriteLine("Found it") Else Console.WriteLine("Didn't find it") End If End Sub 4 Question Answer Marks 2(b)(ii) Python arrayData = [10, 5, 6, 7, 1, 12, 13, 15, 21, 8] searchValue = int(input("Enter the number to search for")) returnValue = linearSearch(searchValue) if returnValue == True: print("It was found") else: print("It was not found") Java Integer[] arrayData = new Integer[10]; public static void main(String[] args){ arrayData[0] = 10; arrayData[1] = 5; arrayData[2] = 6; arrayData[3] = 7; arrayData[4] = 1; arrayData[5] = 12; arrayData[6] = 13; arrayData[7] = 15; arrayData[8] = 12; arrayData[9] = 8; System.out.println("Enter the number to search for"); Integer searchValue; Scanner in = new Scanner(System.in); searchValue = in.nextInt(); Boolean returnValue; returnValue = linearSearch(searchValue); if (returnValue == true){ System.out.println("It was found"); }else{ System.out.println("It was not found"); } } Question Answer Marks 2(b)(iii) 1 mark for screenshot showing input and output for number found 1 mark for screenshot showing input and output for number not found 2 2(c) 1 mark per bullet point • Correct outer loop stop • Correct inner loop stop • Correct < in the IF • Correct theArray(y + 1) • Correct temp • Remainder matching pseudocode Example code: Visual Basic Sub bubbleSort() Dim temp As Integer = 0 For x = 0 To 9 For y = 0 To 8 If theArray(y) < theArray(y + 1) Then temp = theArray(y) theArray(y) = theArray(y + 1) theArray(y + 1) = temp End If Next Next End Sub 6 Question Answer Marks 2(c) Python def bubbleSort(): for x in range (0, 10): for y in range(0, 9): if theArray[y] < theArray[y + 1]: temp = theArray[y] theArray[y] = theArray[y + 1] theArray[y + 1] = temp Java public static void bubbleSort(){ int temp; for (int x = 0; x < 10; x++){ for (int y = 0; y < 9; y++){ if(theArray[y] < theArray[y+1]){ temp = theArray[y]; theArray[y] = theArray[y+1]; theArray[y+1] = temp; } } } }
1 An unordered linked list uses a 1D array to store the data. Each item in the linked list is of a record type, node, with a field data and a field nextNode. The current contents of the linked list are: startPointer 0 Index data nextNode 0 1 1 emptyList 5 1 5 4 2 6 7 3 7 -1 4 2 2 5 0 6 6 0 8 7 56 3 8 0 9 9 0 -1 (a) The following is pseudocode for the record type node. TYPE node DECLARE data : INTEGER DECLARE nextNode : INTEGER ENDTYPE Write program code to declare the record type node. Save your program as question1. Copy and paste the program code into part 1(a) in the evidence document. [2] (b) Write program code for the main program. Declare a 1D array of type node with the identifier linkedList, and initialise it with the data shown in the table on page 2. Declare the pointers. Save your program. Copy and paste the program code into part 1(b) in the evidence document. [4] (c) The procedure outputNodes() takes the array and startPointer as parameters. The procedure outputs the data from the linked list by following the nextNode values. (i) Write program code for the procedure outputNodes(). Save your program. Copy and paste the program code into part 1(c)(i) in the evidence document. [6] (ii) Edit the main program to call the procedure outputNodes(). Take a screenshot to show the output of the procedure outputNodes(). Save your program. Copy and paste the screenshot into part 1(c)(ii) in the evidence document. [1] (d) The function, addNode(), takes the linked list and pointers as parameters, then takes as input the data to be added to the end of the linkedList. The function adds the node in the next available space, updates the pointers and returns True. If there are no empty nodes, it returns False. (i) Write program code for the function addNode(). Save your program. Copy and paste the program code into part 1(d)(i) in the evidence document. [7] (ii) Edit the main program to: • call addNode() • output an appropriate message depending on the result returned from addNode() • call outputNodes() twice; once before calling addNode() and once after calling addNode(). Save your program. Copy and paste the program code into part 1(d)(ii) in the evidence document. [3] (iii) Test your program by inputting the data value 5 and take a screenshot to show the output. Save your program. Copy and paste the screenshot into part 1(d)(iii) in the evidence document. [1]
24 marks
Mark scheme: 1(a) 1 mark per bullet point • Declaring record/class with name node… • …declaring data and next node (both as Integers) Example code: Visual Basic Structure node Dim Data As Integer Dim nextNode As Integer End Structure Python class node: def __init__(self, theData, nextNodeNumber): self. Data = theData self.nextNode = nextNodeNumber Java class node{ private Integer Data; private Integer nextNode; public node(Integer dataP, Integer nextNodeP){ this.Data = dataP; this.nextNode = nextNodeP; } } Question Answer Marks 1(b) 1 mark per bullet point • Declaring array named linkedList with data type node • Assigning all nodes correctly as record/object nodes … • …with correct values stored • declaring startPointer as 0, emptyList as 5 Example code: Visual Basic Dim linkedList(9) As node linkedList(0).data = 1 linkedList(0).nextNode = 1 linkedList(1).data = 5 linkedList(1).nextNode = 4 linkedList(2).data = 6 linkedList(2).nextNode = 7 linkedList(3).data = 7 linkedList(3).nextNode = -1 linkedList(4).data = 2 linkedList(4).nextNode = 2 linkedList(5).data = 0 linkedList(5).nextNode = 6 linkedList(6).data = 0 linkedList(6).nextNode = 8 linkedList(7).data = 56 linkedList(7).nextNode = 3 linkedList(8).data = 0 linkedList(8).nextNode = 9 linkedList(9).data = 0 linkedList(9).nextNode = -1 Dim startPointer As Integer = 0 Dim emptyList As Integer = 5 4 Question Answer Marks 1(b) Python linkedList = [node(1,1),node(5,4),node(6,7),node(7,-1),node(2,2),node(0,6), node(0,8),node(56,3),node(0,9),node(0,-1)] startPointer = 0 emptyList = 5 Java public static void main(String[] args){ node[] linkedList = new node[10]; linkedList[0] = new node(1,1); linkedList[1] = new node(5, 4); linkedList[2] = new node(6, 7); linkedList[3] = new node(7,-1); linkedList[4] = new node(2,2); linkedList[5] = new node(0,6); linkedList[6] = new node(0,8); linkedList[7] = new node(56, 3); linkedList[8] = new node(0,9); linkedList[9] = new node(0,-1); Integer startPointer = 0; Integer emptyList = 5; } Question Answer Marks 1(c)(i) 1 mark per bullet point • Procedure outputNodes … • …taking linked list and start pointer as parameters • Looping until nextNode/pointer is –1 • Outputting the node data in the correct order, i.e. following pointers • Updating pointer to current node’s nextNode • Using the correct record/class field/properties throughout Example code: Visual Basic Sub outputNodes(ByRef linkedList, ByVal currentPointer) While (currentPointer <> -1) Console.WriteLine(linkedList(currentPointer).data) currentPointer = linkedList(currentPointer).nextNode End While End Sub Python def outputNodes(linkedList, currentPointer): while(currentPointer != -1): print(str(linkedList[currentPointer].data)) currentPointer = linkedList[currentPointer].nextNode Java public static void outputNodes(node[] linkedList, Integer currentPointer){ while(currentPointer != -1){ System.out.println(linkedList[currentPointer].data); currentPointer = linkedList[currentPointer].nextNode; } } 6 Question Answer Marks 1(c)(ii) Screenshot showing: 1 5 2 6 56 7 1 1(d)(i) 1 mark per bullet point to max 7 • Function taking list and both pointers as parameters • Taking (integer) data as input • Checking if list is full … • … and returning False • Insert the input data to the empty list node’s data • Following pointers to find last node in Linked List … • …and updating last node’s pointer to empty list/location where new node is added • Updating empty list to it’s first elements pointer • Returning true when added successfully Example code: Visual Basic Function addNode(ByRef linkedList() As node, ByVal currentPointer As Integer, ByRef emptyList As Integer) Console.WriteLine("Enter the data to add") Dim dataToAdd As Integer = Console.ReadLine() Dim previousPointer As Integer = 0 Dim newNode As node If emptyList < 0 Or emptyList > 9 Then Return False Else newNode.data = dataToAdd newNode.nextNode = -1 7 Question Answer Marks 1(d)(i) linkedList(emptyList) = newNode previousPointer = 0 While (currentPointer <> -1) previousPointer = currentPointer currentPointer = linkedList(currentPointer).nextNode End While Dim valueToWrite As Integer = emptyList linkedList(previousPointer).nextNode = valueToWrite emptyList = linkedList(emptyList).nextNode Return True End If End Function Python def addNode(linkedList, currentPointer, emptyList): dataToAdd = input("Enter the data to add") if emptyList <0 or emptyList > 9: return False else: newNode = node(int(dataToAdd), -1) linkedList[emptyList] = (newNode) previousPointer = 0 while(currentPointer != -1): previousPointer = currentPointer currentPointer = linkedList[currentPointer].nextNode linkedList[previousPointer].nextNode = emptyList emptyList = linkedList[emptyList].nextNode return True Question Answer Marks 1(d)(i) Java public static Boolean addNode(node[] linkedList, Integer currentPointer, Integer emptyList){ Integer dataToAdd; Integer previousPointer; node newNode; Scanner in = new Scanner(System.in); System.out.println("Enter the data to add"); dataToAdd = in.nextInt(); if(emptyList < 0 || emptyList > 9){ return false; }else{ newNode = new node(dataToAdd, -1); linkedList[emptyList] = newNode; previousPointer = 0; while(currentPointer != -1){ previousPointer = currentPointer; currentPointer = linkedList[currentPointer].nextNode; } linkedList[previousPointer].nextNode = emptyList; emptyList = linkedList[emptyList].nextNode; return true; } } Question Answer Marks 1(d)(ii) 1 mark per bullet point • Call addNode() with list, start and empty pointers and store/check return value … • …output appropriate message if True returned and if False returned • Calling outputNodes() with list and start pointer before and after addNode() Example code: Visual Basic Sub Main() Dim linkedList(10) As node linkedList(0).data = 1 linkedList(0).nextNode = 1 linkedList(1).data = 5 linkedList(1).nextNode = 4 linkedList(2).data = 6 linkedList(2).nextNode = 7 linkedList(3).data = 7 linkedList(3).nextNode = -1 linkedList(4).data = 2 linkedList(4).nextNode = 2 linkedList(5).data = -1 linkedList(5).nextNode = 6 linkedList(6).data = -1 linkedList(6).nextNode = 7 linkedList(7).data = 56 linkedList(7).nextNode = 3 linkedList(8).data = -1 linkedList(8).nextNode = 9 linkedList(9).data = -1 linkedList(9).nextNode = -1 Dim startPointer As Integer = 0 Dim emptyList As Integer = 5 outputNodes(linkedList, startPointer) Dim returnValue As Boolean returnValue = addNode(linkedList, startPointer, emptyList) 3 Question Answer Marks 1(d)(ii) If returnValue = True Then Console.WriteLine("Item successfully added") Else Console.WriteLine("Item not added, list full") End If outputNodes(linkedList, startPointer) Console.ReadLine() End Sub Python linkedList = [node(1,1),node(5,4),node(6,7),node(7,-1),node(2,2),node(-1,6), node(-1,7),node(56,3),node(-1,9),node(-1,-1)] startPointer = 0 emptyList = 5 outputNodes(linkedList, startPointer) returnValue = addNode(linkedList, startPointer, emptyList) if returnValue == True: print("Item successfully added") else: print("Item not added, list full") outputNodes(linkedList, startPointer) Java public static void main(String[] args){ node[] linkedList = new node[10]; linkedList[0] = new node(1,1); linkedList[1] = new node(5, 4); linkedList[2] = new node(6, 7); linkedList[3] = new node(7,-1); linkedList[4] = new node(2,2); linkedList[5] = new node(-1,6); linkedList[6] = new node(-1,7); linkedList[7] = new node(56, 3); linkedList[8] = new node(-1,9); Question Answer Marks 1(d)(ii) linkedList[9] = new node(-1,-1); Integer startPointer = 0; Integer emptyList = 5; outputNodes(linkedList, startPointer); Boolean returnValue; returnValue = addNode(linkedList, startPointer, emptyList); if (returnValue == true){ System.out.println("Item successfully added"); }else{ System.out.println("Item not added, list full"); } outputNodes(linkedList, startPointer); } 1(d)(iii) 1 mark for screenshot showing : • Linked list output • 5 input • Message saying Successfully added or equivalent • Linked list output with 5 at the end. Example: 1 5 2 6 56 7 5 (being input) 1 5 2 6 56 7 5 1
2 A program stores the following ten integers in a 1D array with the identifier arrayData. 10 5 6 7 1 12 13 15 21 8 (a) Write program code for a new program to: • declare the global 1D array, arrayData, with ten elements • initialise arrayData in the main program using the data values shown. Save your program as question2. Copy and paste the program code into part 2(a) in the evidence document. [2] (b) (i) A function, linearSearch(), takes an integer as a parameter and performs a linear search on arrayData to find the parameter value. It returns True if it was found and False if it was not found. Write program code for the function linearSearch(). Save your program. Copy and paste the program code into part 2(b)(i) in the evidence document. [6] (ii) Edit the main program to: • allow the user to input an integer value • pass the value to linearSearch() as the parameter • output an appropriate message to tell the user whether the search value was found or not. Save your program. Copy and paste the program code into part 2(b)(ii) in the evidence document. [4] (iii) Test your program with one value that is in the array and one value that is not in the array. Take a screenshot to show the result of each test. Save your program. Copy and paste the screenshots into part 2(b)(iii) in the evidence document. [2] (c) The following bubble sort pseudocode algorithm sorts the data in theArray into descending numerical order. There are five incomplete statements. PROCEDURE bubbleSort() DECLARE temp : INTEGER FOR x 0 to ………………………………… FOR y 0 to ………………………………… IF theArray[y] ………………………………… theArray[y + 1] THEN temp theArray[y] theArray[y] theArray[y + 1] ENDIF NEXT y NEXT x ENDPROCEDURE Write program code for the procedure bubbleSort() to sort the data in arrayData into descending order. Save your program. Copy and paste the program code into part 2(c) in the evidence document. [6]
20 marks
Mark scheme: 2(a) 1 mark per bullet point • Array with identifier arrayData • correct 10 data items added Example code: Visual Basic Dim arrayData(9) As Integer Sub Main() arrayData(0) = 10 arrayData(1) = 5 arrayData(2) = 6 arrayData(3) = 7 arrayData(4) = 1 arrayData(5) = 12 arrayData(6) = 13 arrayData(7) = 15 arrayData(8) = 21 arrayData(9) = 8 End Sub Python arrayData = [10, 5, 6, 7, 1, 12, 13, 15, 21, 8] Java int[] arrayData = new int[]; public static void main(String[] args){ arrayData[0] = 10; arrayData[1] = 5; arrayData[2] = 6; arrayData[3] = 7; arrayData[4] = 1; arrayData[5] = 12; arrayData[6] = 13; Question Answer Marks 2(a) arrayData[7] = 15; arrayData[8] = 21; arrayData[9] = 8; } 2(b)(i) 1 mark per bullet point • function linearSearch with correct identifier • …taking integer search value as a parameter • Searching 10 times/through all array elements … • …comparing each element to search value • returning True if found • returning False if not found Example code: Visual Basic Function linearSearch(ByRef searchValue As Integer) For x = 0 To 9 If arrayData(x) = searchValue Then Return True End If Next Return False End Function 6 Question Answer Marks 2(b)(i) Python def linearSearch(searchValue): for x in range(0, 10): if arrayData[x] == searchValue: return True return False Java public static Boolean linearSearch(Integer searchValue){ for (int x = 0; x < 10; x++){ if(arrayData[x] == searchValue){ return true; } } return false; } Question Answer Marks 2(b)(ii) 1 mark per bullet point to max 4 • Taking value as input… • …checking/casting to Integer • Calling linearSearch and sending input as parameter • Storing and checking return value… • …outputting appropriate message if found and if not found Example code: Visual Basic Dim arrayData(10) As Integer Sub Main() arrayData(0) = 10 arrayData(1) = 5 arrayData(2) = 6 arrayData(3) = 7 arrayData(4) = 1 arrayData(5) = 12 arrayData(6) = 13 arrayData(7) = 15 arrayData(8) = 12 arrayData(9) = 8 Console.WriteLine("Enter a number to search for") Dim searchValue As Integer = Console.ReadLine() Dim returnValue As Boolean = linearSearch(searchValue) If returnValue = True Then Console.WriteLine("Found it") Else Console.WriteLine("Didn't find it") End If End Sub 4 Question Answer Marks 2(b)(ii) Python arrayData = [10, 5, 6, 7, 1, 12, 13, 15, 21, 8] searchValue = int(input("Enter the number to search for")) returnValue = linearSearch(searchValue) if returnValue == True: print("It was found") else: print("It was not found") Java Integer[] arrayData = new Integer[10]; public static void main(String[] args){ arrayData[0] = 10; arrayData[1] = 5; arrayData[2] = 6; arrayData[3] = 7; arrayData[4] = 1; arrayData[5] = 12; arrayData[6] = 13; arrayData[7] = 15; arrayData[8] = 12; arrayData[9] = 8; System.out.println("Enter the number to search for"); Integer searchValue; Scanner in = new Scanner(System.in); searchValue = in.nextInt(); Boolean returnValue; returnValue = linearSearch(searchValue); if (returnValue == true){ System.out.println("It was found"); }else{ System.out.println("It was not found"); } } Question Answer Marks 2(b)(iii) 1 mark for screenshot showing input and output for number found 1 mark for screenshot showing input and output for number not found 2 2(c) 1 mark per bullet point • Correct outer loop stop • Correct inner loop stop • Correct < in the IF • Correct theArray(y + 1) • Correct temp • Remainder matching pseudocode Example code: Visual Basic Sub bubbleSort() Dim temp As Integer = 0 For x = 0 To 9 For y = 0 To 8 If theArray(y) < theArray(y + 1) Then temp = theArray(y) theArray(y) = theArray(y + 1) theArray(y + 1) = temp End If Next Next End Sub 6 Question Answer Marks 2(c) Python def bubbleSort(): for x in range (0, 10): for y in range(0, 9): if theArray[y] < theArray[y + 1]: temp = theArray[y] theArray[y] = theArray[y + 1] theArray[y + 1] = temp Java public static void bubbleSort(){ int temp; for (int x = 0; x < 10; x++){ for (int y = 0; y < 9; y++){ if(theArray[y] < theArray[y+1]){ temp = theArray[y]; theArray[y] = theArray[y+1]; theArray[y+1] = temp; } } } }
1 An unordered linked list uses a 1D array to store the data. Each item in the linked list is of a record type, node, with a field data and a field nextNode. The current contents of the linked list are: startPointer 0 Index data nextNode 0 1 1 emptyList 5 1 5 4 2 6 7 3 7 -1 4 2 2 5 0 6 6 0 8 7 56 3 8 0 9 9 0 -1 (a) The following is pseudocode for the record type node. TYPE node DECLARE data : INTEGER DECLARE nextNode : INTEGER ENDTYPE Write program code to declare the record type node. Save your program as question1. Copy and paste the program code into part 1(a) in the evidence document. [2] (b) Write program code for the main program. Declare a 1D array of type node with the identifier linkedList, and initialise it with the data shown in the table on page 2. Declare the pointers. Save your program. Copy and paste the program code into part 1(b) in the evidence document. [4] (c) The procedure outputNodes() takes the array and startPointer as parameters. The procedure outputs the data from the linked list by following the nextNode values. (i) Write program code for the procedure outputNodes(). Save your program. Copy and paste the program code into part 1(c)(i) in the evidence document. [6] (ii) Edit the main program to call the procedure outputNodes(). Take a screenshot to show the output of the procedure outputNodes(). Save your program. Copy and paste the screenshot into part 1(c)(ii) in the evidence document. [1] (d) The function, addNode(), takes the linked list and pointers as parameters, then takes as input the data to be added to the end of the linkedList. The function adds the node in the next available space, updates the pointers and returns True. If there are no empty nodes, it returns False. (i) Write program code for the function addNode(). Save your program. Copy and paste the program code into part 1(d)(i) in the evidence document. [7] (ii) Edit the main program to: • call addNode() • output an appropriate message depending on the result returned from addNode() • call outputNodes() twice; once before calling addNode() and once after calling addNode(). Save your program. Copy and paste the program code into part 1(d)(ii) in the evidence document. [3] (iii) Test your program by inputting the data value 5 and take a screenshot to show the output. Save your program. Copy and paste the screenshot into part 1(d)(iii) in the evidence document. [1]
24 marks
Mark scheme: 1(a) 1 mark per bullet point • Declaring record/class with name node… • …declaring data and next node (both as Integers) Example code: Visual Basic Structure node Dim Data As Integer Dim nextNode As Integer End Structure Python class node: def __init__(self, theData, nextNodeNumber): self. Data = theData self.nextNode = nextNodeNumber Java class node{ private Integer Data; private Integer nextNode; public node(Integer dataP, Integer nextNodeP){ this.Data = dataP; this.nextNode = nextNodeP; } } Question Answer Marks 1(b) 1 mark per bullet point • Declaring array named linkedList with data type node • Assigning all nodes correctly as record/object nodes … • …with correct values stored • declaring startPointer as 0, emptyList as 5 Example code: Visual Basic Dim linkedList(9) As node linkedList(0).data = 1 linkedList(0).nextNode = 1 linkedList(1).data = 5 linkedList(1).nextNode = 4 linkedList(2).data = 6 linkedList(2).nextNode = 7 linkedList(3).data = 7 linkedList(3).nextNode = -1 linkedList(4).data = 2 linkedList(4).nextNode = 2 linkedList(5).data = 0 linkedList(5).nextNode = 6 linkedList(6).data = 0 linkedList(6).nextNode = 8 linkedList(7).data = 56 linkedList(7).nextNode = 3 linkedList(8).data = 0 linkedList(8).nextNode = 9 linkedList(9).data = 0 linkedList(9).nextNode = -1 Dim startPointer As Integer = 0 Dim emptyList As Integer = 5 4 Question Answer Marks 1(b) Python linkedList = [node(1,1),node(5,4),node(6,7),node(7,-1),node(2,2),node(0,6), node(0,8),node(56,3),node(0,9),node(0,-1)] startPointer = 0 emptyList = 5 Java public static void main(String[] args){ node[] linkedList = new node[10]; linkedList[0] = new node(1,1); linkedList[1] = new node(5, 4); linkedList[2] = new node(6, 7); linkedList[3] = new node(7,-1); linkedList[4] = new node(2,2); linkedList[5] = new node(0,6); linkedList[6] = new node(0,8); linkedList[7] = new node(56, 3); linkedList[8] = new node(0,9); linkedList[9] = new node(0,-1); Integer startPointer = 0; Integer emptyList = 5; } Question Answer Marks 1(c)(i) 1 mark per bullet point • Procedure outputNodes … • …taking linked list and start pointer as parameters • Looping until nextNode/pointer is –1 • Outputting the node data in the correct order, i.e. following pointers • Updating pointer to current node’s nextNode • Using the correct record/class field/properties throughout Example code: Visual Basic Sub outputNodes(ByRef linkedList, ByVal currentPointer) While (currentPointer <> -1) Console.WriteLine(linkedList(currentPointer).data) currentPointer = linkedList(currentPointer).nextNode End While End Sub Python def outputNodes(linkedList, currentPointer): while(currentPointer != -1): print(str(linkedList[currentPointer].data)) currentPointer = linkedList[currentPointer].nextNode Java public static void outputNodes(node[] linkedList, Integer currentPointer){ while(currentPointer != -1){ System.out.println(linkedList[currentPointer].data); currentPointer = linkedList[currentPointer].nextNode; } } 6 Question Answer Marks 1(c)(ii) Screenshot showing: 1 5 2 6 56 7 1 1(d)(i) 1 mark per bullet point to max 7 • Function taking list and both pointers as parameters • Taking (integer) data as input • Checking if list is full … • … and returning False • Insert the input data to the empty list node’s data • Following pointers to find last node in Linked List … • …and updating last node’s pointer to empty list/location where new node is added • Updating empty list to it’s first elements pointer • Returning true when added successfully Example code: Visual Basic Function addNode(ByRef linkedList() As node, ByVal currentPointer As Integer, ByRef emptyList As Integer) Console.WriteLine("Enter the data to add") Dim dataToAdd As Integer = Console.ReadLine() Dim previousPointer As Integer = 0 Dim newNode As node If emptyList < 0 Or emptyList > 9 Then Return False Else newNode.data = dataToAdd newNode.nextNode = -1 7 Question Answer Marks 1(d)(i) linkedList(emptyList) = newNode previousPointer = 0 While (currentPointer <> -1) previousPointer = currentPointer currentPointer = linkedList(currentPointer).nextNode End While Dim valueToWrite As Integer = emptyList linkedList(previousPointer).nextNode = valueToWrite emptyList = linkedList(emptyList).nextNode Return True End If End Function Python def addNode(linkedList, currentPointer, emptyList): dataToAdd = input("Enter the data to add") if emptyList <0 or emptyList > 9: return False else: newNode = node(int(dataToAdd), -1) linkedList[emptyList] = (newNode) previousPointer = 0 while(currentPointer != -1): previousPointer = currentPointer currentPointer = linkedList[currentPointer].nextNode linkedList[previousPointer].nextNode = emptyList emptyList = linkedList[emptyList].nextNode return True Question Answer Marks 1(d)(i) Java public static Boolean addNode(node[] linkedList, Integer currentPointer, Integer emptyList){ Integer dataToAdd; Integer previousPointer; node newNode; Scanner in = new Scanner(System.in); System.out.println("Enter the data to add"); dataToAdd = in.nextInt(); if(emptyList < 0 || emptyList > 9){ return false; }else{ newNode = new node(dataToAdd, -1); linkedList[emptyList] = newNode; previousPointer = 0; while(currentPointer != -1){ previousPointer = currentPointer; currentPointer = linkedList[currentPointer].nextNode; } linkedList[previousPointer].nextNode = emptyList; emptyList = linkedList[emptyList].nextNode; return true; } } Question Answer Marks 1(d)(ii) 1 mark per bullet point • Call addNode() with list, start and empty pointers and store/check return value … • …output appropriate message if True returned and if False returned • Calling outputNodes() with list and start pointer before and after addNode() Example code: Visual Basic Sub Main() Dim linkedList(10) As node linkedList(0).data = 1 linkedList(0).nextNode = 1 linkedList(1).data = 5 linkedList(1).nextNode = 4 linkedList(2).data = 6 linkedList(2).nextNode = 7 linkedList(3).data = 7 linkedList(3).nextNode = -1 linkedList(4).data = 2 linkedList(4).nextNode = 2 linkedList(5).data = -1 linkedList(5).nextNode = 6 linkedList(6).data = -1 linkedList(6).nextNode = 7 linkedList(7).data = 56 linkedList(7).nextNode = 3 linkedList(8).data = -1 linkedList(8).nextNode = 9 linkedList(9).data = -1 linkedList(9).nextNode = -1 Dim startPointer As Integer = 0 Dim emptyList As Integer = 5 outputNodes(linkedList, startPointer) Dim returnValue As Boolean returnValue = addNode(linkedList, startPointer, emptyList) 3 Question Answer Marks 1(d)(ii) If returnValue = True Then Console.WriteLine("Item successfully added") Else Console.WriteLine("Item not added, list full") End If outputNodes(linkedList, startPointer) Console.ReadLine() End Sub Python linkedList = [node(1,1),node(5,4),node(6,7),node(7,-1),node(2,2),node(-1,6), node(-1,7),node(56,3),node(-1,9),node(-1,-1)] startPointer = 0 emptyList = 5 outputNodes(linkedList, startPointer) returnValue = addNode(linkedList, startPointer, emptyList) if returnValue == True: print("Item successfully added") else: print("Item not added, list full") outputNodes(linkedList, startPointer) Java public static void main(String[] args){ node[] linkedList = new node[10]; linkedList[0] = new node(1,1); linkedList[1] = new node(5, 4); linkedList[2] = new node(6, 7); linkedList[3] = new node(7,-1); linkedList[4] = new node(2,2); linkedList[5] = new node(-1,6); linkedList[6] = new node(-1,7); linkedList[7] = new node(56, 3); linkedList[8] = new node(-1,9); Question Answer Marks 1(d)(ii) linkedList[9] = new node(-1,-1); Integer startPointer = 0; Integer emptyList = 5; outputNodes(linkedList, startPointer); Boolean returnValue; returnValue = addNode(linkedList, startPointer, emptyList); if (returnValue == true){ System.out.println("Item successfully added"); }else{ System.out.println("Item not added, list full"); } outputNodes(linkedList, startPointer); } 1(d)(iii) 1 mark for screenshot showing : • Linked list output • 5 input • Message saying Successfully added or equivalent • Linked list output with 5 at the end. Example: 1 5 2 6 56 7 5 (being input) 1 5 2 6 56 7 5 1
2 A program stores the following ten integers in a 1D array with the identifier arrayData. 10 5 6 7 1 12 13 15 21 8 (a) Write program code for a new program to: • declare the global 1D array, arrayData, with ten elements • initialise arrayData in the main program using the data values shown. Save your program as question2. Copy and paste the program code into part 2(a) in the evidence document. [2] (b) (i) A function, linearSearch(), takes an integer as a parameter and performs a linear search on arrayData to find the parameter value. It returns True if it was found and False if it was not found. Write program code for the function linearSearch(). Save your program. Copy and paste the program code into part 2(b)(i) in the evidence document. [6] (ii) Edit the main program to: • allow the user to input an integer value • pass the value to linearSearch() as the parameter • output an appropriate message to tell the user whether the search value was found or not. Save your program. Copy and paste the program code into part 2(b)(ii) in the evidence document. [4] (iii) Test your program with one value that is in the array and one value that is not in the array. Take a screenshot to show the result of each test. Save your program. Copy and paste the screenshots into part 2(b)(iii) in the evidence document. [2] (c) The following bubble sort pseudocode algorithm sorts the data in theArray into descending numerical order. There are five incomplete statements. PROCEDURE bubbleSort() DECLARE temp : INTEGER FOR x 0 to ………………………………… FOR y 0 to ………………………………… IF theArray[y] ………………………………… theArray[y + 1] THEN temp theArray[y] theArray[y] theArray[y + 1] ENDIF NEXT y NEXT x ENDPROCEDURE Write program code for the procedure bubbleSort() to sort the data in arrayData into descending order. Save your program. Copy and paste the program code into part 2(c) in the evidence document. [6]
20 marks
Mark scheme: 2(a) 1 mark per bullet point • Array with identifier arrayData • correct 10 data items added Example code: Visual Basic Dim arrayData(9) As Integer Sub Main() arrayData(0) = 10 arrayData(1) = 5 arrayData(2) = 6 arrayData(3) = 7 arrayData(4) = 1 arrayData(5) = 12 arrayData(6) = 13 arrayData(7) = 15 arrayData(8) = 21 arrayData(9) = 8 End Sub Python arrayData = [10, 5, 6, 7, 1, 12, 13, 15, 21, 8] Java int[] arrayData = new int[]; public static void main(String[] args){ arrayData[0] = 10; arrayData[1] = 5; arrayData[2] = 6; arrayData[3] = 7; arrayData[4] = 1; arrayData[5] = 12; arrayData[6] = 13; Question Answer Marks 2(a) arrayData[7] = 15; arrayData[8] = 21; arrayData[9] = 8; } 2(b)(i) 1 mark per bullet point • function linearSearch with correct identifier • …taking integer search value as a parameter • Searching 10 times/through all array elements … • …comparing each element to search value • returning True if found • returning False if not found Example code: Visual Basic Function linearSearch(ByRef searchValue As Integer) For x = 0 To 9 If arrayData(x) = searchValue Then Return True End If Next Return False End Function 6 Question Answer Marks 2(b)(i) Python def linearSearch(searchValue): for x in range(0, 10): if arrayData[x] == searchValue: return True return False Java public static Boolean linearSearch(Integer searchValue){ for (int x = 0; x < 10; x++){ if(arrayData[x] == searchValue){ return true; } } return false; } Question Answer Marks 2(b)(ii) 1 mark per bullet point to max 4 • Taking value as input… • …checking/casting to Integer • Calling linearSearch and sending input as parameter • Storing and checking return value… • …outputting appropriate message if found and if not found Example code: Visual Basic Dim arrayData(10) As Integer Sub Main() arrayData(0) = 10 arrayData(1) = 5 arrayData(2) = 6 arrayData(3) = 7 arrayData(4) = 1 arrayData(5) = 12 arrayData(6) = 13 arrayData(7) = 15 arrayData(8) = 12 arrayData(9) = 8 Console.WriteLine("Enter a number to search for") Dim searchValue As Integer = Console.ReadLine() Dim returnValue As Boolean = linearSearch(searchValue) If returnValue = True Then Console.WriteLine("Found it") Else Console.WriteLine("Didn't find it") End If End Sub 4 Question Answer Marks 2(b)(ii) Python arrayData = [10, 5, 6, 7, 1, 12, 13, 15, 21, 8] searchValue = int(input("Enter the number to search for")) returnValue = linearSearch(searchValue) if returnValue == True: print("It was found") else: print("It was not found") Java Integer[] arrayData = new Integer[10]; public static void main(String[] args){ arrayData[0] = 10; arrayData[1] = 5; arrayData[2] = 6; arrayData[3] = 7; arrayData[4] = 1; arrayData[5] = 12; arrayData[6] = 13; arrayData[7] = 15; arrayData[8] = 12; arrayData[9] = 8; System.out.println("Enter the number to search for"); Integer searchValue; Scanner in = new Scanner(System.in); searchValue = in.nextInt(); Boolean returnValue; returnValue = linearSearch(searchValue); if (returnValue == true){ System.out.println("It was found"); }else{ System.out.println("It was not found"); } } Question Answer Marks 2(b)(iii) 1 mark for screenshot showing input and output for number found 1 mark for screenshot showing input and output for number not found 2 2(c) 1 mark per bullet point • Correct outer loop stop • Correct inner loop stop • Correct < in the IF • Correct theArray(y + 1) • Correct temp • Remainder matching pseudocode Example code: Visual Basic Sub bubbleSort() Dim temp As Integer = 0 For x = 0 To 9 For y = 0 To 8 If theArray(y) < theArray(y + 1) Then temp = theArray(y) theArray(y) = theArray(y + 1) theArray(y + 1) = temp End If Next Next End Sub 6 Question Answer Marks 2(c) Python def bubbleSort(): for x in range (0, 10): for y in range(0, 9): if theArray[y] < theArray[y + 1]: temp = theArray[y] theArray[y] = theArray[y + 1] theArray[y + 1] = temp Java public static void bubbleSort(){ int temp; for (int x = 0; x < 10; x++){ for (int y = 0; y < 9; y++){ if(theArray[y] < theArray[y+1]){ temp = theArray[y]; theArray[y] = theArray[y+1]; theArray[y+1] = temp; } } } }
2 A 2D array stores data entered by a user. (a) The main program declares a 2D array of 10 by 10 integer elements. The array is initialised with a random number between 1 and 100 in each element. Write program code for the main program. Save your program as Question2_J22. Copy and paste the program code into part 2(a) in the evidence document. [4] (b) The following bubble sort pseudocode algorithm sorts the data in the first dimension of the 2D array into ascending numerical order. ArrayLength 10 FOR X 0 TO ArrayLength - 1 FOR Y 0 TO ArrayLength - 2 FOR Z 0 TO ArrayLength - Y - 2 IF ArrayData[X, Z] > ArrayData[X, Z + 1] THEN TempValue ArrayData[X, Z] ArrayData[X, Z] ArrayData[X, Z+1] ArrayData[X, Z + 1] TempValue ENDIF NEXT Z NEXT Y NEXT X (i) Amend your main program by writing program code to implement the bubble sort algorithm after the initialisation of the array elements. You must not use any built-in sorting functions for your programming language. Save your program. Copy and paste the program code into part 2(b)(i) in the evidence document. [5] (ii) Write program code for a procedure to output all the values in the 2D array. The values should be output as a 2D grid, with values in rows and columns. Call the procedure before and after your bubble sort code. Save your program. Copy and paste the program code into part 2(b)(ii) in the evidence document. [3] (iii) Test your program. Take a screenshot to show the output. Copy and paste the screenshot into part 2(b)(iii) in the evidence document. [1] (c) The following pseudocode function uses recursion to perform a binary search in the first row of the array, for the value SearchValue in the array SearchArray. The function returns −1 if the item was not found, or it returns the index where it is found. There are six incomplete statements. FUNCTION BinarySearch(SearchArray, Lower, Upper, SearchValue)RETURNS INTEGER IF Upper >= Lower THEN Mid (Lower + (Upper – 1)) DIV ………………………………… IF SearchArray[0, Mid] = ………………………………… THEN RETURN ………………………………… ELSE IF SearchArray[0, Mid] > SearchValue THEN RETURN BinarySearch(SearchArray, …………………………………, Mid – 1, SearchValue) ELSE RETURN BinarySearch(SearchArray, Mid + 1, …………………………………, SearchValue) ENDIF ENDIF ENDIF RETURN ………………………………… ENDFUNCTION Note: the arithmetic operator DIV performs integer division, e.g. the result of 10 DIV 3 will be 3. (i) Write program code for the recursive function BinarySearch(). Save your program. Copy and paste the program code into part 2(c)(i) in the evidence document. [8] (ii) In the main program, test the function BinarySearch() twice, outputting the returned value each time. One test should be for a number that is in the first line of the array. One test should be for a number that is not in the first line of the array. Take a screenshot to show the output. Copy and paste the screenshot into part 2(c)(ii) in the evidence document. [2]
23 marks
Mark scheme: 2(a) 1 mark per mark point in main local 2D array declared … … with 10 10 integer elements initialising all array elements to a number… …that is random between 1 and 100 (allow inclusive or exclusive) Example program code: VB.NET Sub Main() Dim Random As New Random Dim ArrayData(10, 10) As Integer For x = 0 To 9 For y = 0 To 9 ArrayData(x, y) = Random.Next(1, 100) Next Next Console.ReadLine() End Sub Python import random #main ArrayData= [[0]*10 for i in range(10)] #integer for x in range(0, 10): for y in range(0,10): ArrayData[x][y] = random.randint(1, 100) Question Answer Marks 2(a) Java import java.util.Scanner; import java.util.Random; class Question2{ public static Integer[][] ArrayData; public static void main(String args[]){ Random Rand = new Random(); ArrayData = new Integer[10][10]; for(int x=0; x < 10; x++){ for(int y = 0; y < 10; y++){ ArrayData[x][y] = Rand.nextInt(100);} } } } Question Answer Marks 2(b)(i) 1 mark per mark point 1st outer loop (dimension 1) 2nd loop (dimension 2) inner for loop for all second dimension Selection statement … …swapping the numbers correctly Example program code: VB.NET Dim TempNumber As Integer Dim ArrayLength As Integer = 10 For X = 0 To ArrayLength - 1 For Y = 0 To ArrayLength - 2 For Z = 0 To ArrayLength - Y - 2 if ArrayData(X, Z) > ArrayData(X, Z + 1) then TempNumber = ArrayData(X, Z) ArrayData(X, Z) = ArrayData(X, Z+1) ArrayData(X, Z + 1) = TempNumber end if Next Z Next Y Next X Python ArrayLength = 10 for X in range(0, ArrayLength): for Y in range(0, ArrayLength-1): for Z in range(0, ArrayLength - Y - 1): if(ArrayData[X][Z] > ArrayData[X][Z+1]): TempNumber = ArrayData[X][Z] ArrayData[X][Z] = ArrayData[X][Z+1] ArrayData[X][Z+1] = TempNumber Accept for MP5: ArrayData[X][Z], ArrayData[X][Z+1] = ArrayData[X][Z+1], ArrayData[X][Z] 5 Question Answer Marks 2(b)(i) Java Integer ArrayLength = 10; for(int X = 0; X < ArrayLength; X++){ for(int Y = 0; Y < ArrayLength; Y++){ for(int Z = 0; Z < ArrayLength - Y - 1; Z++){ if(ArrayData[X][Z] > ArrayData[X][Z + 1]){ TempNumber = ArrayData[X][Z]; ArrayData[X][Z] = ArrayData[X][Z+1]; ArrayData[X][Z + 1] = TempNumber; } } } } Question Answer Marks 2(b)(ii) 1 mark per mark point procedure header (and end where appropriate) Outputting all 10 10 values with each 2nd dimension on a complete line Calling procedure before and after bubble sort Example program code: VB.NET Sub Main() Dim random As New Random Dim ArrayData(10, 10) As Integer For x = 0 To 9 For y = 0 To 9 ArrayData(x, y) = random.Next(1, 100) Next Next Console.WriteLine("before") printarray(ArrayData) Dim TempNumber As Integer Dim ArrayLength As Integer = 10 For X = 0 To ArrayLength - 1 For Y = 0 To ArrayLength - 2 For Z = 0 To ArrayLength - Y - 2 if ArrayData(X, Z) > ArrayData(X, Z + 1) then TempNumber = ArrayData(X, Z) ArrayData(X, Z) = ArrayData(X, Z+1) ArrayData(X, Z + 1) = TempNumber end if Next Z Next Y Next X Console.WriteLine("after") printarray(ArrayData) Console.ReadLine() End Sub 3 Question Answer Marks 2(b)(ii) Sub Printarray(ByRef ArrayData(,) As Integer) For x = 0 To 9 For y = 0 To 9 Console.Write(ArrayData(x, y) & " ") Next Console.WriteLine() Next End Sub Python import random def Printarray(ArrayData): for x in range(0, 10): for y in range(0, 10): print(ArrayData[x][y], " ", end='') print("") #main ArrayData= [[0]*10 for i in range(10)] #integer for x in range(0, 10): for y in range(0,10): ArrayData[x][y] = random.randint(1, 100) print("Before") printarray(ArrayData) ArrayLength = 10 for X in range(0, ArrayLength): for Y in range(0, ArrayLength): for Z in range(0, ArrayLength - Y - 1): if(ArrayData[X][Z] > ArrayData[X][Z+1]): TempNumber = ArrayData[X][Z] ArrayData[X][Z] = ArrayData[X][Z+1] ArrayData[X][Z+1] = TempNumber print("After") Printarray(ArrayData) Question Answer Marks 2(b)(ii) Java import java.util.Scanner; import java.util.Random; class Question2{ public static Integer[][] ArrayData; public static void printArray(Integer[][] theArrayData){ for(int x = 0; x < 10; x++){ for(int y = 0; y < 10; y++){ System.out.printf(theArrayData[x][y] + " "); } System.out.println(); } } public static void main(String args[]){ Random rand = new Random(){ ArrayData = new Integer[10][10]; for(int x=0; x < 10; x++){ for(int y = 0; y < 10; y++){ ArrayData[x][y] = rand.nextInt(100); } } Integer TempNumber = 0; System.out.println("Before"); printArray(ArrayData); Integer ArrayLength = 10; for(int X = 0; X < ArrayLength; X++){ for(int Y = 0; Y < ArrayLength; Y++){ for(int Z = 0; Z < ArrayLength - Y - 1; Z++){ if(ArrayData[X][Z] > ArrayData[X][Z + 1]){ Question Answer Marks 2(b)(ii) TempNumber = ArrayData[X][Z]; ArrayData[X][Z] = ArrayData[X][Z+1]; ArrayData[X][Z + 1] = TempNumber; } } } } System.out.println("After"); PrintArray(ArrayData); } } Question Answer Marks 2(b)(iii) 1 mark for output showing array unsorted and then sorted on 1 of the dimensions e.g. 1 Question Answer Marks 2(c)(i) 1 mark for each completed statement (6) 1 mark per mark point function declaration taking appropriate parameters and recursive calls remainder of the function is accurate including appropriate DIV operator. Example program code: VB.NET Function BinarySearch(ByVal SearchArray(,) As Integer, Lower As Integer, Upper As Integer, SearchValue As Integer) Dim Mid As Integer If Upper >= 0 Then Mid = (Lower + (Upper - 1)) \ 2 If SearchArray(0, Mid) = SearchValue Then Return Mid ElseIf SearchArray(0, Mid) > SearchValue Then Return BinarySearch(SearchArray, Lower, Mid - 1, SearchValue) Else Return BinarySearch(SearchArray, Mid + 1, Upper, SearchValue) End If End If Return -1 End Function Python def BinarySearch(SearchArray, Lower, Upper, SearchValue): if Upper >= 0: Mid = int((Lower + (Upper - 1)) / 2) If SearchArray[0][Mid] == SearchValue: return Mid elif SearchArray[0][Mid] > SearchValue: return BinarySearch(SearchArray, Lower, Mid-1, SearchValue) else: return BinarySearch(SearchArray, Mid+1, Upper, SearchValue) return -1 8 Question Answer Marks 2(c)(i) Java public static Integer BinarySearch(Integer[][] SearchArray, Integer Lower, Integer Upper, Integer SearchValue){ Integer Mid = 0; If Upper >= 0 { Mid = (Lower + (Upper - 1)) / 2; If SearchArray[0][Mid] == SearchValue ){ return Mid; }else if SearchArray[0][Mid] > SearchValue { return BinarySearch(SearchArray, Lower, Mid-1, SearchValue); }else{ return BinarySearch(SearchArray, Mid+1, Upper, SearchValue); } } return -1; } Question Answer Marks 2(c)(ii) 1 mark per mark point screenshot outputting the index when Number is found screenshot outputting –1 with a Number not found e.g. 2
1 The text file IntegerData.txt stores 100 integer numbers between 1 and 100 inclusive. A program is required to read in this data and perform searching and sorting on the data. (a) Write program code to declare a global 1D array, DataArray, with space for 100 integer values. Save your program as Question1_N22. Copy and paste the program code into part 1(a) in the evidence document. [2] (b) The procedure ReadFile() must read in the numbers from the text file and store each one in the array. Use appropriate exception handling. Write program code for the procedure ReadFile(). Save your program. Copy and paste the program code into part 1(b) in the evidence document. [6] (c) The function FindValues() asks the user to enter a number to search for in the array. The number input must be a whole number between 1 and 100 inclusive. The function then returns the number of times the number input appears in the array. Write program code for the function FindValues(). Save your program. Copy and paste the program code into part 1(c) in the evidence document. [7] (d) (i) Write program code to call ReadFile() and FindValues() from the main program. The return value from FindValues() must be output with an appropriate message. Save your program. Copy and paste the program code into part 1(d)(i) in the evidence document. [3] (ii) Test your program using the number 61 as input. Take a screenshot to show the output. Copy and paste the screenshot into part 1(d)(ii) in the evidence document. [1] (e) The procedure BubbleSort() needs to perform a bubble sort on the array and print the contents of the sorted array. Write program code for the procedure BubbleSort() and call it from the main program. Save your program. Copy and paste the program code into part 1(e) in the evidence document. [4]
23 marks
Mark scheme: Question Answer Marks 1(a) 1 mark per point: 2 • (global) 1D (Integer) array DataArray • 100 elements Example program code: Python DataArray = [0 for I in range (100)] Java public static Integer[] DataArray = new Integer[100]; VB.NET Dim DataArray(99) As Integer 1(b) 1 mark per point: 6 • Procedure ReadFile() header (and end where appropriate) • opening file IntegerData.txt (for read) • looping through the 100 elements // looping to end of file • reading each (and all) value from file and storing in array • closing file (in appropriate place) 1 mark per point: • Exception Handling (for opening the file, or for reading values from the file)… • …with appropriate catch and output messages Example program code: Python def ReadFile(): global DataArray try: TextFile = "IntegerData.txt" File = open(TextFile, 'r') for X in range(0, 100): DataArray[X] = File.readline() DataArray[X].rstrip('\n') DataArray[X] = int(DataArray[X]) File.close() except IOError: print("Count not find file") 1(b) Java public static void ReadFile(){ String Filename = "IntegerData.txt"; try{ FileReader F = new FileReader(Filename); BufferedReader Reader = new BufferedReader(F); for(Integer X = 0; X < 100; X++){ DataArray[X] = Integer.parseInt(Reader.readLine()); } Reader.close(); } catch(FileNotFoundException ex){ System.out.println("No file found"); } catch(IOException ex){ System.out.println("No file found"); } } VB.NET Sub ReadFile() try Dim TextFile As String = "IntegerData.txt" Dim FileReader As New System.IO.StreamReader(TextFile) For X = 0 To 99 DataArray(X) = FileReader.ReadLine() Next FileReader.Close() Catch ex As Exception Console.WriteLine("Invalid file") End Try End Sub 1(c) 1 mark per point: 7 • Function FindValues() (and end where appropriate) and input of data to search for in the array • …validation/casting(/storing as) of input as integer • …validation of input between 1 and 100 (inclusive) • looping through all 100 array elements… • …comparing input to each array element… • …initialising counter to 0 and then adding 1 each time it is found… • Returning the total 1(c) Example program code: Python def FindValues(): global DataArray DataToFind = -1 while(DataToFind < 1 or DataToFind > 100): DataToFind = int(input("Enter a number between 1 and 100")) Total = 0 for X in range(0, 99): if DataArray[X] == DataToFind: Total = Total + 1 return Total VB.NET Function FindValues() Dim DataToFind As Integer Do Console.WriteLine("Enter a number between 1 and 100") DataToFind = Console.ReadLine() Loop Until (DataToFind >= 1 And DataToFind <= 100) Dim Total As Integer = 0 For X = 0 To 99 If DataArray(X) = DataToFind Then Total = Total + 1 End If Next Return Total End Function Java public static Integer FindValues(){ Integer DataToFind = -1; while(DataToFind < 1 || DataToFind > 100){ System.out.println("Enter a number between 1 and 100"); Scanner in = new Scanner(System.in); DataToFind = in.nextInt(); } Integer Total = 0; for(Integer X = 0; X < 100; X++){ if(DataArray[X] == DataToFind){ Total = Total + 1; } } return Total; } 1(d)(i) 1 mark per point: 3 • Calling ReadFile() and then FindValues() (in the main program) • storing/using return value from FindValues() … • …outputting return value with appropriate message Example program code: Python ReadFile() print("The number appears " + str(FindValues()) + " times") Java public static void main(String[] args){ ReadFile(); Integer ReturnValue = FindValues(); System.out.println("The number was found " + ReturnValue + " times"); } VB.NET Sub Main() ReadFile() Dim ReturnValue As Integer = FindValues() Console.WriteLine("The number was found " & ReturnValue & " times") End Sub 1(d)(ii) Screenshot showing 61 input and 2 output, e.g. 1 1(e) 1 mark per point: 4 • procedure declaration (and end where appropriate) and outputting array contents at end of procedure and calling procedure from main program • correct outer loop … • … correct inner loop … • … swapping all elements if in incorrect order Example program code: Python def BubbleSort(): global DataArray N = 100 for I in range(N-1): for J in range(0, N-I-1): if DataArray[J] > DataArray[J+1]: DataArray[J], DataArray[J+1] = DataArray[J+1], DataArray[J] #main ReadFile() print("The number appears " + str(FindValues()) + " times") BubbleSort() print(DataArray) Java public static void BubbleSort(){ Integer Temp = 0; for(Integer I = 0; I < 100-1; I++){ for(Integer J = 0; J < 100-I-1; J++){ if(DataArray[J] > DataArray[J+1]){ Temp = DataArray[J]; DataArray[J] = DataArray[J+1]; DataArray[J+1] = Temp; } } } for(Integer X = 0; X < 100; X ++){ System.out.println(DataArray[X]); } } public static void main(String[] args){ ReadFile(); Integer ReturnValue = FindValues(); System.out.println("The number was found " + ReturnValue + " times"); BubbleSort(); } 1(e) VB.NET Sub Bubblesort() Dim Outer As Integer = 100 - 1 Dim Swap As Boolean Dim Inner As Integer Dim Temp As Integer Do Inner = 0 Swap = False Do If DataArray(Inner) > DataArray(Inner + 1) Then Temp = DataArray(Inner) DataArray(Inner) = DataArray(Inner + 1) DataArray(Inner + 1) = Temp Swap = True End If Inner = Inner + 1 Loop Until Inner = Outer Outer = Outer - 1 Loop Until Swap = False Or Outer = 0 For X = 0 To 99 Console.WriteLine(DataArray(X)) Next End Sub Sub Main() ReadFile() Dim ReturnValue As Integer = FindValues() Console.WriteLine("The number was found " & ReturnValue & " times") Bubblesort() End Sub
2 A computer program is being developed that uses a set of cards. The program is written using object-oriented programming. The program has two classes: Card and Hand. The methods and attributes of these classes are shown: Card Number : INTEGER stores the card number from 1 to 5 inclusive Colour : STRING stores the card colour: red, blue or yellow Constructor() takes a number and colour as parameters and sets the private values to these parameters GetNumber() returns the card number GetColour() returns the card colour Hand Cards : ARRAY[0:9] OF Card 1D array of type Card FirstCard : INTEGER stores the position of the first card in the hand NumberCards : INTEGER stores the number of cards in the hand Constructor() takes five card objects as parameters, assigns each card to the array Cards[], initialises FirstCard to 0 and NumberCards to 5 GetCard() takes an index as a parameter and returns the card at that index in the array (a) (i) Write program code to declare the class Card, its attributes and constructor. Do not write program code for the get methods. Use your programming language appropriate constructor. All attributes must be private. If you are writing in Python, include attribute declarations using comments. Save your program as Question2_N22. Copy and paste the program code into part 2(a)(i) in the evidence document. [5] (ii) Write program code for the class methods GetNumber() and GetColour(). Save your program. Copy and paste the program code into part 2(a)(ii) in the evidence document. [3] (iii) The program is tested with the following cards: Number Colour 1 red 2 red 3 red 4 red 5 red 1 blue 2 blue 3 blue 4 blue 5 blue 1 yellow 2 yellow 3 yellow 4 yellow 5 yellow Write program code to declare each of these cards as a variable of type Card in the main program. Save your program. Copy and paste the program code into part 2(a)(iii) in the evidence document. [2] (b) (i) Write program code to declare the class Hand, its attributes and constructor. Do not write the get methods. Use your programming language appropriate constructor. All attributes must be private. If you are writing in Python, include attribute declarations using comments. Save your program. Copy and paste the program code into part 2(b)(i) in the evidence document. [6] (ii) The get method GetCard() takes an index as a parameter and returns the card stored at that index in the array. Write program code for the method GetCard(). Save your program. Copy and paste the program code into part 2(b)(ii) in the evidence document. [2] (iii) Two players are declared with 5 cards each. Player 1 has the cards: 1 red, 2 red, 3 red, 4 red, 1 yellow. Player 2 has the cards: 2 yellow, 3 yellow, 4 yellow, 5 yellow, 1 blue. Write program code to declare player 1 and player 2 as objects of type Hand, with the cards indicated. Save your program. Copy and paste the program code into part 2(b)(iii) in the evidence document. [2] (c) The function CalculateValue() takes a player’s hand as a parameter and returns a score calculated using the following rules: • If a card is red, 5 points are added to the player’s score. • If a card is blue, 10 points are added to the player’s score. • If a card is yellow, 15 points are added to the player’s score. • The number of each card in the hand is added to the player’s score. (i) Write program code for the function CalculateValue(). Assume that there are only 5 cards in the player’s hand in this function. Save your program. Copy and paste the program code into part 2(c)(i) in the evidence document. [6] (ii) Amend the main program by writing program code to use the function CalculateValue() for each of the two players. The player with the highest score wins. Output an appropriate message to identify the winning player, or if the game was a draw (both players have the same number of points). Save your program. Copy and paste the program code into part 2(c)(ii) in the evidence document. [4] (iii) Test your program. Take a screenshot to show the output. Copy and paste the screenshot into part 2(c)(iii) in the evidence document. [1]
31 marks
Mark scheme: 2(a)(i) 1 mark per point: 5 • class Card declaration (and end where appropriate) • Private attributes declared Number as integer and Colour as string • constructor header (and end where appropriate)… • …taking 2 parameters • assigning parameters to attributes Example program code: Python class Card: #Number as integer #Colour as string def __init__(self, Number1, Colour1): self.__Number = Number1; self.__Colour = Colour1; 2(a)(i) Java class Card{ private Integer Number; private String Colour; public Card(Integer Number1, String Colourp){ Number = Number1; Colour = Colourp; }} VB.NET Class Card Private Number As Integer Private Colour As String Sub New(Number1, Colourp) Number = Number1 Colour = Colourp End Sub End Class 2(a)(ii) 1 mark per point: 3 • 1 get method as function (and end where appropriate) with no parameters… • …returning the value • 2nd correct get method Example program code: Python def GetNumber(self): return self.__Number def GetColour(self): return self.__Colour Java public Integer GetNumber(){ return Number; } public String GetColour(){ return Colour; } VB.NET Function GetNumber() Return Number End Function Function GetColour() Return Colour End Function 2(a)(iii) 1 mark per point: 2 • one card initialised as type Card … • … all 15 cards initialised correctly as type Card Example program code: Python OneRed = Card(1, "red") TwoRed = Card(2, "red") ThreeRed = Card(3, "red") FourRed = Card(4, "red") FiveRed = Card(5, "red") OneBlue = Card(1, "blue") TwoBlue = Card(2, "blue") ThreeBlue = Card(3, "blue") FourBlue = Card(4, "blue") FiveBlue = Card(5, "blue") OneYellow = Card(1, "yellow") TwoYellow = Card(2, "yellow") ThreeYellow = Card(3, "yellow") FourYellow = Card(4, "yellow") FiveYellow = Card(5, "yellow") Java CARD oneRed = new Card(1, "red"); CARD twoRed = new Card(2, "red"); CARD threeRed = new Card(3, "red"); CARD fourRed = new Card(4, "red"); CARD fiveRed = new Card(5, "red"); CARD oneBlue = new Card(1, "blue"); CARD twoBlue = new Card(2, "blue"); CARD threeBlue = new Card(3, "blue"); CARD fourBlue = new Card(4, "blue"); CARD fiveBlue = new Card(5, "blue"); CARD oneYellow = new Card(1, "yellow"); CARD twoYellow = new Card(2, "yellow"); CARD threeYellow = new Card(3, "yellow"); CARD fourYellow = new Card(4, "yellow"); CARD fiveYellow = new Card(5, "yellow"); 2(a)(iii) VB.NET Dim OneRed As New Card (1, "red") Dim TwoRed As New Card(2, "red") Dim ThreeRed As New Card(3, "red") Dim FourRed As New Card(4, "red") Dim FiveRed As New Card(5, "red") Dim OneBlue As New Card(1, "blue") Dim TwoBlue As New Card(2, "blue") Dim ThreeBlue As New Card(3, "blue") Dim FourBlue As New Card(4, "blue") Dim FiveBlue As New Card(5, "blue") Dim OneYellow As New Card(1, "yellow") Dim TwoYellow As New Card(2, "yellow") Dim ThreeYellow As New Card(3, "yellow") Dim FourYellow As New Card(4, "yellow") Dim FiveYellow As New Card(5, "yellow") 2(b)(i) 1 mark per point: 6 • class Hand declaration (and end where appropriate) • private attribute declarations; FirstCard as integer, NumberCards as integer • private attribute array named Cards of type Card with 10 elements • constructor with 5 Card objects as parameters • assigning each Card parameter to the array (in constructor) • initialising FirstCard to 0 and NumberCards to 5 (in constructor) Example program code: Python class Hand: #Cards[10] as Card #FirstCard as integer #NumberCards as integer def __init__(self, Card1, Card2, Card3, Card4, Card5): self.__Cards = [] self.__Cards.append(Card1) self.__Cards.append(Card2) self.__Cards.append(Card3) self.__Cards.append(Card4) self.__Cards.append(Card5) self.__FirstCard = 0 self.__NumberCards = 5 2(b)(i) Java class Hand{ private Card[] Cards = new Card[10]; private Integer FirstCard; private Integer NumberCards; public Hand(CARD Card1, CARD Card2, CARD Card3, CARD Card4, CARD Card5){ Cards[0] = Card1; Cards[1] = Card2; Cards[2] = Card3; Cards[3] = Card4; Cards[4] = Card5; FirstCard = 0; NumberCards = 5; } } VB.NET class Hand Private Cards(9) As Card Private FirstCard As Integer Private NumberCards As Integer Sub New(Card1, Card2, Card3, Card4, Card5) Cards(0) = Card1 Cards(1) = Card2 Cards(2) = Card3 Cards(3) = Card4 Cards(4) = Card5 FirstCard = 0 NumberCards = 5 End Sub End Class 2(b)(ii) 1 mark per point: 2 • function GetCard() header (and end where appropriate) taking (integer) parameter • returning the card at parameter index in array Example program code: Python def GetCard(self, Position): return self.__Cards[Position] Java public Card GetCard(Integer Position){ return Cards[Position]; } VB.NET Function GetCard(Position) Return Cards(Position) End Function 2(b)(iii) 1 mark per point: 2 • 2 variables (player 1 and player 2) of type Hand • using constructor and sending the correct variables as parameters Example program code: Python Player1 = Hand(OneRed, TwoRed, ThreeRed, FourRed, OneYellow) Player2 = Hand(TwoYellow, ThreeYellow, FourYellow, FiveYellow, OneBlue) Java Hand Player1 = new Hand(OneRed, TwoRed, ThreeRed, FourRed, OneYellow); Hand Player2 = new Hand(TwoYellow, ThreeYellow, FourYellow, FiveYellow, OneBlue); VB.NET Dim Player1 As New Hand(OneRed, TwoRed, ThreeRed, FourRed, OneYellow) Dim Player2 As New Hand(TwoYellow, ThreeYellow, FourYellow, FiveYellow, OneBlue) 2(c)(i) 1 mark per point: 6 • function CalculateValue() header (and end where appropriate) taking one parameter and initialising score to 0 • looping through all 5 Card objects in parameter array… • … adding 5 to score for red, 10 to score for blue, 15 to score if yellow • … adding each card number to score • Using GetCard(), GetColour() and GetNumber() correctly • Returning calculated score Example program code: Python def CalculateValue(Player): Score = 0 for Count in range(0, 4): CardGot = Player.GetCard(Count) Score = Score + CardGot.GetNumber() Colour = CardGot.GetColour() if Colour == "red": Score = Score + 5 elif Colour == "blue": Score = Score + 10 else: Score = Score + 15 return Score 2(c)(i) Java public static Integer CalculateValue(Hand Player){ Integer Score = 0; String Colour; Card CardGot; for(Integer X = 0; X<5; X++){ CardGot = Player.GetCard(X); Score = Score + CardGot.GetNumber(); Colour = CardGot.GetColour(); if(Colour == "red"){ Score = Score + 5; }else if(Colour == "blue"){ Score = Score + 10; } else { Score = Score + 15; }}return Score;} VB.NET Function CalculateValue(Player As Hand) Dim Score As Integer = 0 Dim Colour As String Dim CardGot As Card For Count = 0 To 4 CardGot = Player.GetCard(Count) Score = Score + CardGot.GetNumber() Colour = CardGot.GetColour() If Colour = "red" Then Score = Score + 5 ElseIf Colour = "blue" Then Score = Score + 10 Else Score = Score + 15 End If Next Return Score End Function 2(c)(ii) 1 mark per point: 4 • One function call of CalculateValue( ) for each player … • …sending the player's hand as parameter • Comparing return values and outputting the player with the highest score in an appropriate message … • … or if there was a draw in appropriate message Example program code: Python Player1score = CalculateValue(Player1) Player2score = CalculateValue(Player2) if Player1score > Player2score: print("Player 1 wins") elif Player1score < Player2score: print("Player 2 wins") else: print("It's a draw") Java Integer Player1score = CalculateValue(Player1); Integer Player2score = CalculateValue(Player2); if(Player1score > Player2score){ System.out.println("Player 1 wins"); }else if(Player2score > Player1score){ System.out.println("Player2 wins"); } else { System.out.println("It's a draw"); } VB.NET Dim Player1score As Integer Dim Player2score As Integer Player1score = CalculateValue(Player1) Player2score = CalculateValue(Player2) If Player1score > Player2score Then Console.WriteLine("Player 1 wins") ElseIf Player1score < Player2score Then Console.WriteLine("Player 2 wins") Else Console.WriteLine("It's a draw") End If 2(c)(iii) Output showing player 2 wins, for example: 1
1 A computer program is needed to store jobs in order of priority. Each job has a job number (for example, 123) and a priority from 1 to 10, with 1 being the highest priority and 10 the lowest. The program stores the jobs in a global 2D array. The pseudocode declaration for the array is: DECLARE Jobs : ARRAY[0:99, 0:1] OF INTEGER For example: • Jobs[0, 0] stores the job number of the first job. • Jobs[0, 1] stores the priority of the first job. The global variable, NumberOfJobs, stores the number of jobs currently in the array. (a) Write program code to declare the global 2D array Jobs and the global variable NumberOfJobs. Save your program as Question1_N22. Copy and paste the program code into part 1(a) in the evidence document. [3] (b) The procedure Initialise() stores –1 in each of the array elements and assigns 0 to NumberOfJobs. Write program code for the procedure Initialise(). Save your program. Copy and paste the program code into part 1(b) in the evidence document. [3] (c) The procedure AddJob(): • takes a job number and priority as parameters • stores the job in the next free array element • outputs ‘Added’ if the job was successfully stored in the array • outputs ‘Not added’ if the job was not successfully stored in the array. Write program code for the procedure AddJob(). Save your program. Copy and paste the program code into part 1(c) in the evidence document. [5] (d) The main program should call the procedure Initialise() and then use the AddJob() procedure to store the following jobs in the order given: Job number Priority 12 10 526 9 33 8 12 9 78 1 Write program code for the main program and perform the tasks described. Save your program. Copy and paste the program code into part 1(d) in the evidence document. [2] (e) When a new job has been added, the array is sorted into ascending numerical order of priority using an insertion sort. Write program code for the procedure InsertionSort() to sort the data into ascending numerical order of priority. Save your program. Copy and paste the program code into part 1(e) in the evidence document. [5] (f) The procedure PrintArray() outputs each job number and priority on a line, for example: 123 priority 1 39 priority 3 120 priority 7 Write program code for the procedure PrintArray(). Save your program. Copy and paste the program code into part 1(f) in the evidence document. [3] (g) The main program needs to sort the array and then output the contents of the array. (i) Amend the main program by writing program code to call procedures InsertionSort() and PrintArray(). Save your program. Copy and paste the program code into part 1(g)(i) in the evidence document. [1] (ii) Test your program. Take a screenshot of the output. Copy and paste the screenshot into part 1(g)(ii) in the evidence document. [1]
23 marks
Mark scheme: Question Answer Marks 1(a) 1 mark per point: 3 • (global) 2-D array Jobs with correct identifier (and Integer data type) • … with 100 elements by 2 elements • (global) NumberOfJobs declared as variable (as Integer) Example program code: Java public static Integer[][] Jobs = new Integer[100][2]; public static Integer NumberOfJobs; Python Jobs # global integer, 100 by 2 elements NumberOfJobs # global integer VB.NET Dim Jobs(99, 1) As Integer Dim NumberOfJobs As Integer 1(b) 1 mark per point: 3 • procedure heading (and end where appropriate) and assigns 0 to NumberOfJobs • looping through both array element dimensions • … assigns −1 to all elements Example program code: Java public static void Initialise(){ for(Integer x = 0; x<100;x++){ for(Integer y = 0; y<2; y++){ Jobs[x][y] = -1; } } NumberOfJobs = 0; } Python def Initialise(): global Jobs global NumberOfJobs for x in range(0, 100): Jobs.append([-1,-1]) NumberOfJobs = 0 VB.NET Sub Initialise() For X = 0 To 99 For Y = 0 To 1 Jobs(X, Y) = -1 Next Next NumberOfJobs = 0 End Sub 1(c) 1 mark per point (Max 5): 5 • Function header (and end where appropriate) with two (integer) parameters • Checks if array is full … • … if full outputs "Not added" • Storing parameters job number and priority to only the next available array position • Incrementing NumberOfJobs • Outputting "Added" if successful Example program code: Java public static void AddJob(Integer Description, Integer Priority){ if(NumberOfJobs == 100){ System.out.println("Not added"); }else{ Jobs[NumberOfJobs][0] = Description; Jobs[NumberOfJobs][1] = Priority; NumberOfJobs = NumberOfJobs + 1; System.out.println("Added"); } } Python def AddJob(JobNumber, Priority): global NumberOfJobs global Jobs if NumberOfJobs == 100: print("Not added") else: Jobs[NumberOfJobs] = [JobNumber, Priority] print("Added") NumberOfJobs = NumberOfJobs + 1 VB.NET Sub AddJob(JobNumber, Priority) If NumberOfJobs = 100 Then Console.WriteLine("Not added") Else Jobs(NumberOfJobs, 0) = JobNumber Jobs(NumberOfJobs, 1) = Priority NumberOfJobs = NumberOfJobs + 1 Console.WriteLine("Added") End If End Sub 1(d) 1 mark per point: 2 • Calls Initialise() (in the main program) • 5 AddJob calls with correct values as parameters in correct order Example program code: Java public static void main(String args[]){ Initialise(); AddJob(12, 10); AddJob(526, 9); AddJob(33,8); AddJob(12,9); AddJob(78,1); } Python Initialise() AddJob(12,10) AddJob(526,9) AddJob(33,8) AddJob(12,9) AddJob(78,1) VB.NET Sub Main() Initialise() AddJob(12, 10) AddJob(526, 9) AddJob(33, 8) AddJob(12, 9) AddJob(78, 1) End Sub 1(e) 1 mark per point: 5 • Procedure header (and end where appropriate) • Outer loop through all 5 elements / number of jobs … • … inner loop through array elements … • …and comparing priority (second index) … • …moving the elements up and inserting correctly Example program code: Python def InsertionSort(): global Jobs global NumberOfJobs for I in range(1, NumberOfJobs): Current1 = Jobs[I][0] Current2 = Jobs[I][1] while I > 0 and Jobs[I-1][1] > Current2: Jobs[I][0] = Jobs[I-1][0] Jobs[I][1] = Jobs[I-1][1] I = I - 1 Jobs[I][0] = Current1 Jobs[I][1] = Current2 Java public static void InsertionSort(){ Integer Current1; Integer Current2; Integer Counter; Integer Placed; for(Integer i = 1; i < NumberOfJobs; i++){ Current1 = Jobs[i][0]; Current2 = Jobs[i][1]; while(i > 0 && Jobs[i-1][1] > Current2){ Jobs[i][0] = Jobs[i-1][0]; Jobs[i][1] = Jobs[i-1][1]; i = i - 1; } Jobs[i][0] = Current1; Jobs[i][1] = Current2; } } 1(e) VB.NET Sub InsertionSort() Dim Tempa As Integer Dim Tempb As Integer Dim Counter As Integer Dim Placed As Boolean For i = 1 To NumberOfJobs - 1 Tempa = Jobs(i, 0) Tempb = Jobs(i, 1) Counter = i Placed = False While (Counter > 0 And Not Placed) If (Jobs(Counter - 1, 1) > Tempb) Then Jobs(Counter, 0) = Jobs(Counter - 1, 0) Jobs(Counter, 1) = Jobs(Counter - 1, 1) Counter = Counter - 1 Else Placed = True End If End While Jobs(Counter, 0) = Tempa Jobs(Counter, 1) = Tempb Next i End Sub 1(f) 1 mark per point: 3 • procedure heading (and end where appropriate) and outputting all job numbers and priorities • Outputting the job and priority for each element on the same line, with a line break between each job … • … with 'priority' between job number and priority Example program code: Java public static void PrintArray(){ for(Integer x = 0; x < NumberOfJobs; x++){ System.out.println(Jobs[x][0] + " priority " + Jobs[x][1]); } } Python def PrintArray(): global Jobs global NumberOfJobs for X in range(0, NumberOfJobs): print(str(Jobs[X][0]), " priority ", str(Jobs[X][1])) VB.NET Sub PrintArray() For X = 0 To NumberOfJobs - 1 Console.WriteLine(Jobs(X, 0) & " priority " & Jobs(X, 1)) Next End Sub 1(g)(i) • calling both subroutines in the main program in the correct order 1 Example program code: Java InsertionSort(); PrintArray(); Python InsertionSort() PrintArray() VB.NET InsertionSort() PrintArray() 1(g)(ii) 1 mark for added 5 times and jobs in order. 1 526 and 12 can be reversed
2 A computer game is being developed. The game has 10 different characters that are all active in the game. Part of the game is being written using object-oriented programming. The class Character stores data about the characters. Each character has a name and the x coordinate and y coordinate of their current position. Character Name : STRING stores the name of the character XCoordinate : INTEGER stores the x coordinate YCoordinate : INTEGER stores the y coordinate Constructor() initialises Name, XCoordinate and YCoordinate from the values passed as parameters GetName() returns the name of the character GetX() returns the x coordinate of the character GetY() returns the y coordinate of the character ChangePosition() takes XChange as an integer parameter and adds it to the x coordinate takes YChange as an integer parameter and adds it to the y coordinate (a) Write program code to declare the class Character and its constructor. Do not write program code for the other methods. Use your programming language appropriate constructor. All attributes must be private. If you are writing in Python, include attribute declarations using comments. Save your program as Question2_N22. Copy and paste the program code into part 2(a) in the evidence document. [4] (b) Write program code for the three get methods for the class Character. Save your program. Copy and paste the program code into part 2(b) in the evidence document. [3] (c) Write program code for the method ChangePosition(). Save your program. Copy and paste the program code into part 2(c) in the evidence document. [2] (d) The main program has a 1D array of characters. Each character is stored as an object of type Character. The game has a maximum of 10 characters. The character names, x coordinates and y coordinates are stored in the file Characters.txt in the order: • name • x coordinate • y coordinate. For example, the first character in the file is named Amal, with the x coordinate 0 and the y coordinate 2. Amend the main program by writing program code to: • declare the array • read in all 10 characters from Characters.txt • store each character as an object in the array. Save your program. Copy and paste the program code into part 2(d) in the evidence document. [7] (e) The main program needs to read in a character’s name from the user, search for the character in the array and store the index of its position. It repeats until the user enters a name that exists in the array. Amend the main program by writing program code to perform this task. Save your program. Copy and paste the program code into part 2(e) in the evidence document. [5] (f) The user will enter a letter to identify the direction the chosen character from part 2(e) should move. • If ‘A’ is input, the character moves left (x coordinate minus 1). • If ‘W’ is input, the character moves up (y coordinate plus 1). • If ‘S’ is input, the character moves down (y coordinate minus 1). • If ‘D’ is input, the character moves right (x coordinate plus 1). Amend the main program by writing program code to: • take a letter as input until it is a valid move (A, W, S or D) • change the position of the character using the appropriate method. Save your program. Copy and paste the program code into part 2(f) in the evidence document. [7] (g) (i) When a change to a character’s position has been made, the program needs to output the character’s name and the new x and y coordinates of the character, in the format: Qui has changed coordinates to X = 83 and Y = 0 Amend the main program by writing program code to perform these tasks. Save your program. Copy and paste the program code into part 2(g)(i) in the evidence document. [2] (ii) Test your program by inputting the following four items of data in the order given: THOMAS qui X A Take a screenshot of the output. Copy and paste the screenshot into part 2(g)(ii) in the evidence document. [1]
31 marks
Mark scheme: 2(a) 1 mark per point: 4 • Class declaration (and end where appropriate) for Character • Declaring the 3 private attributes with appropriate data types; Name as string, xCoordinate as integer, yCoordinate as integer • Constructor method (and end where appropriate) taking 3 parameters … • …assigning parameters to all 3 attributes Example program code: Java class Character{ private String Name; private Integer XCoordinate; private Integer YCoordinate; public Character(String Namep, Integer XCoord, Integer YCoord){ Name = Namep; XCoordinate = XCoord; YCoordinate = YCoord; }} Python class Character: #private Name as string #private XCoordinate as integer #private YCoordinate as integer def __init__(self, Namep, Xcoord, Ycoord): self.__Name = Namep self.__XCoordiante = Xcoord self.__YCoordinate = Ycoord VB.NET Class Character Private Name As String Private XCoordinate As Integer Private YCoordinate As Integer Sub New(Namep, Xcoord, Ycoord) Name = Namep XCoordinate = Xcoord YCoordinate = Ycoord End Sub End Class 2(b) 1 mark per point: 3 • 1 get method header (and end where appropriate) with no parameters… • …returning correct value • 2nd and 3rd correct get methods Example program code: Java public String GetName(){ return Name;} public Integer GetX(){ return XCoordinate;} public Integer GetY(){ return YCoordinate;} Python def GetName(self): return self.__Name def GetX(self): return self.__XCoordinate def GetY(self): return self.__YCoordinate VB.NET Function GetName() Return Name End Function Function GetX() Return XCoordinate End Function Function GetY() Return YCoordinate End Function 2(c) 1 mark per point: 2 • method header (and end where appropriate) taking 2 (integer) parameters • adding both parameters to existing x and y coordinate values Example program code: Java public void ChangePosition(Integer XChange, Integer YChange){ XCoordinate = XCoordinate + XChange; YCoordinate = YCoordinate + YChange; } Python def ChangePosition(self, XChange, YChange): self.__XCoordinate = self.__XCoordinate + XChange self.__YCoordinate = self.__YCoordinate + YChange VB.NET Sub changePosition(XChange, YChange) XCoordinate = XCoordinate + XChange YCoordinate = YCoordinate + YChange End Sub 2(d) 1 mark per point (Max 7): 7 • declaration of 1D array, 10 elements of type Character • opening text file Characters.txt to read • looping until EOF/10 times… • … reading in each 3-set of values from file … • … instantiate a Character with correct parameters read in from file… • … store in next element/append in declared array • closing the text file (in appropriate place) • Exception handling for opening and reading data from file… • … with appropriate catch and output Example program code: Java public static void main(String[] args){ Character[] Characters = new Character[10]; String TextFile = "Characters.txt"; String Name = ""; Integer Xcoord = 0; Integer Ycoord = 0; try{ FileReader f = new FileReader(TextFile); BufferedReader Reader = new BufferedReader(f); for(Integer X = 0; X < 10; X++){ Name = Reader.readLine(); Xcoord = Integer.parseInt(Reader.readLine()); Ycoord = Integer.parseInt(Reader.readLine()); } Reader.close(); }catch(FileNotFoundException ex){ System.out.println("No file found"); } catch(IOException ex){ System.out.println("No file found"); } } Python Characters = [] TextFile = "Characters.txt" try: File = open(TextFile, 'r') for X in range(0, 10): Name = File.readline().strip() XCoord = File.readline().strip() YCoord = File.readline().strip() TempC = Character(Name, int(XCoord), int(YCoord)) Characters.append(TempC) File.close() except: print("File not found") 2(d) VB.NET Sub Main() Dim Characters(0 To 9) As Character Dim TextFile As String = "Characters.txt" Try Dim FileReader As New System.IO.StreamReader(TextFile) For X = 0 To 10 Name = FileReader.ReadLine() Xcoord = FileReader.ReadLine() Ycoord = FileReader.ReadLine() Characters(X) = New Character(Name, Xcoord, Ycoord) Next FileReader.Close() Catch ex As Exception Console.WriteLine("File not found") End Try end sub 2(e) 1 mark per point (Max 5): 5 • Taking name as input … • …converting/checking case e.g. all to lower • Looping through array of characters comparing each character name to input … • …continuously taking repeat input if not found in array • …storing the index when found • Accessing the name of character in the array using GetName() Example program code: Python Position = -1 CharacterName = "" while(Position == -1): CharacterInput = input("Enter the Character to move").rstrip('\n').lower() for Count in range(0, 10): Temp = str(Characters[Count].GetName().strip()) if(Temp == CharacterInput): Position = Count VB.NET Dim Position As Integer = -1 Dim CharacterName As String = "" While Position = -1 Console.WriteLine("Enter the Character to move") CharacterName = Console.ReadLine For Count = 0 To 9 If(Characters(Count).GetName).tolower = CharacterName.ToLower Then Position = Count End If Next End While 2(e) Java Integer Position = -1; String CharacterName = ""; Scanner scanner = new Scanner(System.in); String Temp = ""; while(Position == -1){ System.out.println("Enter the Character to move"); CharacterName = scanner.nextLine(); for(Integer Count = 0; Count < 10; Count++){ Temp = Characters[Count].GetName(); Temp = Temp.toLowerCase(); if(Temp.equals(CharacterName.toLowerCase())){ Position = Count; } }} 2(f) 1 mark per point (Max 7): 7 • Taking move as input… • …looping until valid • Calling ChangePosition()with object • If A is input parameters are −1, 0 • If D is input parameters are 1, 0 • If W is input parameters are 0, 1 • If S is input parameters are 0, −1 Example program code: Java Boolean IsValid = false; String Move = ""; while(IsValid != true){ System.out.println("Enter A for left, W for up, S or down or D for right"); Move = scanner.nextLine(); if(Move.toUpperCase().equals("A")){ Characters[Position].ChangePosition(-1,0); IsValid = true; } else if(Move.toUpperCase().equals("W")){ Characters[Position].ChangePosition(0,1); IsValid = true; } else if(Move.toUpperCase().equals("S")){ Characters[Position].ChangePosition(0,-1); IsValid = true; } else if(Move.toUpperCase().equals("D")){ Characters[Position].ChangePosition(1,0); IsValid = true; } } Python IsValid = False while(IsValid != True): Move = input("Enter A for left, W for up, S for down, or D for right") if(Move.upper() == "A"): Characters[Position].ChangePosition(-1,0) IsValid = True elif (Move.upper() == "W"): Characters[Position].ChangePosition(0,1) IsValid = True elif (Move.upper() == "S"): Characters[Position].ChangePosition(0,-1) IsValid = True elif(Move.upper() == "D"): Characters[Position].ChangePosition(1,0) IsValid = True 2(f) VB.NET Dim IsValid As Boolean = False Dim Move As String While IsValid <> True Console.WriteLine("Enter A for left, W for up, S for down or D for right") Move = Console.ReadLine() If Move.ToUpper = "A" Then Characters(Position).ChangePosition(-1, 0) IsValid = True ElseIf Move.ToUpper = "W" Then Characters(Position).ChangePosition(0, 1) IsValid = True ElseIf Move.ToUpper = "S" Then Characters(Position).ChangePosition(0, -1) IsValid = True ElseIf Move.ToUpper = "D" Then Characters(Position).ChangePosition(1, 0) IsValid = True End If End While 2(g)(i) 1 mark per point: 2 • Outputting given message including name, x and y position • …all using appropriate get methods Example program code: Java System.out.println(CharacterName + " has changed coordinates to X = " + Characters[Position].GetX() + " Y = " + Characters[Position].GetY()); Python print(CharacterName, " has changed coordinate to X = ", str(Characters[Position].GetX()), " Y = ", str(Characters[Position].GetY())) VB.NET Console.WriteLine(CharacterName & " has changed coordinates to X = " & Characters(Position).GetX & " Y = " & Characters(Position).GetY()) 2(g)(ii) 1 mark for correct result, for example: 1
1 The text file IntegerData.txt stores 100 integer numbers between 1 and 100 inclusive. A program is required to read in this data and perform searching and sorting on the data. (a) Write program code to declare a global 1D array, DataArray, with space for 100 integer values. Save your program as Question1_N22. Copy and paste the program code into part 1(a) in the evidence document. [2] (b) The procedure ReadFile() must read in the numbers from the text file and store each one in the array. Use appropriate exception handling. Write program code for the procedure ReadFile(). Save your program. Copy and paste the program code into part 1(b) in the evidence document. [6] (c) The function FindValues() asks the user to enter a number to search for in the array. The number input must be a whole number between 1 and 100 inclusive. The function then returns the number of times the number input appears in the array. Write program code for the function FindValues(). Save your program. Copy and paste the program code into part 1(c) in the evidence document. [7] (d) (i) Write program code to call ReadFile() and FindValues() from the main program. The return value from FindValues() must be output with an appropriate message. Save your program. Copy and paste the program code into part 1(d)(i) in the evidence document. [3] (ii) Test your program using the number 61 as input. Take a screenshot to show the output. Copy and paste the screenshot into part 1(d)(ii) in the evidence document. [1] (e) The procedure BubbleSort() needs to perform a bubble sort on the array and print the contents of the sorted array. Write program code for the procedure BubbleSort() and call it from the main program. Save your program. Copy and paste the program code into part 1(e) in the evidence document. [4]
23 marks
Mark scheme: Question Answer Marks 1(a) 1 mark per point: 2 • (global) 1D (Integer) array DataArray • 100 elements Example program code: Python DataArray = [0 for I in range (100)] Java public static Integer[] DataArray = new Integer[100]; VB.NET Dim DataArray(99) As Integer 1(b) 1 mark per point: 6 • Procedure ReadFile() header (and end where appropriate) • opening file IntegerData.txt (for read) • looping through the 100 elements // looping to end of file • reading each (and all) value from file and storing in array • closing file (in appropriate place) 1 mark per point: • Exception Handling (for opening the file, or for reading values from the file)… • …with appropriate catch and output messages Example program code: Python def ReadFile(): global DataArray try: TextFile = "IntegerData.txt" File = open(TextFile, 'r') for X in range(0, 100): DataArray[X] = File.readline() DataArray[X].rstrip('\n') DataArray[X] = int(DataArray[X]) File.close() except IOError: print("Count not find file") 1(b) Java public static void ReadFile(){ String Filename = "IntegerData.txt"; try{ FileReader F = new FileReader(Filename); BufferedReader Reader = new BufferedReader(F); for(Integer X = 0; X < 100; X++){ DataArray[X] = Integer.parseInt(Reader.readLine()); } Reader.close(); } catch(FileNotFoundException ex){ System.out.println("No file found"); } catch(IOException ex){ System.out.println("No file found"); } } VB.NET Sub ReadFile() try Dim TextFile As String = "IntegerData.txt" Dim FileReader As New System.IO.StreamReader(TextFile) For X = 0 To 99 DataArray(X) = FileReader.ReadLine() Next FileReader.Close() Catch ex As Exception Console.WriteLine("Invalid file") End Try End Sub 1(c) 1 mark per point: 7 • Function FindValues() (and end where appropriate) and input of data to search for in the array • …validation/casting(/storing as) of input as integer • …validation of input between 1 and 100 (inclusive) • looping through all 100 array elements… • …comparing input to each array element… • …initialising counter to 0 and then adding 1 each time it is found… • Returning the total 1(c) Example program code: Python def FindValues(): global DataArray DataToFind = -1 while(DataToFind < 1 or DataToFind > 100): DataToFind = int(input("Enter a number between 1 and 100")) Total = 0 for X in range(0, 99): if DataArray[X] == DataToFind: Total = Total + 1 return Total VB.NET Function FindValues() Dim DataToFind As Integer Do Console.WriteLine("Enter a number between 1 and 100") DataToFind = Console.ReadLine() Loop Until (DataToFind >= 1 And DataToFind <= 100) Dim Total As Integer = 0 For X = 0 To 99 If DataArray(X) = DataToFind Then Total = Total + 1 End If Next Return Total End Function Java public static Integer FindValues(){ Integer DataToFind = -1; while(DataToFind < 1 || DataToFind > 100){ System.out.println("Enter a number between 1 and 100"); Scanner in = new Scanner(System.in); DataToFind = in.nextInt(); } Integer Total = 0; for(Integer X = 0; X < 100; X++){ if(DataArray[X] == DataToFind){ Total = Total + 1; } } return Total; } 1(d)(i) 1 mark per point: 3 • Calling ReadFile() and then FindValues() (in the main program) • storing/using return value from FindValues() … • …outputting return value with appropriate message Example program code: Python ReadFile() print("The number appears " + str(FindValues()) + " times") Java public static void main(String[] args){ ReadFile(); Integer ReturnValue = FindValues(); System.out.println("The number was found " + ReturnValue + " times"); } VB.NET Sub Main() ReadFile() Dim ReturnValue As Integer = FindValues() Console.WriteLine("The number was found " & ReturnValue & " times") End Sub 1(d)(ii) Screenshot showing 61 input and 2 output, e.g. 1 1(e) 1 mark per point: 4 • procedure declaration (and end where appropriate) and outputting array contents at end of procedure and calling procedure from main program • correct outer loop … • … correct inner loop … • … swapping all elements if in incorrect order Example program code: Python def BubbleSort(): global DataArray N = 100 for I in range(N-1): for J in range(0, N-I-1): if DataArray[J] > DataArray[J+1]: DataArray[J], DataArray[J+1] = DataArray[J+1], DataArray[J] #main ReadFile() print("The number appears " + str(FindValues()) + " times") BubbleSort() print(DataArray) Java public static void BubbleSort(){ Integer Temp = 0; for(Integer I = 0; I < 100-1; I++){ for(Integer J = 0; J < 100-I-1; J++){ if(DataArray[J] > DataArray[J+1]){ Temp = DataArray[J]; DataArray[J] = DataArray[J+1]; DataArray[J+1] = Temp; } } } for(Integer X = 0; X < 100; X ++){ System.out.println(DataArray[X]); } } public static void main(String[] args){ ReadFile(); Integer ReturnValue = FindValues(); System.out.println("The number was found " + ReturnValue + " times"); BubbleSort(); } 1(e) VB.NET Sub Bubblesort() Dim Outer As Integer = 100 - 1 Dim Swap As Boolean Dim Inner As Integer Dim Temp As Integer Do Inner = 0 Swap = False Do If DataArray(Inner) > DataArray(Inner + 1) Then Temp = DataArray(Inner) DataArray(Inner) = DataArray(Inner + 1) DataArray(Inner + 1) = Temp Swap = True End If Inner = Inner + 1 Loop Until Inner = Outer Outer = Outer - 1 Loop Until Swap = False Or Outer = 0 For X = 0 To 99 Console.WriteLine(DataArray(X)) Next End Sub Sub Main() ReadFile() Dim ReturnValue As Integer = FindValues() Console.WriteLine("The number was found " & ReturnValue & " times") Bubblesort() End Sub
2 A computer program is being developed that uses a set of cards. The program is written using object-oriented programming. The program has two classes: Card and Hand. The methods and attributes of these classes are shown: Card Number : INTEGER stores the card number from 1 to 5 inclusive Colour : STRING stores the card colour: red, blue or yellow Constructor() takes a number and colour as parameters and sets the private values to these parameters GetNumber() returns the card number GetColour() returns the card colour Hand Cards : ARRAY[0:9] OF Card 1D array of type Card FirstCard : INTEGER stores the position of the first card in the hand NumberCards : INTEGER stores the number of cards in the hand Constructor() takes five card objects as parameters, assigns each card to the array Cards[], initialises FirstCard to 0 and NumberCards to 5 GetCard() takes an index as a parameter and returns the card at that index in the array (a) (i) Write program code to declare the class Card, its attributes and constructor. Do not write program code for the get methods. Use your programming language appropriate constructor. All attributes must be private. If you are writing in Python, include attribute declarations using comments. Save your program as Question2_N22. Copy and paste the program code into part 2(a)(i) in the evidence document. [5] (ii) Write program code for the class methods GetNumber() and GetColour(). Save your program. Copy and paste the program code into part 2(a)(ii) in the evidence document. [3] (iii) The program is tested with the following cards: Number Colour 1 red 2 red 3 red 4 red 5 red 1 blue 2 blue 3 blue 4 blue 5 blue 1 yellow 2 yellow 3 yellow 4 yellow 5 yellow Write program code to declare each of these cards as a variable of type Card in the main program. Save your program. Copy and paste the program code into part 2(a)(iii) in the evidence document. [2] (b) (i) Write program code to declare the class Hand, its attributes and constructor. Do not write the get methods. Use your programming language appropriate constructor. All attributes must be private. If you are writing in Python, include attribute declarations using comments. Save your program. Copy and paste the program code into part 2(b)(i) in the evidence document. [6] (ii) The get method GetCard() takes an index as a parameter and returns the card stored at that index in the array. Write program code for the method GetCard(). Save your program. Copy and paste the program code into part 2(b)(ii) in the evidence document. [2] (iii) Two players are declared with 5 cards each. Player 1 has the cards: 1 red, 2 red, 3 red, 4 red, 1 yellow. Player 2 has the cards: 2 yellow, 3 yellow, 4 yellow, 5 yellow, 1 blue. Write program code to declare player 1 and player 2 as objects of type Hand, with the cards indicated. Save your program. Copy and paste the program code into part 2(b)(iii) in the evidence document. [2] (c) The function CalculateValue() takes a player’s hand as a parameter and returns a score calculated using the following rules: • If a card is red, 5 points are added to the player’s score. • If a card is blue, 10 points are added to the player’s score. • If a card is yellow, 15 points are added to the player’s score. • The number of each card in the hand is added to the player’s score. (i) Write program code for the function CalculateValue(). Assume that there are only 5 cards in the player’s hand in this function. Save your program. Copy and paste the program code into part 2(c)(i) in the evidence document. [6] (ii) Amend the main program by writing program code to use the function CalculateValue() for each of the two players. The player with the highest score wins. Output an appropriate message to identify the winning player, or if the game was a draw (both players have the same number of points). Save your program. Copy and paste the program code into part 2(c)(ii) in the evidence document. [4] (iii) Test your program. Take a screenshot to show the output. Copy and paste the screenshot into part 2(c)(iii) in the evidence document. [1]
31 marks
Mark scheme: 2(a)(i) 1 mark per point: 5 • class Card declaration (and end where appropriate) • Private attributes declared Number as integer and Colour as string • constructor header (and end where appropriate)… • …taking 2 parameters • assigning parameters to attributes Example program code: Python class Card: #Number as integer #Colour as string def __init__(self, Number1, Colour1): self.__Number = Number1; self.__Colour = Colour1; 2(a)(i) Java class Card{ private Integer Number; private String Colour; public Card(Integer Number1, String Colourp){ Number = Number1; Colour = Colourp; }} VB.NET Class Card Private Number As Integer Private Colour As String Sub New(Number1, Colourp) Number = Number1 Colour = Colourp End Sub End Class 2(a)(ii) 1 mark per point: 3 • 1 get method as function (and end where appropriate) with no parameters… • …returning the value • 2nd correct get method Example program code: Python def GetNumber(self): return self.__Number def GetColour(self): return self.__Colour Java public Integer GetNumber(){ return Number; } public String GetColour(){ return Colour; } VB.NET Function GetNumber() Return Number End Function Function GetColour() Return Colour End Function 2(a)(iii) 1 mark per point: 2 • one card initialised as type Card … • … all 15 cards initialised correctly as type Card Example program code: Python OneRed = Card(1, "red") TwoRed = Card(2, "red") ThreeRed = Card(3, "red") FourRed = Card(4, "red") FiveRed = Card(5, "red") OneBlue = Card(1, "blue") TwoBlue = Card(2, "blue") ThreeBlue = Card(3, "blue") FourBlue = Card(4, "blue") FiveBlue = Card(5, "blue") OneYellow = Card(1, "yellow") TwoYellow = Card(2, "yellow") ThreeYellow = Card(3, "yellow") FourYellow = Card(4, "yellow") FiveYellow = Card(5, "yellow") Java CARD oneRed = new Card(1, "red"); CARD twoRed = new Card(2, "red"); CARD threeRed = new Card(3, "red"); CARD fourRed = new Card(4, "red"); CARD fiveRed = new Card(5, "red"); CARD oneBlue = new Card(1, "blue"); CARD twoBlue = new Card(2, "blue"); CARD threeBlue = new Card(3, "blue"); CARD fourBlue = new Card(4, "blue"); CARD fiveBlue = new Card(5, "blue"); CARD oneYellow = new Card(1, "yellow"); CARD twoYellow = new Card(2, "yellow"); CARD threeYellow = new Card(3, "yellow"); CARD fourYellow = new Card(4, "yellow"); CARD fiveYellow = new Card(5, "yellow"); 2(a)(iii) VB.NET Dim OneRed As New Card (1, "red") Dim TwoRed As New Card(2, "red") Dim ThreeRed As New Card(3, "red") Dim FourRed As New Card(4, "red") Dim FiveRed As New Card(5, "red") Dim OneBlue As New Card(1, "blue") Dim TwoBlue As New Card(2, "blue") Dim ThreeBlue As New Card(3, "blue") Dim FourBlue As New Card(4, "blue") Dim FiveBlue As New Card(5, "blue") Dim OneYellow As New Card(1, "yellow") Dim TwoYellow As New Card(2, "yellow") Dim ThreeYellow As New Card(3, "yellow") Dim FourYellow As New Card(4, "yellow") Dim FiveYellow As New Card(5, "yellow") 2(b)(i) 1 mark per point: 6 • class Hand declaration (and end where appropriate) • private attribute declarations; FirstCard as integer, NumberCards as integer • private attribute array named Cards of type Card with 10 elements • constructor with 5 Card objects as parameters • assigning each Card parameter to the array (in constructor) • initialising FirstCard to 0 and NumberCards to 5 (in constructor) Example program code: Python class Hand: #Cards[10] as Card #FirstCard as integer #NumberCards as integer def __init__(self, Card1, Card2, Card3, Card4, Card5): self.__Cards = [] self.__Cards.append(Card1) self.__Cards.append(Card2) self.__Cards.append(Card3) self.__Cards.append(Card4) self.__Cards.append(Card5) self.__FirstCard = 0 self.__NumberCards = 5 2(b)(i) Java class Hand{ private Card[] Cards = new Card[10]; private Integer FirstCard; private Integer NumberCards; public Hand(CARD Card1, CARD Card2, CARD Card3, CARD Card4, CARD Card5){ Cards[0] = Card1; Cards[1] = Card2; Cards[2] = Card3; Cards[3] = Card4; Cards[4] = Card5; FirstCard = 0; NumberCards = 5; } } VB.NET class Hand Private Cards(9) As Card Private FirstCard As Integer Private NumberCards As Integer Sub New(Card1, Card2, Card3, Card4, Card5) Cards(0) = Card1 Cards(1) = Card2 Cards(2) = Card3 Cards(3) = Card4 Cards(4) = Card5 FirstCard = 0 NumberCards = 5 End Sub End Class 2(b)(ii) 1 mark per point: 2 • function GetCard() header (and end where appropriate) taking (integer) parameter • returning the card at parameter index in array Example program code: Python def GetCard(self, Position): return self.__Cards[Position] Java public Card GetCard(Integer Position){ return Cards[Position]; } VB.NET Function GetCard(Position) Return Cards(Position) End Function 2(b)(iii) 1 mark per point: 2 • 2 variables (player 1 and player 2) of type Hand • using constructor and sending the correct variables as parameters Example program code: Python Player1 = Hand(OneRed, TwoRed, ThreeRed, FourRed, OneYellow) Player2 = Hand(TwoYellow, ThreeYellow, FourYellow, FiveYellow, OneBlue) Java Hand Player1 = new Hand(OneRed, TwoRed, ThreeRed, FourRed, OneYellow); Hand Player2 = new Hand(TwoYellow, ThreeYellow, FourYellow, FiveYellow, OneBlue); VB.NET Dim Player1 As New Hand(OneRed, TwoRed, ThreeRed, FourRed, OneYellow) Dim Player2 As New Hand(TwoYellow, ThreeYellow, FourYellow, FiveYellow, OneBlue) 2(c)(i) 1 mark per point: 6 • function CalculateValue() header (and end where appropriate) taking one parameter and initialising score to 0 • looping through all 5 Card objects in parameter array… • … adding 5 to score for red, 10 to score for blue, 15 to score if yellow • … adding each card number to score • Using GetCard(), GetColour() and GetNumber() correctly • Returning calculated score Example program code: Python def CalculateValue(Player): Score = 0 for Count in range(0, 4): CardGot = Player.GetCard(Count) Score = Score + CardGot.GetNumber() Colour = CardGot.GetColour() if Colour == "red": Score = Score + 5 elif Colour == "blue": Score = Score + 10 else: Score = Score + 15 return Score 2(c)(i) Java public static Integer CalculateValue(Hand Player){ Integer Score = 0; String Colour; Card CardGot; for(Integer X = 0; X<5; X++){ CardGot = Player.GetCard(X); Score = Score + CardGot.GetNumber(); Colour = CardGot.GetColour(); if(Colour == "red"){ Score = Score + 5; }else if(Colour == "blue"){ Score = Score + 10; } else { Score = Score + 15; }}return Score;} VB.NET Function CalculateValue(Player As Hand) Dim Score As Integer = 0 Dim Colour As String Dim CardGot As Card For Count = 0 To 4 CardGot = Player.GetCard(Count) Score = Score + CardGot.GetNumber() Colour = CardGot.GetColour() If Colour = "red" Then Score = Score + 5 ElseIf Colour = "blue" Then Score = Score + 10 Else Score = Score + 15 End If Next Return Score End Function 2(c)(ii) 1 mark per point: 4 • One function call of CalculateValue( ) for each player … • …sending the player's hand as parameter • Comparing return values and outputting the player with the highest score in an appropriate message … • … or if there was a draw in appropriate message Example program code: Python Player1score = CalculateValue(Player1) Player2score = CalculateValue(Player2) if Player1score > Player2score: print("Player 1 wins") elif Player1score < Player2score: print("Player 2 wins") else: print("It's a draw") Java Integer Player1score = CalculateValue(Player1); Integer Player2score = CalculateValue(Player2); if(Player1score > Player2score){ System.out.println("Player 1 wins"); }else if(Player2score > Player1score){ System.out.println("Player2 wins"); } else { System.out.println("It's a draw"); } VB.NET Dim Player1score As Integer Dim Player2score As Integer Player1score = CalculateValue(Player1) Player2score = CalculateValue(Player2) If Player1score > Player2score Then Console.WriteLine("Player 1 wins") ElseIf Player1score < Player2score Then Console.WriteLine("Player 2 wins") Else Console.WriteLine("It's a draw") End If 2(c)(iii) Output showing player 2 wins, for example: 1