Presentation is loading. Please wait.

Presentation is loading. Please wait.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 1 What comes next? Recursion (Chapter 6, 15) Recursive Data Structures.

Similar presentations


Presentation on theme: "©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 1 What comes next? Recursion (Chapter 6, 15) Recursive Data Structures."— Presentation transcript:

1 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 1 What comes next? Recursion (Chapter 6, 15) Recursive Data Structures Pattern Matching (Chapter 9) Other languages: C# Using an IDE: Eclipse This material will not be on the final.

2 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 2 Recursion Recursion solves a problem by breaking it down into one or more smaller problems with the same structure. Examples –Any problem that involves doing something with each element of a list can be thought of as processing the first element and then processing the rest of the list –Many mathematical functions are defined recursively –Data structures can be recursive Directory structures are recursive –The best sorting algorithms are recursive An recursive method is a method that makes a call to itself. Basic solution structure –If problem is small enough, solve it –If not, recur on a smaller version of the problem.

3 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 3 Recursive Definitions The factorial of N is the product of the first N positive integers: N * (N – 1) * (N – 2 ) *... * 2 * 1 The factorial of N can be defined recursively as 1 if N = 1 factorial( N ) = N * factorial( N-1 ) otherwise

4 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 4 Recursive Method Implementing the factorial of N recursively will result in the following method. public int factorial( int N ) { if ( N == 1 ) { return 1; } else { return N * factorial( N-1 ); } } Test to stop or continue. Recursive case: recursion continues. End case: recursion stops.

5 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 5 Anagrams List all anagrams of a given word. Word C A T C T A A T C A C T T C A T A C Anagrams

6 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 6 Recursive Solution The basic idea is to make recursive calls on a sub-word after every rotation. Here’s how: C C A A T T Recursion A A T T C C T T C C A A Rotate Left C A T C T A A T C A C T T C A T A C

7 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 7 Towers of Hanoi The goal of the Towers of Hanoi puzzle is to move N disks from peg 1 to peg 3: –You must move one disk at a time. –You must never place a larger disk on top of a smaller disk.

8 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 8 Towers of Hanoi Solution

9 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 9 Recursive Sorting Algorithms There are two commonly used sorting methods that use recursion –Merge sort: sort each half of the array and merge the sorted halves together –Quicksort: use a pivot value to separate the array into two parts Both these methods are more efficient that the sorts we’ve seen before –N log N instead of N 2

10 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 10 Quicksort To sort an array from index low to high, we first select a pivot element p. –Move all elements less than the pivot to the first half of an array and all elements larger than the pivot to the second half. Put the pivot in the middle. –Recursively apply quicksort on the two halves.

