Complex objects How might you design a class called NestedRects of graphical objects that look like this? Requirements for the constructor: –Like many.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Getting started with ML ML is a functional programming language. ML is statically typed: The types of literals, values, expressions and functions in a.
TOPIC 12 CREATING CLASSES PART 1 1 Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson,
Introduction to Computing Science and Programming I
Lecture 2 Introduction to C Programming
Recursive methods. Recursion A recursive method is a method that contains a call to itself Often used as an alternative to iteration when iteration is.
CSC1016 Coursework Clarification Derek Mortimer March 2010.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Computer Science 1620 Loops.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
IAT 800 Lab 1: Loops, Animation, and Simple User Interaction.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
16-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Chapter 11 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Stacks (Revised and expanded from CIT 591). What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on.
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Stacks. What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
Recursion. Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example: A list.
1 Infinite Loops  The body of a while loop eventually must make the condition false  If not, it is an infinite loop, which will execute until the user.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Games and Simulations O-O Programming in Java The Walker School
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
COMPSCI 101 Principles of Programming Lecture 27 - Using the Canvas widget to draw rows and columns of shapes.
1 CSC 222: Computer Programming II Spring 2005 Stacks and recursion  stack ADT  push, pop, peek, empty, size  ArrayList-based implementation, java.util.Stack.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Recursion. Basic problem solving technique is to divide a problem into smaller subproblems These subproblems may also be divided into smaller subproblems.
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
Intermediate Algebra Prerequisite Topics Review Quick review of basic algebra skills that you should have developed before taking this class 18 problems.
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
Recursion A method is recursive if it makes a call to itself. A method is recursive if it makes a call to itself. For example: For example: public void.
Unit 2, cont. September 12 More HTML. Attributes Some tags are modifiable with attributes This changes the way a tag behaves Modifying a tag requires.
CIS 068 Welcome to CIS 068 ! Stacks and Recursion.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
Input, Output, and Processing
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
1 Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering CS 241 Computer Programming II CS 241 – Computer Programming.
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
1 Textual Data Many computer applications manipulate textual data word processors web browsers online dictionaries.
(c) University of Washington16-1 CSC 143 Java Linked Lists Reading: Ch. 20.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Types and Interfaces COMP.
1 Arrays of Arrays An array can represent a collection of any type of object - including other arrays! The world is filled with examples Monthly magazine:
Recursion Chapter 11. How it works “A recursive computation solves a problem by using the solution of the same problem with simpler inputs” Big Java,
1 Recursive algorithms Recursive solution: solve a smaller version of the problem and combine the smaller solutions. Example: to find the largest element.
Recursion ITI 1121 N. El Kadri. Reminders about recursion In your 1 st CS course (or its equivalent), you have seen how to use recursion to solve numerical.
Programming in Java (COP 2250) Lecture 12 & 13 Chengyong Yang Fall, 2005.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Section Recursion  Recursion – defining an object (or function, algorithm, etc.) in terms of itself.  Recursion can be used to define sequences.
Recursion (Continued)
Java Programming: Guided Learning with Early Objects
Java Software Structures: John Lewis & Joseph Chase
Applied Algorithms (Lecture 17) Recursion Fall-23
Lesson 2: Building Blocks of Programming
Stacks.
Implementing Non-Static Features
Stacks.
Recursion Taken from notes by Dr. Neil Moore
Special instance methods: toString
Presentation transcript:

Complex objects How might you design a class called NestedRects of graphical objects that look like this? Requirements for the constructor: –Like many graphical objects, takes 5 parameters: x and y describing coordinates of upper left width and height of outermost rectangle canvas –Spacing between rectangles is 4 pixels

