FEN NOEA/IT: Advanced Computer Studies 1 Patterns The concept of patterns originates from architecture (Christopher Alexander, 1977): “Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice” (Christopher Alexander e. a.: “A Pattern Language”. Oxford University Press, New York, 1977.)
FEN NOEA/IT: Advanced Computer Studies 2 (OO) Design Patterns A well known and widely accepted concept in software engineering Developed in the early 1990s and published by Gamma e.a. (“Gang of Four”, GoF) in 1995: “(…) design patterns (…) are descriptions of communicating objects and classes that are customized to solve a general design problem in a particular context.” (Erich Gamma e.a.:”Design Patterns. Elements of Reusable Object-Oriented Software”. Addison-Wesley )
FEN NOEA/IT: Advanced Computer Studies 3 The Benefits of Patterns A pattern captures a proven good design: –A pattern is based on experience –A pattern is discovered – not invented It introduces a new (and higher) level of abstraction, which makes it easier: –to talk and reason about design on a higher level –to document and communicate design One doesn’t have to reinvent solutions over and over again Patterns facilitate reuse not only of code fragments, but of ideas.
FEN NOEA/IT: Advanced Computer Studies 4 Patterns as a Learning Tool It is often said that good skills in software construction require experience and talent …and neither can be taught or learned at school Patterns capture experience (and talent) in a way that is communicable and comprehensible …and hence experience can be taught (and learned) So we should rely heavily on patterns in our teaching
FEN NOEA/IT: Advanced Computer Studies 5 Algorithm Patterns The term is not commonly used in literature, but the concept is well known. Terms used in textbooks are: –Algorithm paradigms –Algorithm (or solution) strategies –Methodologies For several years we have used the the term “Algoritmeskabeloner” in Danish I propose that we introduce the term “Algorithm Patterns” in our international programme
FEN NOEA/IT: Advanced Computer Studies 6 Algorithm Patterns Many different problems from many different problem domains may be solved by algorithms that possess a common structure – or a common pattern. By abstracting and formalizing this structure it becomes a reusable pattern with all the desired properties connected to patterns. Patterns have names – within the field of algorithms the following – among others – may be identified: –Sweep algorithms –Search algorithms –Merge algorithms –Divide and Conquer algorithms –Greedy algorithms –Backtracking algorithms –Dynamic programming etc. etc.…
FEN NOEA/IT: Advanced Computer Studies 7 The Sweep Algorithm Pattern Purpose: –inspects all elements in a collection (senselessly sweeping through the collection) and doing something according to the characteristics of the current element. Benefits: –separates operations depending on the collection (loop control) from operations depending on the actual problem at hand.
FEN NOEA/IT: Advanced Computer Studies 8 The Sweep Algorithm Pattern Examples: counting the number of students older than 25 years in of list of students increasing the value of a discount percentage by 10 on all elements with a balance of more than DKK 10,000 in a set of customers calculating the average number of words per sentence in a text etc.
FEN NOEA/IT: Advanced Computer Studies 9 The Sweep Pattern - Structure Notation: US: Unvisited set ; while { ; } // end while Please note: INIT, DONE, SELECT and REMOVE depends only on the data representation The realisation of DO_INIT and DO depends on the concrete task to be accomplished by the algorithm as well as the data representation The structure is independent of the task and data representation
FEN NOEA/IT: Advanced Computer Studies 10 Sweep Algorithms on Sequences of Integers visitedUS a: i Data representation (Java): An array, a and a counter, i: int i; int a[]; INIT, DONE, SELECT and REMOVE may be concretised by a counter: i Concretisation of the abstract operations then yields: –INIT:i = 0 –DONE:i >= a.length –SELECT:a[i] –REMOVE:i++ ; int i = 0; while ( i < a.length ) { ; i++; } // end while
FEN NOEA/IT: Advanced Computer Studies 11 Sweep Algorithms on Sequences of Integers visitedUS a: i Data representation (Java): int i; int a[]; ; int i = 0; while ( i < a.length ) { ; i++; } // end while ; for (int i= 0 ; i < a.length ; i++ ) { ; } // end for In Java a counter controlled loop may be written simpler using the for-statement.
FEN NOEA/IT: Advanced Computer Studies 12 Applying the Sweep Pattern Counting zeros in an array: DO_INIT:int count= 0; DO:if (a[i] = = 0) count++; int count= 0; for (int i= 0 ; i < a.length; i++){ if (a[i] = = 0) count++; } // end for ; for (int i= 0 ; i < a.length ; i++ ) { ; } // end for
FEN NOEA/IT: Advanced Computer Studies 13 Applying the Sweep Pattern Increasing all elements by one: DO_INIT:no concretising is needed. DO:a[i]++; ; for (int i= 0 ; i < a.length ; i++ ) { ; } // end for for (int i= 0 ; i < a.length; i++) { a[i]++; } // end for
FEN NOEA/IT: Advanced Computer Studies 14 The Sweep Pattern in C# Loops may be written more simply using the foreach loop: ArrayList a = new ArrayList(); foreach (int x in a) System.Console.WriteLine(x); The foreach loop can only be used if: 1.The collection implements IEnumerable 2.The elements in the collection are not changed The reason for this is that the foreach is implemented using an iterator:
FEN NOEA/IT: Advanced Computer Studies 15 Iterators in C# An iterator is an object that encapsulations the internal structure of a collection and still allowing iteration through the collection In C# iterators are called enumerators Example: IList a = new ArrayList(); IEnumerator it = a.GetEnumerator(); while (it.MoveNext()) { //it.Current = (int)it.Current * 3; System.Console.WriteLine(it.Current); } Current is a read-only property
FEN NOEA/IT: Advanced Computer Studies 16 The Search Algorithm Pattern Purpose: –The algorithm looks for an element (target, t) with some specified property in a collection Benefits: –The search terminates when the first occurrence of the target is discovered –Loop control is separated from the testing for the desired property Examples: –Searching for a customer with a balance greater than DKK 10,000 –Searching for a student older than 30 –Searching for the word “algorithm” in a text.
FEN NOEA/IT: Advanced Computer Studies 17 The Search Pattern - Structure Notation: CC: Candidate Collection c: Element to be examined t:The target element ; boolean found= false; while ( ! found && ) { ; if ( ) found = true; else { } Only the abstract operations (in red) are problem specific The structure is general and reusable
FEN NOEA/IT: Advanced Computer Studies 18 Formalism The abstract operations ought to be formally specified, but in this context we will rely on intuition.
FEN NOEA/IT: Advanced Computer Studies 19 initialise:int i = 0 select:c = a[i] CC Ø:i < a.length split:i ++ CC a: i int c; int i= 0; boolean found= false; while ( !found && i<a.length ) { c = a[i]; if (c == target) found= true; else i ++; } // end while Does this realisation meet the requirements? Applying the pattern to an int[] a Conditions connected to loop control Conditions connected to the actual search
FEN NOEA/IT: Advanced Computer Studies 20 Binary Search: A "smart" realisation of the search pattern on a sorted sequence The strategy: –Select an element in the middle of the candidate set: If this is the element we are looking for – we are done If the target comes after the middle element, then look in the upper part (remember the collection is sorted) If the target comes before the middle element, then look in the lower part (again remember the collection is sorted) –Repeat this until the target has been found or there are no more candidate elements
FEN NOEA/IT: Advanced Computer Studies 21 CC a: lowhigh Binary Search: Applied to a sorted array of integers int low = 0; int high = a.length -1; int c, middle; boolean found = false; while ( ! found && low<=high ) { middle = (high + low) / 2; c= a[middle]; if (c == t) found= true; else if ( c<t )low = middle+1; else high= middle-1; } // end while INITIALISE:int low = 0; int high= a.length; SELECT:middle= (low´+high)/2 c = a[i] CC Ø:low <= high SPLIT:if (k<m) low= middle + 1; else high:= middle – 1; INITIALISE:int low = 0; int high= a.length; SELECT:middle= (low+high)/2 c = a[middle] CC Ø:low <= high SPLIT:if (c<t) low= middle + 1; else high= middle – 1;
FEN NOEA/IT: Advanced Computer Studies 22 Binary Search Please note: –Binary search is very efficient (logarithmic in execution time), but: The realisation of SPLIT relies heavily on the precondition that the array is sorted. The realisation of SELECT requires that the data representation provides random access to elements. Binary search is not to be applied otherwise (don’t ever use it on linked lists)
FEN NOEA/IT: Advanced Computer Studies 23 Merge Pattern The Merge Pattern deals with the problem of joining two sorted sequences into one sorted sequence. The following example illustrates merging two sequences s and t into a third sequence r: Let s = [1, 3, 6, 7, 9] and t = [1, 2, 5, 7, 11, 17] Then r = [1, 1, 2, 3, 5, 6, 7, 7, 9, 11, 17]
FEN NOEA/IT: Advanced Computer Studies 24 Merge Pattern s.reset(); t.reset(); while(s.hasMore() && t.hasMore()){ if(s.getCurrent()<t.getCurrent()){ s.next(); } else { if(s.getCurrent() > t.getCurrent()){ t.next(); } else{ s.next(); t.next(); } } } if(s.hasMore()) else
FEN NOEA/IT: Advanced Computer Studies 25 Merge Pattern View the code: MergePattern.zip
FEN NOEA/IT: Advanced Computer Studies 26 Opgave Brug Merge Pattern til at realisere følgende metoder: public static int[] MergeUnion(int[] s, int[] t) //returnerer fletning af s og t uden dubletter //dvs. foreningsmængde public static int[] MergeIntersect(int[] s, int[] t) //returnerer elementer som er i både s og t //dvs. fællesmængde public static int[] MergeDifference(int[] s, int[] t) //returnerer elementer som er i s, men ikke i t //dvs. mængdedifferens