1649 assignment 1 (pass) 1649 assignment 1 (pass) 1649 assignment 1 (pass) 1649 assignment 1 (pass) 1649 assignment 1 (pass) 1649 assignment 1 (pass) 1649 assignment 1 (pass) 1649 assignment 1 (pass) 1649 assignment 1 (pass) 1649 assignment 1 (pass) 1649 assignment 1 (pass) 1649 assignment 1 (pass) 1649 assignment 1 (pass) 1649 assignment 1 (pass) 1649 assignment 1 (pass) 1649 assignment 1 (pass) 1649 assignment 1 (pass) 1649 assignment 1 (pass) 1649 assignment 1 (pass) FPT Greenwich
Higher Nationals in Computing Unit 19: Data Structures and Algorithms ASSIGNMENT Assessor name: PHAN MINH TAM Learner’s name: DAO VINH KHANG ID:GCS200222 Class:GCS0905B Subject code: 1649 Assignment due: Assignment submitted: ASSIGNMENT FRONT SHEET Qualification BTEC Level HND Diploma in Computing Unit number and title Unit 19: Data Structures and Algorithms Submission date Date Received 1st submission Re-submission Date Date Received 2nd submission Student Name DAO VINH KHANG Student ID GCS200222 Class GCS0905B Assessor name TAMPM Student declaration I certify that the assignment submission is entirely my own work and I fully understand the consequences of plagiarism I understand that making a false declaration is a form of malpractice Student’s signature KHANG Grading grid P1 P2 P3 M1 M2 M3 D1 D2 Summative Feedback: Resubmission Feedback: 3.1 3.2 Grade: Assessor Signature: Internal Verifier’s Comments: Signature & Date: Date: ASSIGNMENT BRIEF Qualification BTEC Level HND Diploma in Business Unit number Unit 19: Data Structures and Algorithms Assignment title Examine and specify ADT and DSA Academic Year 2022 Unit Tutor TamPM Issue date 12 – September – 2022 Submission date IV name and date Submission Format: Format: ● The submission is in the form of an individual written report and a presentation This should be written in a concise, formal business style using single spacing and font size 12 You are required to make use of headings, paragraphs and subsections as appropriate, and all work must be supported with research and referenced using the Harvard referencing system Please also provide a bibliography using the Harvard referencing system Submission ● Students are compulsory to submit the assignment in due date and in a way requested by the Tutor ● ● The form of submission will be a soft copy posted on http://cms.greenwich.edu.vn/ Remember to convert the word file into PDF file before the submission on CMS Note: ● ● The individual Assignment must be your own work, and not copied by or from another student If you use ideas, quotes or data (such as diagrams) from books, journals or other sources, you must reference your sources, using the Harvard style ● Make sure that you understand and follow the guidelines to avoid plagiarism Failure to comply this requirement will result in a failed assignment Unit Learning Outcomes: LO1 Examine abstract data types, concrete data structures and algorithms LO2 Specify abstract data types and algorithms in a formal notation Assignment Brief and Guidance: Assignment scenario You work as in-house software developer for Softnet Development Ltd, a software body-shop providing network provisioning solutions Your company is part of a collaborative service provisioning development project and your company has won the contract to design and develop a middleware solution that will interface at the front-end to multiple computer provisioning interfaces including SOAP, HTTP, JML and CLI, and the back-end telecom provisioning network via CLI Your account manager has assigned you a special role that is to inform your team about designing and implementing abstract data types You have been asked to create a presentation for all collaborating partners on how ADTs can be utilised to improve software design, development and testing Further, you have been asked to write an introductory report for distribution to all partners on how to specify abstract data types and algorithms in a formal notation Tasks Part You will need to prepare a presentation on how to create a design specification for data structures, explaining the valid operations that can be carried out on the structures using the example of: A stack ADT, a concrete data structure for a First In First out (FIFO) queue Two sorting algorithms Two network shortest path algorithms Part You will need to provide a formal written report that includes the following: Explanation on how to specify an abstract data type using the example of software stack Explanation of the advantages of encapsulation and information hiding when using an ADT Discussion of imperative ADTs with regard to object orientation Learning Outcomes and Assessment Criteria (Assignment 1) Pass Merit Distinction LO1 Examine abstract data types, concrete data structures and algorithms P1 Create a design specification for data structures explaining the valid operations that can be carried out on the structures M1 Illustrate, with an example, a concrete data structure for a First In First out (FIFO) queue M2 Compare the performance of two sorting algorithms D1 Analyse the operation, using illustrations, of two network shortest path algorithms, providing an example of each P2 Determine the operations of a memory stack and how it is used to implement function calls in a computer LO2 Specify abstract data types and algorithms in a formal notation P3 Using an imperative definition, specify the abstract data type for a software stack M3 Examine the advantages of encapsulation and information hiding when using an ADT D2 Discuss the view that imperative ADTs are a basis for object orientation and, with justification, state whether you agree Table of Contents Contents Unit 19: Data Structures and Algorithms ASSIGNMENT P1/ Create a design specification for data structures explaining the valid operations that can be carried out on the structures 1/ Introduction to Abstract Data Type 1.1/ What is ADT? 1.2/ The benefits of ADT 1.3/ ADT example Suppose we have an index array of size We have an index location starting from 0, 1, 2, Array is a data structure where the elements are stored in a contiguous location The memory address of the first element is 1000, second element is 1004, third element is 1008, and the fourth element is 1012 Since it is of integer type so it will occupy bytes and the difference between the addresses of each element is bytes The values stored in an array are 10, 20, 30 and 40 These values, index positions and the memory addresses are the implementations 1.4/ Comparison between ADT and OOP 2/ Linear Data Structures 2.1/ Definition 2.2/ Linked List 2.3/ Stack 2.4/ Queue 3/ Sorting Algorithms 4/ Searching Algorithms 11 4.1/ Definition 12 4.2/ Linear search 12 4.3/ Binary Search 13 P2/ Determine the operations of a memory stack and how it is used to implement function calls in a computer 14 1/ Memory stack 14 The Push Operation 15 The Pop Operation 16 P3 Using an imperative definition, specify the abstract data type for a software stack 17 1/ Formal specification 17 2/ What are the pre-condition, post-condition, and error-condition? 18 2.1/ Pre-condition 18 2.2/ Post-condition 18 Page |1 2.3/ Error-condition 18 3/ Specify stack Operation using this formal language 19 Page |2 ASSIGNMENT Answer P1/ Create a design specification for data structures explaining the valid operations that can be carried out on the structures 1/ Introduction to Abstract Data Type 1.1/ What is ADT? In computer science, an abstract data type (ADT) is a mathematical model for a given class of data structures that behaves similarly; or for certain data types of one or more semantically similar programming languages An abstract data type is defined indirectly, only by the operations that can be performed on it and by mathematical constraints on the effects (and possibly costs) of those operations To be more specific, you can take Java's List interface as an example The interface does not define any behaviour at all because there is no concrete List class The interface just defines a set of methods that other classes (e.g., Array List and LinkedList) must implement to be considered a List 1.2/ The benefits of ADT The following are the advantages of using the data structure: • These are the essential ingredients used for creating fast and powerful algorithms • They help us to manage and organize the data Page |3 • Data structures make the code cleaner and easier to understand 1.3/ ADT example Suppose we have an index array of size We have an index location starting from 0, 1, 2, Array is a data structure where the elements are stored in a contiguous location The memory address of the first element is 1000, second element is 1004, third element is 1008, and the fourth element is 1012 Since it is of integer type so it will occupy bytes and the difference between the addresses of each element is bytes The values stored in an array are 10, 20, 30 and 40 These values, index positions and the memory addresses are the implementations The abstract or logical view of the integer array can be stated as: • It stores a set of elements of integer type • It reads the elements by position, i.e., index • It modifies the elements by index • It performs sorting The implementation view of the integer array: 1.4/ Comparison between ADT and OOP ADT OOP Abstract ADT is abstraction that define set of value and set of operations on these values Definition It is a type for objects whose behaviour It is basic unit of OOP is defined by a set of value and a set of operation Using User-defined data type It is an instance of class Data type ATD is not definitely an OOP concept Objects is an OOP concept Example List, Stacks, Queue, Sets, etc Test T=new Test Use Allocate memory when data is stored When we instantiate an object then memory is allocated 2/ Linear Data Structures 2.1/ Definition Page |4 It is a sell-contained component which consist of methods and properties to make certain type of data useful Selection sort Selection Sort is a simple algorithm This sorting algorithm is an algorithm based on in-place comparison, where the list is divided into two parts, the sorted list on the left and the unsorted list on the left the right Initially, the sorted part is empty, and the unsorted part is the entire original list The smallest element is selected from the unsorted array and swapped with the leftmost element, and that element becomes the element of the sorted array This process continues until all the elements in the unsorted array have been moved to the sorted array 4/ Searching Algorithms P a g e | 11 4.1/ Definition In computer science, a search algorithm is an algorithm that takes a problem as input and returns a solution to that problem, usually after weighing a series of possible solutions body Most of the algorithms studied by computer scientists to solve problems are search algorithms The set of all possible solutions to a problem is called the search space Brute-force search or information less "primary" search algorithms use the simplest and most intuitive method Meanwhile, informed search algorithms use heuristics to apply knowledge of the structure of the search space to reduce the time required for searching 4.2/ Linear search Each element is checked, and if any match is found, that element is returned; If not found, the search continues until all data is found P a g e | 12 4.3/ Binary Search Binary Search has a great advantage in terms of time complexity when compared to Linear Search Linear Search has a worst-case complexity of Ο(n) while Binary Search is Ο(log n) Binary Search searches for a specific element by comparing the middle element in the data set If a match is found, the index of the element is returned If the search element is greater than the middle element value, the search element is searched in the subarray to the right of the middle element; otherwise, it will look in the subarray to the left of the middle element The process will continue like this on the subarray until all elements in this subarray are found P a g e | 13 P2/ Determine the operations of a memory stack and how it is used to implement function calls in a computer 1/ Memory stack Stack memory is a memory usage mechanism that allows the system memory to be used as temporary data storage that behaves as a first-in-last-out buffer One of the essential elements of stack memory operation is a register called the Stack Pointer The stack pointer indicates where the current stack memory location is and is adjusted automatically each time a stack operation is carried out PUSH and POP are commonly used at the beginning and at the end of a function or subroutine At the beginning of a function, the current contents of the registers used by the calling program are stored in the stack memory using PUSH operations, and at the end of the function, the data on the stack memory is restored to the registers using POP operations Typically, each register PUSH operation should have a corresponding register POP operation; otherwise, the stack pointer will not be able to restore registers to their original values This can result in unpredictable behaviors, for example, function return to incorrect addresses P a g e | 14 The Push Operation The push operation involves inserting data items into a stack Let's examine our restaurant plate dispenser in our second figure The push operation adds plates (data items) to the plate dispenser P a g e | 15 (stack) The first plate is pushed to the bottom of the stack with all subsequent plates following in order after it The first data item inserted is the most inaccessible and is positioned at the bottom of the stack The Pop Operation The pop operation involves removing data items from a loaded stack In our plate dispenser illustration, the last plate (data item) added is positioned at the top of the stack This data item is popped out of the stack as the first item to be removed Think of the spring loading system at the base of the plate dispenser It pushes the stack of plates upward each time a plate is removed In memory, items continue to be popped out in that order P a g e | 16 P3 Using an imperative definition, specify the abstract data type for a software stack 1/ Formal specification In computer science, formal specifications are math-based techniques intended to aid in the implementation of systems and software They are used to describe a system, to analyze its behavior, and to support its design by verifying key properties of interest through robust and efficient reasoning tools These specifications are formal in the sense that they have syntax, their semantics are in a domain, and they can be used to infer useful information With each passing decade, computer systems become more and more powerful and, as a result, they become more impactful on society Therefore, better techniques are needed to support reliable software design and implementation Established engineering disciplines use mathematical analysis as the foundation of product design creation and validation The official specification is one of the ways to achieve this in terms of software engineering reliability as has been predicted Other methods such as testing are more commonly used to improve code quality Benefit: P a g e | 17 • A higher level of rigor enables a better understanding of the problem • Defects are uncovered that would likely go unnoticed with traditional specification methods • identify defects earlier in the life cycle • Can guarantee the absence of certain defects Limit: • Used as an adjunct to, not a replacement for, standard quality assurance methods • Formal methods are not a panacea, but can increase confidence in a product’s reliability if applied with care and skill • Very useful for consistency checks, but cannot assure completeness of a specification 2/ What are the pre-condition, post-condition, and error-condition? 2.1/ Pre-condition By convention, the precondition of a public method is required to check the parameter and throw the specified exception This is because : assert is designed to check the correctness of the program, not for exception handling When assert false, it will throw an Assertion Error, a generic and non-obvious exception that the programmer can handle As for the private method, we can use it to check the correctness of a variable — no matter what the user enters When we write assert right before performing the operation, we are doing a precondition check 2.2/ Post-condition A post Condition is a statement or set of statements describing the outcome of action if true when the operation has completed its task The Post Conditions statement indicates what will be true when the action finishes its task A postcondition associated with a method invocation is a condition that must be true when we return from a method For example, if a natural logarithm method was called with input X, and the method returns Y, we must have (within the limits of the level of precision being used) 2.3/ Error-condition Status ERROR is always enabled Result An error message is issued if no ON-unit is active when the ERROR condition arises, or if the ON-unit does not use a GOTO (to exit the block) to recover from the condition Cause and syntax P a g e | 18 The ERROR condition is the implicit action for many conditions This provides a common condition that can be used to check for a number of different conditions, rather than checking each condition separately The ERROR condition is raised under the following circumstances: • As a result of the implicit action for a condition, which is to raise the ERROR condition • As a result of the normal return action for some conditions, such as SUBSCRIPTRANGE CONVERSION or when no retry is attempted • As a result of an error (for which there is no other PL/I-defined condition) during program execution • As a result of a SIGNAL ERROR statement In order to prevent a loop of ERROR conditions, the first statement in any ON ERROR block should be ON ERROR SYSTEM 3/ Specify stack Operation using this formal language After the function exits another set of conditions will apply A statement of these postconditions is needed to check that a particular implementation of the function works according to requirements For example, the pre and postconditions of a typical math square-foot function defined in the style of VDM are: SQRT(x:real)y:real pre x >=0 post y*y = x and y >= The input must be zero or positive; the output when multiplied by itself must equal the input and be greater than or equal to zero because sqrt() always returns the positive square root Alternatively, the relationship between pre- and post-conditions can be represented as a Hoare triple {P}A{Q} where P and Q are predicates and A is a program that terminates when it is run The Vienna Development Method (VDM) founded on Hoare Logic supplied a basis for the realization of these concepts in software design, but various less formal specification languages are now available OCL for example, an adjunct to the Unified Modelling Language (UML), allows the use of formal English to define conditions and invariants VDM, OCL, etc are typified as being formal methods Their representation as Design by Contract has resulted in further denormalization although this may not have been the intention of Bertrand Meyer who coined the metaphor to represent the relationship between client code and code supplying a service Applying VDM to a stack ADT, a possible set of operations on a could be formulated as: Stack(max_size: integer): r: Stack P a g e | 19 pre true post r = a new Stack instance r.max_size = max_size size(r) = is_empty(r) = True is_full(r) = False invariant: size(r) >= size(S: Stack): r: (0 S.max_size) pre true post r = j - k where {S = Stack(), j * push(S, i), k * pop(S), j >= k} {the sum of valid pushes - pops since S was created} is_empty(S: Stack): r: bool pre true post r = (size(S) = 0) is_full(S: Stack): r: bool pre true post r = (size(S) = S.max_size) top(S: Stack): r: Item pre not is_empty(s) post r = i where {i = pop(S), S = push(S, i)} {defines i, S after i has been popped off and pushed back on again} push(S: Stack, i: Item): None pre not is_full(S) and n = size(S) P a g e | 20 post top(S) = i and size(S) = n + pop(S: Stack): r: Item pre not is_empty(S) and i = top(S) and n = size(S) post r = i and size(S) = n - The precondition true specifies the operation is valid for any state of a stack: there are no preconditions An ADT invariant specifies conditions that are True for any instance and remain True throughout its lifetime irrespective of the operations carried out on it It is therefore appropriate to place the invariant after the postconditions for initializing an instance When the item on the left is pushed onto the stack and pop() is called that item will be the one on the top of the stack and will be removed This characteristic makes a stack a Last-In-First-Out structure, a LIFO, as opposed to a queue which features First-In-First-Out, a FIFO A traditional implementation of a stack without using any OOP techniques is best done in a separate file called 'stack.py' The first step is to define a record to hold persistent data for the stack instance By persistent I mean data that persists from one access of the stack to another (for data to persist from one run of a program to another it needs to be placed in backing storage i.e., put in a file saved to disk or some other medium) An array to hold items in pushed order is required A stack pointer points to the next free location in the array When the array has zero based indexing, size and the value of stack-pointer are the same: only a stack pointer is needed Maximum size is the size of the array Using Python's record equivalent as before gets: from array_types import array_ class stack: def init (self, max_size): self.array = array_(max_size) self.SP = # the stack pointer self.max_size = max_size Now define the stack operations: def push(stack, item): stack._array[stack.SP] = item stack.SP += P a g e | 21 def pop(stack): stack.SP -= return stack.array[stack.SP] # etc A complete set of operations is in 'stack.py' from the download project in Stacks.zip Test scripts are also included There are a couple points to note from the tests, in part resulting from the characteristics of the underlying list type used to implement array_ When there is an attempt to push an item onto a full stack this overflow produces an exception The exception is raised before SP is incremented making the push() operation valid as far as it goes However, when an underflow occurs from popping an empty stack, the stack pointer is decremented to -1 before the invalid removal is attempted There is no exception, but this is neither here nor there: the stack is already corrupted and will no longer function correctly The value of the stack pointer SP is also the size of the stack, and the ADT invariant is broken For those with a belief that design by contract is the answer to all life's problems this may be of no consequence: calling pop() on an empty stack is in clear violation of pop's precondition This is not my belief, and these problems will be dealt with in a later article The second point is that when items are popped off the stack pointer is decremented but items are not actually removed They will remain in the array until an item is pushed into the space they occupy For a limited number of small objects this is not a problem but for a large structure replacing references to objects with a reference to None in pop() might be required A test file for 'stack.py' is in 'stack_test.py' Testing the stack In a test file possible syntax to use stack operations is: from stack import * # import all stack's identifiers by name a_stack = stack(6) print('stack size:', size(a_stack), ' stack array:', a_stack.array) push(a_stack, '||') p = pop(a_stack) print(empty(a_stack)) P a g e | 22 This is not at all bad and you could begin to wonder what OOP all about is A problem might come up though if a queue was also required and someone had been foolish enough to implement removing an item from the front of the queue as pop() Then with: from stack import * from queue import * queue's pop() would hide the stack's pop() and the wrong function would get called REFERENCES 1.Wikipedia.org (2019) Shortest path problem [online] Available at: https://en.wikipedia.org/wiki/Shortest_path_problem [Accessed 10/12/2022] P a g e | 23 geeksforgeeks.org (2019) stack push() and pop() in C++ STL [online] Available at https://www.geeksforgeeks.org/stack-push-and-pop-in-c-stl/ [Accessed 10/12/2022] hackerearth.com (2019) Dijkstra's Algorithm [online] Available at: https://www.hackerearth.com/practice/notes/dijkstrasalgorithm/?utm_source=header&utm_medium=search&utm_campaign=he-search [Accessed 10/12/2022] en.wikibooks.org (2019) Data Structure Stack and Queues [online] Available at: https://en.wikibooks.org/wiki/Data_Structures/Stacks_and_Queues [Accessed 10/12/2022] 5.freecodecamp.org (2019) Data Structures 101: Stacks Available at: https://www.freecodecamp.org/news/data-structures-101-stacks-696b3282980/ [Accessed 10/12/2022] geeksforgeeks.org (2019) stack push() and pop() in C++ STL [online] Available at https://www.geeksforgeeks.org/stack-push-and-pop-in-c-stl/ [Accessed 10/12/2022] geeksforgeeks.org (2019) stack push() and pop() in C++ STL [online] Available at https://www.geeksforgeeks.org/stack-push-and-pop-in-c-stl/ [Accessed 10/12/2022] geeksforgeeks.org (2019) stack push() and pop() in C++ STL [online] Available at https://www.geeksforgeeks.org/stack-push-and-pop-in-c-stl/ [Accessed 10/12/2022] stack push() and pop() in C++ STL [online] Available at: https://www.google.com.vn/search?q=What+is+ADT%3F&hl=vi&sxsrf=ALiCzsbQPlah1WmPEQwe22 JSoVhTgQ9CJw:1665574100972&source=lnms&tbm=isch&sa=X&ved=2ahUKEwjWtYqFy9r6AhXvQP UHHcWdBdYQ_AUoAXoECAIQAw&biw=723&bih=730&dpr=1.25#imgrc=EmzUsLQ3b2QcjM [Accessed 10/12/2022] 10.freecodecamp.org (2019) Data Structures 101: Stacks Available at: https://www.freecodecamp.org/news/data-structures-101-stacks-696b3282980/ [Accessed 10/12/2022] P a g e | 24 Powered by TCPDF (www.tcpdf.org) Index of comments 3.1 ADT was presented Linear data structures, sorting and searching algorithms were disccused The operations of memory stacks and how it is used to implement function calls in a computer were determined The abstract data type for a sofware stack was specified 3.2 Powered by TCPDF (www.tcpdf.org) Pass