Constructor for NestedRects public NestedRects (double x double y, double width, double height, DrawingCanvas canvas) { new FramedRect(x, y, width, height, canvas); while (width >= 8 && height >= 8) { width = width - 8; height = height - 8; x = x + 4; y = y + 4; new FramedRect(x, y, width, height, canvas); }

Making NestedRects Useful Say that we want NestedRects objects to behave much like other graphical objects? NestedRects class should define methods like –moveTo –removeFromCanvas But our constructor just draws the object! Need a way to keep track of entire collection of nested rectangles!

Challenges Need to keep track of the rectangles in the collection Instance variables for each of the rectangles won’t work: FramedRect rectangle1, rectangle2; We don’t know how many there will be until a user specifies parameters when constructing one!

A Recursive Solution A recursive structure consists of –A base structure (the simplest form of the structure) –A way to describe complex structures in terms of simpler structures of the same kind Let’s change the way we think about NestedRects –Rather than a series of FramedRects… –An outer FramedRect + a smaller NestedRects inside

NestedRects: a recursive def’n public class NestedRects { private FramedRect outerRect; // outermost rectangle private NestedRects rest; // inner nested rects public NestedRects(double x, double y, double width, double height, DrawingCanvas canvas) { outerRect = new FramedRect(x, y, width, height, canvas); if (width >= 8 && height >= 8) { rest = new NestedRects(x+4, y+4, width-8, height-8, canvas); } else { rest = null; // nothing more to construct }

// Move nested rects to (x, y) public void moveTo(double x, double y) { outerRect.moveTo(x, y); if (rest != null) { rest.moveTo(x+4, y+4); } // Remove the nested rects from the canvas public void removeFromCanvas() { outerRect.removeFromCanvas(); if (rest != null) { rest.removeFromCanvas(); }

Tracing the execution of new NestedRects( 50, 50, 19, 21, canvas);

Tracing the execution of moveTo( 84, 104 )

A Better Recursive Solution? moveTo and removeFromCanvas require checking whether rest is null Missing check will cause program to crash Can we write NestedRects to avoid the check for null?

Two Kinds of NestedRects “Normal” recursive case –outerRect –rest A special “simplest” NestedRects: empty! Define a new class, BaseRects, representing an empty collection of FramedRects

A NestedRects Interface Recursive and empty nested rectangles are different, but they’re still collections of nested rectangles public interface NestedRectsInterface { // Move nested rectangles to (x, y) void moveTo(double x, double y); // Remove nested rectangles from canvas void removeFromCanvas(); }

A Simple Base Class public class BaseRects implements NestedRectsInterface { // Constructor has nothing to initialize public BaseRects() { } // Move nested rectangles to (x, y) public void moveTo(double x, double y) { } // Remove nested rectangles from canvas public void removeFromCanvas() { } }

Revised Recursive Class public class NestedRects implements NestedRectsInterface { private FramedRect outerRect; // outermost rectangle private NestedRectsInterface rest; // inner nested rects public NestedRects(double x, double y, double width, double height, DrawingCanvas canvas) { outerRect = new FramedRect(x, y, width, height, canvas); if (width >= 8 && height >= 8) { rest = new NestedRects(x+4, y+4, width-8, height-8, canvas); } else { // construct a base object rest = new BaseRects(); }

// Move nested rects to (x, y) public void moveTo(double x, double y) { outerRect.moveTo(x, y); rest.moveTo(x+4, y+4) } // Remove the nested rects from the canvas public void removeFromCanvas() { outerRect.removeFromCanvas(); rest.removeFromCanvas(); }

Evaluating new NestedRects(54, 54, 11, 13, canvas)

Since objects of type BaseRects and NestedRects know how to “moveTo” and “removeFromCanvas” … Checks for null are eliminated!

Data Collections as Recursive Structures: an Example Useful feature of some web browsers: automatic address completion Type Browser responds with suggestion Browser needs a way to keep track of all URLs typed in by a user in order to provide the most useful suggestions

List of URLs as a recursive structure What capabilities should a list of URLs have? Define an interface: public interface UrlListInterface { // Returns a list of all entries starting with prefix public UrlListInterface getmatches(String prefix); // Determines whether the collection contains url public boolean contains(String url); //Convert list to a string; entries separated by new lines public String toString(); }

Empty UrlList as a base class public class EmptyUrlList implements UrlListInterface { public EmptyUrlList( ) { } public UrlListInterface getMatches(String prefix) { return new EmptyUrlList( ); } public boolean contains(String url) { return false; } public String toString() { return ""; }

A non-empty UrlList public class NonemptyUrlList implements UrlListInterface { private String firstUrl; // The first URL in the list Private UrlListInterface rest;// The rest of the list of URLs public NonemptyUrlList(String newURL, UrlListInterface existingList) { firstUrl = newURL; rest = existingList }

public UrlListInterface getMatches(String prefix) { if ( firstUrl.startsWith(prefix) ) { return new NonemptyUrlList(firstUrl, rest.getMatches(prefix)); } else { return rest.getMatches(prefix); } public boolean contains(String url) { return firstUrl.equals( url ) || rest.contains( url ); } public String toString() { // "\n" is a newline character return firstUrl + "\n" + rest.toString( ); }

Designing recursive structures Recursive structures built by defining classes for base and recursive cases –Both implement same interface –Base class No instance variable has same type as interface or class Generally easy to write –Recursive class At least one instance variable has same type as interface of class Care needed to be sure methods terminate

Implementing recursive structures Define interface with methods that both base and recursive classes must implement Define one or more base classes –Convince yourself that constructor and methods work properly Define constructors for recursive classes –Recursive calls of constructor only create objects simpler than the one being built –Should eventually end up at a base class Write methods for recursive classes

Recursive Methods Can write recursive methods that are not part of recursive structures Complexity controlled by an int parameter –Recursive invocations simpler –Simpler = smaller, non-negative parameter

Base case replaces Base class Recursive methods Must include at least one base case Typically contain a conditional statement –At least one case is a recursive invocation –At least one case is a base case -- i.e., no recursive invocation of the method

An example: Exponentiation Inspiration: Fast algorithms for exponentiation important to RSA algorithm for public key cryptography A simple (not fast!) recursive method: // returns base raised to exponent as long as exponent >=0 public double simplePower(double base, int exponent) { if (exponent == 0) { return 1; } else { return base * simplePower(base, exponent-1); }

Rules for writing recursive methods Write the base case –No recursive call Write the recursive case –All recursive calls should go to simpler cases –Simpler cases must eventually reach base case

Applying rules to simplePower Base case: exponent == 0 –Returns 1 –Correct answer for raising base to the 0th power –No recursive invocation Recursive case: uses else clause –Recursive call involves smaller value for exponent –Recursive calls eventually reach base case of 0: exponent greater than 0 to start and always goes down by 1

Rules of Exponents Simple algorithm took advantage of these rules: –base 0 = 1 –base exp+1 = base * base exp New algorithm will make use of this rule: –Base m*n = (base m ) n Let m = 2, n = exp/2

Faster exponentiation public double fastPower(double base, int exponent) { if (exponent == 0) { return 1; } else if ( exponent%2 == 1 ) { return base * fastPower(base, exponent-1); } else { return fastPower(base* base, exponent/2); }

Tracing fastPower fastPower(3, 16) = fastPower(9, 8) = fastPower(81, 4) = fastPower(6561, 2) = fastPower( , 1) = * fastPower( , 0) = * 1 = Only 5 multiplications! Division by 2 is fast and easy for computers