11 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 11 When Not to Use Recursion When recursive algorithms are designed carelessly, it can lead to very inefficient and unacceptable solutions. For example, consider the following: public int fibonacci( int N ) { if (N == 0 || N == 1) { return 1; } else { return fibonacci(N-1) + fibonacci(N-2); }

12 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 12 Excessive Repetition Recursive Fibonacci ends up repeating the same computation numerous times.

13 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 13 Static vs. Dynamic Structures A static data structure has a fixed size Arrays are static –Once you instantiate it, the length is constant –To get a different size, you have to instantiate a new array –An ArrayList can change its size but it really just hides the work involved in changing the size of a static structure Dynamic data structures grow and shrink as needed at execution time A dynamic data structure is implemented using reference variables called links

14 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 14 References as Links Recall that an object reference is a variable that stores the address of an object Object references can be used to create links between objects Suppose a Student object contains a reference to another Student object John Smith 40725 3.57 Jane Jones 58821 3.72

15 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 15 References as Links References can be used to create a variety of linked structures, such as a linked list: This is called a LinkedList –LinkedList class has same methods as ArrayList studentList

16 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 16 Other Dynamic List Representations doubly linked list, with next and previous references A queue adds items to the rear of the list and removes them from the front list enqueue dequeue

17 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 17 Trees and Binary Trees A tree is a non-linear data structure that consists of a root node and potentially many levels of additional nodes that form a hierarchy –Each node can be linked to at least two other nodes A binary tree is defined recursively. Either it is empty (the base case) or it consists of a root and two subtrees, each of which is a binary tree Directories form a tree-like structure

18 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 18 Other Languages There are a number of other languages with a syntax very similar to that of Java –Java's syntax is based on that of C which is not object- oriented –C++ was designed to be backwards-compatible with C –C# was based on C/C++ without the backwards- compatibility –Many of the scripting languages started from C's syntax JavaScript is a scripting language that is used inside web pages –It is not related to Java

19 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Other Languages: C# Like Java, C# is –A modern, general-purpose object-oriented language –Based on C and C++ C# is part of the.NET family of languages supported by MicroSoft –Multiple languages which can interoperate –Languages compile to a common intermediate language –Common Language Runtime runs programs from all the.NET languages

20 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. C# Program Structure A program consists of one or more files A file can contain one or more classes and/or namespaces –name of file is not tied to name of class At least one class must contain Main –There are several allowed signatures return type is either int or void either no parameter or String array

21 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. First Program namespace FirstProgram { class First { static void Main() { System.Console.WriteLine( "Welcome to C#!"); }

22 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Console I/O System.Console.WriteLine( arg) –argument can be any type –for objects, ToString is invoked System.Console.ReadLine() –returns a String System is a namespace –using System; allows you to omit the namespace when calling the method

23 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. C# Types Value types –simple types: primitive types from Java plus unsigned types and decimal Reference types - objects

24 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Operators Has same operators as Java with similar precedence and associativity == compares values for strings and simple types, addresses for all other objects

25 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. C# on onyx mono is an open-source project that provides facilities for running C# programs under Linux http://www.mono-project.com Compile a program by typing mcs First.cs Run a program by typing mono First.exe

26 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 26 Using an IDE IDE = Integrated Development Environment –Do all your editing, compiling and running from inside the IDE program –Debugger allows you to execute your program in steps and look at the variables to see what is happening. Eclipse is an IDE used for Java –available on onyx

27 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 27 Patterns and Regular Expressions Chapter 9, sections 3-4

28 Regular Expressions When you are searching for –words in a document –files with a particular name When you need to determine whether a string has the correct formatto be –a telephone number –a zip code –a student ID you need a way of describing what you want to see Regular expressions provide a special language that can be used for these types of tasks

29 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 29 Regular Expressions The pattern is called a regular expression. Rules –The brackets [ ] represent choices –The asterisk symbol * means zero or more occurrences. –The plus symbol + means one or more occurrences. –The hat symbol ^ means negation. –The hyphen – means ranges. –The parentheses ( ) and the vertical bar | mean a range of choices for multiple characters.

30 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 30 Pattern Example Suppose students are assigned a three-digit code: –The first digit represents the major (5 indicates computer science); –The second digit represents either in-state (1), out-of-state (2), or foreign (3); –The third digit indicates campus housing: On-campus dorms are numbered 1-7. Students living off-campus are represented by the digit 8. The 3-digit pattern to represent computer science majors living on-campus is 5[123][1-7] first character is 5 second character is 1, 2, or 3 third character is any digit between 1 and 7

31 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 31 Regular Expression Examples Matches AZxx, CAxx, and COxx, where x is a single digit. (AZ|CA|CO)[0-9][0-9] Matches wad, weed, bad, and beed. [wb](ad|eed) A valid Java identifier consisting of alphanumeric characters, underscores, and dollar signs, with the first character being an alphabet. [a-zA-z][a-zA-Z0- 9_$]* A single digit 0, 1, or 3. [013] A single character that is either a lowercase letter or a digit. [a-z0-9] A single digit that is 0, 1, 2, 3, 8, or 9. [0-9&&[^4567]] Any two-digit number from 00 to 99. [0-9][0-9] DescriptionExpression

32 Java Classes for Pattern Matching The String class has replaceAll, split and matches that use strings representing patterns The Pattern and Matcher classes are provided to support pattern matching operations Scanner uses patterns for delimiters

33 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 33 The replaceAll Method The replaceAll method replaces all occurrences of a substring that matches a given regular expression with a given replacement string. String originalText, modifiedText; originalText =...; //assign string modifiedText = originalText.replaceAll("[aeiou]","@"); Replace all vowels with the symbol @

34 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 34 The Pattern and Matcher Classes The matches and replaceAll methods of the String class are shorthand for using the Pattern and Matcher classes from the java.util.regex package. If str and regex are String objects, then str.matches(regex); is equivalent to Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(str); matcher.matches();

35 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 35 The compile Method The compile method of the Pattern class converts the stated regular expression to an internal format to carry out the pattern-matching operation. This conversion is carried out every time the matches method of the String class is executed, so it is more efficient to use the compile method when we search for the same pattern multiple times. See the sample programs Ch9MatchJavaIdentifier2 and Ch9PMCountJava

36 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 36 The find Method The find method is another powerful method of the Matcher class. –It searches for the next sequence in a string that matches the pattern, and returns true if the pattern is found. When a matcher finds a matching sequence of characters, we can query the location of the sequence by using the start and end methods. See Ch9PMCountJava2


Download ppt "©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 1 What comes next? Recursion (Chapter 6, 15) Recursive Data Structures."

Similar presentations


Ads by Google