Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Going further • Recursion • Collections • Beyond Java Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-1 Recursion • Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems • A recursive definition is one which uses the word or concept being defined in the definition itself – a recursive definition of an English word is often not helpful – In math and computer science, a recursive definition can be an appropriate way to express a concept Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-2 Recursive Definitions • Consider the following list of numbers: 24, 88, 40, 37 • Such a list can be defined as follows: A LIST is a: or a: number number comma LIST • That is, a LIST is defined to be a single number, or a number followed by a comma followed by a LIST • The concept of a LIST is used to define itself Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-3 Recursive Definitions • The recursive part of the LIST definition is used several times, terminating with the non-recursive part: number comma LIST 24 , 88, 40, 37 number comma LIST 88 , 40, 37 number comma LIST 40 , 37 number 37 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-4 Infinite Recursion • All recursive definitions have to have a nonrecursive part • If they didn't, there would be no way to terminate the recursive path • Such a definition would cause infinite recursion • This problem is similar to an infinite loop, but the non-terminating "loop" is part of the definition itself • The non-recursive part is often called the base case Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-5 Recursive Definitions • N!, for any positive integer N, is defined to be the product of all integers between 1 and N inclusive • This definition can be expressed recursively as: 1! N! = = 1 N * (N-1)! • A factorial is defined in terms of another factorial • Eventually, the base case of 1! is reached Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-6 Recursive Definitions 5! 120 5 * 4! 24 4 * 3! 6 3 * 2! 2 2 * 1! 1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-7 Recursive Programming • A method in Java can invoke itself; if set up that way, it is called a recursive method • The code of a recursive method must be structured to handle both the base case and the recursive case • Each call to the method sets up a new execution environment, with new parameters and local variables • As with any method call, when the method completes, control returns to the method that invoked it (which may be an earlier invocation of itself) • See Factorial.java Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-8 Recursive Programming • Note that just because we can use recursion to solve a problem, doesn't mean we should • For instance, we usually would not use recursion to solve the sum of 1 to N problem, because the iterative version is easier to understand • However, for some problems, recursion provides an elegant solution, often cleaner than an iterative version • You must carefully decide whether recursion is the correct technique for any problem Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-9 Recursive Directory Listing • Suppose you want to list all the files in a directory including files in any subdirectories that might be present. • Algorithm for each entry in the current directory if it is a file, print its name else // must be a directory do recursive call on the entry Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-10 Towers of Hanoi • The Towers of Hanoi is a puzzle made up of three vertical pegs and several disks that slide on the pegs • The disks are of varying size, initially placed on one peg with the largest disk on the bottom with increasingly smaller ones on top • The goal is to move all of the disks from one peg to another under the following rules: – We can move only one disk at a time – We cannot move a larger disk on top of a smaller one Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-11 Towers of Hanoi Original Configuration Move 1 Move 2 Move 3 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-12 Towers of Hanoi Move 4 Move 5 Move 6 Move 7 (done) Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-13 Towers of Hanoi • An iterative solution to the Towers of Hanoi is quite complex • A recursive solution is much shorter and more elegant • See SolveTowers.java • See TowersOfHanoi.java Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-14 Fractals • A fractal is a geometric shape made up of the same pattern repeated in different sizes and orientations • The Koch Snowflake is a particular fractal that begins with an equilateral triangle • To get a higher order of the fractal, the sides of the triangle are replaced with angled line segments • See KochSnowflake.java • See KochPanel.java Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-15 Koch Snowflakes < x5 , y5 > < x 5 , y5 > < x 4 , y4 > Becomes < x3 , y 3 > < x 2 , y2 > < x1 , y1 > Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley < x 1 , y1 > 11-16 Other Examples of Recursion • Recursive sort algorithms • Recursive data structures – Chapter 12 – COMPSCI 225 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-17 Collections Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-18 Collections • A collection is an object that serves as a repository for other objects • A collection usually provides services such as adding, removing, and otherwise managing the elements it contains • Sometimes the elements in a collection are ordered, sometimes they are not • Sometimes collections are homogeneous, containing all the same type of objects, and sometimes they are heterogeneous Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-19 Dynamic Structures • A static data structure has a fixed size • This meaning is different from the meaning of the static modifier • Arrays are static; once you define the number of elements it can hold, the size doesn’t change • A dynamic data structure grows and shrinks at execution time as required by its contents • A dynamic data structure is implemented using links Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-20 Object References • Recall that an object reference is a variable that stores the address of an object • A reference also can be called a pointer • References often are depicted graphically: student John Smith 40725 3.58 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-21 References as Links • Object references can be used to create links between objects • Suppose a Student class contains a reference to another Student object John Smith 40725 3.57 Jane Jones 58821 3.72 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-22 References as Links • References can be used to create a variety of linked structures, such as a linked list: studentList Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-23 Queues • A queue is similar to a list but adds items only to the rear of the list and removes them only from the front • It is called a FIFO data structure: First-In, First-Out • Analogy: a line of people at a bank teller’s window enqueue Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley dequeue 12-24 Stacks • A stack ADT is also a linear data structure Stacks often are drawn vertically: • Items are added and removed from only one end of a stack push pop • It is therefore LIFO: LastIn, First-Out • Example: a stack of plates in a cupboard, a stack of hay bales in a barn Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-25 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 • In a general tree, each node can have many child nodes • We often work with binary trees which have no more than two children per node Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-26 Binary Trees • In a binary tree, each node can have no more than two child nodes • A binary tree can be 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 • Trees are typically are represented using references as dynamic links, though it is possible to use fixed representations like arrays • For binary trees, this requires storing only two links per node to the left and right child Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-27 Graphs • A graph is a non-linear structure • Unlike a tree or binary tree, a graph does not have a root • Any node in a graph can be connected to any other node by an edge • Analogy: the highway system connecting cities on a map Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-28 The Java Collections API Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-29 Collection Classes • The Java standard library contains several classes that represent collections, often referred to as the Java Collections API • Their underlying implementation is implied in the class names such as ArrayList and LinkedList • Several interfaces are used to define operations on the collections, such as List, Set, SortedSet, Map, and SortedMap Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-30 Generics • As mentioned in Chapter 7, Java supports generic types, which are useful when defining collections • A class can be defined to operate on a generic data type which is specified when the class is instantiated: LinkedList<Book> myList = new LinkedList<Book>(); • By specifying the type stored in a collection, only objects of that type can be added to it • Furthermore, when an object is removed, its type is already established Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-31 Beyond java Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-32 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 objectoriented – C++ was designed to be backwards-compatible with C – C# was based on C/C++ without the backwardscompatibility – 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 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12-33 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 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley First Program namespace FirstProgram { class First { static void Main() { System.Console.WriteLine( "Welcome to C#!"); } } } Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C# Types • Value types – simple types: primitive types from Java plus unsigned types and decimal • Reference types - objects Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Operators • Has same operators as Java with similar precedence and associativity • == compares values for strings and simple types, addresses for all other objects Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C# using VMWare • There is a Windows virtual machine on the onyx workstations – vmware & • C# Express is installed on the virtual machine • You can download the .NET development environment to your own Windows machine for free using your MSDN account Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley