COS 312 DAY 23 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone progress report Overdue Assignment 6 Over Due Assignment 7 (bonus) – Due May 11 – Will.

Slides:



Advertisements
Similar presentations
Chapter 17 Recursion.
Advertisements

Chapter 15 Lists. Chapter Scope Types of list collections Using lists to solve problems Various list implementations Comparing list implementations Java.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 7: Recursion Java Software Structures: Designing and Using.
Chapter 8: Recursion Java Software Solutions
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 7 Iterators Modified. Chapter Scope The purpose of an iterator The Iterator and Interable interfaces The concept of fail-fast collections Using.
Chapter 15 Lists.
1 Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  Chapter 11 of the book.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
ELC 310 Day 24. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Agenda Questions? Problem set 5 Parts A Corrected  Good results Problem set 5.
Chapter 13 Linked Structures - Stacks. Chapter Scope Object references as links Linked vs. array-based structures Managing linked lists Linked implementation.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
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.
Chapter 11 Recursion. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Recursion Recursion is a fundamental programming technique that can provide.
Recursion Chapter 5.
© 2004 Pearson Addison-Wesley. All rights reserved October 27, 2006 Recursion (part 2) ComS 207: Programming I (in Java) Iowa State University, FALL 2006.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Arrays Arrays are objects that help us organize large amounts of information.
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.
COS 312 DAY 21 Tony Gauvin. Ch 1 -2 Agenda Questions? Last Capstone Progress reports due April 23 Assignment 6 Due Assignment 7 Posted – Chapters 15,
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 8 Recursion Modified.
Chapter 4 Recursion. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Explain the underlying concepts of recursion.
CSE 501N Fall ‘09 12: Recursion and Recursive Algorithms 8 October 2009 Nick Leidenfrost.
11-1 Recursive Thinking A recursive definition is one which uses the word or concept being defined in the definition itself When defining an English word,
Lecture 7 b Recursion is a fundamental programming technique that can provide an elegant solution to certain kinds of problems b Today: thinking in a recursive.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 8: Recursion Presentation slides for Java Software Solutions for AP* Computer Science 3rd.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
COS 312 DAY 19 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 Layers using non-opaque panels.
Chapter 6 Lists Modified. Chapter Scope Types of lists Using lists to solve problems Various list implementations Comparing list implementations 6 - 2Java.
Iterators ITI 1121 N. El Kadri. Motivation Given a (singly) linked-list implementation of the interface List, defined as follows, public interface List.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Recursion.
Recursion A recursive definition is one which uses the word or concept being defined in the definition itself Example: “A computer is a machine.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
COS 312 DAY 18 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 5 Corrected – 1 A, 2 B’s, 1 C, 1 D 1 F and 1 MIA –
Linked Structures Chapter 13 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
COS 312 DAY 24 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 6 Corrected Assignment 7 (bonus) – Due May 11 – Will be scored on 15 point scale, points.
Iterators. Chapter Scope The purpose of an iterator The Iterator and Interable interfaces The concept of fail-fast collections Using iterators to solve.
COS 312 DAY 20 Tony Gauvin. Ch 1 -2 Agenda Questions? Next Capstone progress report is due April 25 Assignment 5 Graded – Not much original code Assignment.
Recursion.
CHAPTER 4: Linked Structures
Recursion -- Introduction
CprE 185: Intro to Problem Solving (using C)
Abdulmotaleb El Saddik University of Ottawa
Chapter 16 Iterators.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Chapter 8: Recursion Java Software Solutions
Java Software Structures: John Lewis & Joseph Chase
Chapter 4 Linked Structures - Stacks
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Java Software Solutions Foundations of Program Design 9th Edition
Chapter 7 Iterators.
Recursive Definitions
Chapter 12 Recursion (methods calling themselves)
Recursion (part 2) October 26, 2007 ComS 207: Programming I (in Java)
Chapter 4 Linked Structures - Stacks
Chapter 8: Recursion Java Software Solutions
Chapter 8 Recursion.
Chapter 11 Recursion.
Chapter 8: Recursion Java Software Solutions
11 Recursion Software Solutions Lewis & Loftus java 5TH EDITION
Recursion (part 2) March 22, 2006 ComS 207: Programming I (in Java)
Java Software Solutions Foundations of Program Design Sixth Edition
Presentation transcript:

COS 312 DAY 23 Tony Gauvin

Ch 1 -2 Agenda Questions? Capstone progress report Overdue Assignment 6 Over Due Assignment 7 (bonus) – Due May 11 – Will be scored on 15 point scale, points to be added to assignment average. Iterators

Left to do May 5 Chap 17 Recursion May 1 PM Quiz 3 & Capstone presentations (Assignment 7 Bonus) Java Foundations, 3rd Edition, Lewis/DePasquale/Chase5 - 3

Chapter 16 Iterators

Chapter Scope The purpose of an iterator The Iterator and Interable interfaces The concept of fail-fast collections Using iterators to solve problems Iterator implementations Java Foundations, 3rd Edition, Lewis/DePasquale/Chase16 - 5

Iterators Using various methods, the user could write code to access each element in a collection, but it would be slightly different for each collection An iterator is an object that allows the user to acquire and use each element in a collection It works with a collection, but is a separate object An iterator simplifies the classic step of processing elements in a collection Java Foundations, 3rd Edition, Lewis/DePasquale/Chase16 - 6

Iterators There are two key interfaces in the Java API related to iterators: – Iterator – used to define an iterator – Iterable – used to define a collection that provides an iterator A collection is Iterable, which means it will provide an Iterator when requested Example: An Array is Iterable and it provides an Iterator of what ever type was used to construct the array when requested String[4] provides an Iterator of type String Java Foundations, 3rd Edition, Lewis/DePasquale/Chase16 - 7

Iterators The Iterator interface: The Iterable interface: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase16 - 8

Iterators Suppose myList is an ArrayList of Book objects Iterator itr = myList.iterator(); while (itr.hasNext()) System.out.println(itr.next()); The first line obtains the iterator, then the loop uses hasNext and next to access and print each book Java Foundations, 3rd Edition, Lewis/DePasquale/Chase16 - 9

Iterators A for-each loop can be used for the same goal: for (Book book : myList) System.out.println(book); The for-each loop uses an iterator behind the scenes (book) The for-each loop can be used on any object (collection) that is Iterable Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Iterators You may want to use an iterator explicitly if you don't want to process all elements – i.e., searching for a particular element You may also use an explicit iterator if you want to call the remove method The for-each loop does not give access to the iterator, so remove cannot be called Java Foundations, 3rd Edition, Lewis/DePasquale/Chase Iterator itr = myList.iterator(); while (itr.hasNext()) if (itr == “Dune”) itr.remove());

Iterators You shouldn't assume that an iterator will deliver the elements in any particular order unless the documentation explicitly says you can Also, remember that an iterator is accessing the elements stored in the collection The structure of the underlying collection should not be changed while an iterator is being used Most iterators in the Java API are fail-fast, meaning they throw an exception if the collection is modified while the iterator is active Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Concurrency Issues in Comp. Sci. Since modern computers are multithreaded what happens when two processes need access to a common resource (or each other) at the same time? Java Foundations, 3rd Edition, Lewis/DePasquale/Chase Code\chap16\DiningPhilosophers\DiningPhilosophers\Philosophers.java

Program of Study Revisited The ProgramOfStudy class was introduced in the last chapter It implements the Iterable interface Its iterator method returns the iterator provided by the list The POSGrades class uses a for-each loop to print courses with a grade of A or A- Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * Represents a Program of Study, a list of courses taken and planned, for an * individual student. * Java Foundations 4.0 */ public class ProgramOfStudy implements Iterable, Serializable { private List list; /** * Constructs an initially empty Program of Study. */ public ProgramOfStudy() { list = new LinkedList (); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Adds the specified course to the end of the course list. * course the course to add */ public void addCourse(Course course) { if (course != null) list.add(course); } /** * Finds and returns the course matching the specified prefix and number. * prefix the prefix of the target course number the number of the target course the course, or null if not found */ public Course find(String prefix, int number) { for (Course course : list) if (prefix.equals(course.getPrefix()) && number == course.getNumber()) return course; return null; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Adds the specified course after the target course. Does nothing if * either course is null or if the target is not found. * target the course after which the new course will be added newCourse the course to add */ public void addCourseAfter(Course target, Course newCourse) { if (target == null || newCourse == null) return; int targetIndex = list.indexOf(target); if (targetIndex != -1) list.add(targetIndex + 1, newCourse); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Replaces the specified target course with the new course. Does nothing if * either course is null or if the target is not found. * target the course to be replaced newCourse the new course to add */ public void replace(Course target, Course newCourse) { if (target == null || newCourse == null) return; int targetIndex = list.indexOf(target); if (targetIndex != -1) list.set(targetIndex, newCourse); } /** * Creates and returns a string representation of this Program of Study. * a string representation of the Program of Study */ public String toString() { String result = ""; for (Course course : list) result += course + "\n"; return result; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Returns an iterator for this Program of Study. * an iterator for the Program of Study */ public Iterator iterator() { return list.iterator(); } /** * Saves a serialized version of this Program of Study to the specified * file name. * fileName the file name under which the POS will be stored IOException */ public void save(String fileName) throws IOException { FileOutputStream fos = new FileOutputStream(fileName); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(this); oos.flush(); oos.close(); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Loads a serialized Program of Study from the specified file. * fileName the file from which the POS is read the loaded Program of Study IOException ClassNotFoundException */ public static ProgramOfStudy load(String fileName) throws IOException, ClassNotFoundException { FileInputStream fis = new FileInputStream(fileName); ObjectInputStream ois = new ObjectInputStream(fis); ProgramOfStudy pos = (ProgramOfStudy) ois.readObject(); ois.close(); return pos; } Code\chap16\ProgramOfStudy.java Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; /** * Demonstrates the use of an Iterable object (and the technique for reading * a serialzed object from a file). * Java Foundations 4.0 */ public class POSGrades { /** * Reads a serialized Program of Study, then prints all courses in which * a grade of A or A- was earned. */ public static void main(String[] args) throws Exception { ProgramOfStudy pos = ProgramOfStudy.load("ProgramOfStudy"); System.out.println(pos); System.out.println("Classes with Grades of A or A-\n"); for (Course course : pos) { if (course.getGrade().equals("A") || course.getGrade().equals("A-")) System.out.println(course); } } Code\chap16\POSGrades.java Code\chap16\POSGrades.java Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Program of Study Revisited Now we'll use an iterator to remove any course in the program of study that doesn't already have a grade Since the iterator's remove method will be used, we cannot use a for-each loop Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

import java.io.FileInputStream; import java.io.ObjectInputStream; import java.util.Iterator; /** * Demonstrates the use of an explicit iterator. * Java Foundations 4.0 */ public class POSClear { /** * Reads a serialized Program of Study, then removes all courses that * don't have a grade. */ public static void main(String[] args) throws Exception { ProgramOfStudy pos = ProgramOfStudy.load("ProgramOfStudy"); System.out.println(pos); System.out.println("Removing courses with no grades.\n"); Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Iterator itr = pos.iterator(); while (itr.hasNext()) { Course course = itr.next(); if (!course.taken()) itr.remove(); } System.out.println(pos); pos.save("ProgramOfStudy"); } Code\chap16\POSClear.java Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Implementing Array-based Iterators Our ArrayList class contains a private inner class that defines an iterator for the list An iterator is an appropriate use for an inner class because of its intimate relationship with the outer class (the collection) It maintains a modification count that is initialized to the current number of elements in the collection If those counts get out of a sync, the iterator throws a ConcurrentModificationException Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * ArrayListIterator iterator over the elements of an ArrayList. */ private class ArrayListIterator implements Iterator { int iteratorModCount; int current; /** * Sets up this iterator using the specified modCount. * modCount the current modification count for the ArrayList */ public ArrayListIterator() { iteratorModCount = modCount; current = 0; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Returns true if this iterator has at least one more element * to deliver in the iteration. * true if this iterator has at least one more element to deliver * in the iteration ConcurrentModificationException if the collection has changed * while the iterator is in use */ public boolean hasNext() throws ConcurrentModificationException { if (iteratorModCount != modCount) throw new ConcurrentModificationException(); return (current < rear); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Returns the next element in the iteration. If there are no * more elements in this iteration, a NoSuchElementException is * thrown. * the next element in the iteration NoSuchElementException if an element not found exception occurs ConcurrentModificationException if the collection has changed */ public T next() throws ConcurrentModificationException { if (!hasNext()) throw new NoSuchElementException(); current++; return list[current - 1]; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * The remove operation is not supported in this collection. * UnsupportedOperationException if the remove method is called */ public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } Code\chap16\jsjf\ArrayList.java Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Implementing Linked-Based Iterators Similarly, an iterator can use links Like the previous example, the LinkedListItertor class is implemented as a private inner class Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * LinkedIterator represents an iterator for a linked list of linear nodes. */ private class LinkedListIterator implements Iterator { private int iteratorModCount; // the number of elements in the collection private LinearNode current; // the current position /** * Sets up this iterator using the specified items. * collection the collection the iterator will move over size the integer size of the collection */ public LinkedListIterator() { current = head; iteratorModCount = modCount; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Returns true if this iterator has at least one more element * to deliver in the iteration. * true if this iterator has at least one more element to deliver * in the iteration ConcurrentModificationException if the collection has changed * while the iterator is in use */ public boolean hasNext() throws ConcurrentModificationException { if (iteratorModCount != modCount) throw new ConcurrentModificationException(); return (current != null); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Returns the next element in the iteration. If there are no * more elements in this iteration, a NoSuchElementException is * thrown. * the next element in the iteration NoSuchElementException if the iterator is empty */ public T next() throws ConcurrentModificationException { if (!hasNext()) throw new NoSuchElementException(); T result = current.getElement(); current = current.getNext(); return result; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * The remove operation is not supported. * UnsupportedOperationException if the remove operation is called */ public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } Code\chap16\jsjf\LinkedList.java Code\chap16\OrderedLLTester.java Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Chapter 17 Recursion

Chapter Scope The concept of recursion Recursive methods Infinite recursion When to use (and not use) recursion Using recursion to solve problems – Solving a maze – Towers of Hanoi Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Recursion Recursion is a programming technique in which a method can call itself to fulfill its purpose A recursive definition is one which uses the word or concept being defined in the definition itself In some situations, a recursive definition can be an appropriate way to express a concept Before applying recursion to programming, it is best to practice thinking recursively Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Recursive Definitions Consider the following list of numbers: 24, 88, 40, 37 Such a list can be defined recursively: A LIST is a:number or a:number comma LIST That is, a LIST can be a number, or a number followed by a comma followed by a LIST The concept of a LIST is used to define itself How big can a List be? Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Recursive Definitions Java Foundations, 3rd Edition, Lewis/DePasquale/Chase LIST:numbercommaLIST 24,88, 40, 37 numbercommaLIST 88,40, 37 numbercommaLIST 40, 37 number 37

Other Recursive Definitions Recursive acronym – GNU  GNU’s Not UNIX Definitions in Nature – A fern is a fern to the front, a fern to the left and a fern to the right Number series 10, 15, 20, 25, 30, 35 …. a 1 = 10; a n = a n Java Foundations, 3rd Edition, Lewis/DePasquale/Chase5 - 40

Infinite Recursion All recursive definitions must have a non- recursive part (termination or base-case) If they don't, there is no way to terminate the recursive path A definition without a non-recursive part causes infinite recursion This problem is similar to an infinite loop -- with the definition itself causing the infinite “looping” The non-recursive part is called the base case Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Recursion in Math Mathematical formulas are often expressed recursively 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: 1! = 1 N! = N * (N-1)! A factorial is defined in terms of another factorial until the base case of 1! is reached Code\chap17\Factorial.java Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

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 handle both the base case and the recursive case Each call sets up a new execution environment, with new parameters and new local variables As always, when the method completes, control returns to the method that invoked it (which may be another instance of itself) Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Recursive Programming Consider the problem of computing the sum of all the integers between 1 and N, inclusive If N is 5, the sum is This problem can be expressed recursively as: The sum of 1 to N is N plus the sum of 1 to N-1 Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Recursive Programming The sum of the integers between 1 and N: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Recursive Programming A recursive method that computes the sum of 1 to N: public int sum(int num) { int result; if (num == 1) result = 1; //base-case else result = num + sum(num-1); //recursive step return result; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Recursive Programming Tracing the recursive calls of the sum method Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Recursion vs. Iteration 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 The iterative version is easier to understand (in fact there is a formula that computes it without a loop at all) You must be able to determine when recursion is the correct technique to use Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Recursion vs. Iteration Every recursive solution has a corresponding iterative solution A recursive solution may simply be less efficient Furthermore, recursion has the overhead of multiple method invocations However, for some problems recursive solutions are often more simple and elegant to express Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Direct vs. Indirect Recursion A method invoking itself is considered to be direct recursion A method could invoke another method, which invokes another, etc., until eventually the original method is invoked again For example, method m1 could invoke m2, which invokes m3, which invokes m1 again This is called indirect recursion It is often more difficult to trace and debug Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Direct vs. Indirect Recursion Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Maze Traversal We've seen a maze solved using a stack The same approach can also be done using recursion The run-time stack tracking method execution performs the same function As before, we mark a location as "visited" and try to continue along the path The base cases are: – a blocked path – finding a solution Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Maze Traversal Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

import java.util.*; import java.io.*; /** * MazeTester uses recursion to determine if a maze can be traversed. * Java Foundations 4.0 */ public class MazeTester { /** * Creates a new maze, prints its original form, attempts to * solve it, and prints out its final form. */ public static void main(String[] args) throws FileNotFoundException { Scanner scan = new Scanner(System.in); System.out.print("Enter the name of the file containing the maze: "); String filename = scan.nextLine(); Maze labyrinth = new Maze(filename); System.out.println(labyrinth); MazeSolver solver = new MazeSolver(labyrinth); Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

if (solver.traverse(0, 0)) System.out.println("The maze was successfully traversed!"); else System.out.println("There is no possible path."); System.out.println(labyrinth); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

import java.util.*; import java.io.*; /** * Maze represents a maze of characters. The goal is to get from the * top left corner to the bottom right, following a path of 1's. Arbitrary * constants are used to represent locations in the maze that have been TRIED * and that are part of the solution PATH. * Java Foundations 4.0 */ public class Maze { private static final int TRIED = 2; private static final int PATH = 3; private int numberRows, numberColumns; private int[][] grid; Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Constructor for the Maze class. Loads a maze from the given file. * Throws a FileNotFoundException if the given file is not found. * filename the name of the file to load FileNotFoundException if the given file is not found */ public Maze(String filename) throws FileNotFoundException { Scanner scan = new Scanner(new File(filename)); numberRows = scan.nextInt(); numberColumns = scan.nextInt(); grid = new int[numberRows][numberColumns]; for (int i = 0; i < numberRows; i++) for (int j = 0; j < numberColumns; j++) grid[i][j] = scan.nextInt(); } /** * Marks the specified position in the maze as TRIED * row the index of the row to try col the index of the column to try */ public void tryPosition(int row, int col) { grid[row][col] = TRIED; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Return the number of rows in this maze * the number of rows in this maze */ public int getRows() { return grid.length; } /** * Return the number of columns in this maze * the number of columns in this maze */ public int getColumns() { return grid[0].length; } /** * Marks a given position in the maze as part of the PATH * row the index of the row to mark as part of the PATH col the index of the column to mark as part of the PATH */ public void markPath(int row, int col) { grid[row][col] = PATH; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Determines if a specific location is valid. A valid location * is one that is on the grid, is not blocked, and has not been TRIED. * row the row to be checked column the column to be checked true if the location is valid */ public boolean validPosition(int row, int column) { boolean result = false; // check if cell is in the bounds of the matrix if (row >= 0 && row < grid.length && column >= 0 && column < grid[row].length) // check if cell is not blocked and not previously tried if (grid[row][column] == 1) result = true; return result; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Returns the maze as a string. * a string representation of the maze */ public String toString() { String result = "\n"; for (int row=0; row < grid.length; row++) { for (int column=0; column < grid[row].length; column++) result += grid[row][column] + ""; result += "\n"; } return result; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * MazeSolver attempts to recursively traverse a Maze. The goal is to get from the * given starting position to the bottom right, following a path of 1's. Arbitrary * constants are used to represent locations in the maze that have been TRIED * and that are part of the solution PATH. * Java Foundations 4.0 */ public class MazeSolver { private Maze maze; /** * Constructor for the MazeSolver class. */ public MazeSolver(Maze maze) { this.maze = maze; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Attempts to recursively traverse the maze. Inserts special * characters indicating locations that have been TRIED and that * eventually become part of the solution PATH. * row row index of current location column column index of current location true if the maze has been solved */ public boolean traverse(int row, int column) { boolean done = false; if (maze.validPosition(row, column)) { maze.tryPosition(row, column); // mark this cell as tried if (row == maze.getRows()-1 && column == maze.getColumns()-1) done = true; // the maze is solved else { done = traverse(row+1, column); // down if (!done) done = traverse(row, column+1); // right Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

if (!done) done = traverse(row-1, column); // up if (!done) done = traverse(row, column-1); // left } if (done) // this location is part of the final path maze.markPath(row, column); } return done; } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

The Towers of Hanoi The Towers of Hanoi is a puzzle made up of three vertical pegs and several disks that slide onto the pegs The disks are of varying size, initially placed on one peg with the largest disk on the bottom and increasingly smaller disks on top The goal is to move all of the disks from one peg to another following these rules: – Only one disk can be moved at a time – A disk cannot be placed on top of a smaller disk – All disks must be on some peg (except for the one in transit) Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Towers of Hanoi The initial state of the Towers of Hanoi puzzle: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Towers of Hanoi A solution to the three-disk Towers of Hanoi puzzle: Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Towers of Hanoi A solution to ToH can be expressed recursively To move N disks from the original peg to the destination peg: – Move the topmost N-1 disks from the original peg to the extra peg – Move the largest disk from the original peg to the destination peg – Move the N-1 disks from the extra peg to the destination peg The base case occurs when a peg contains only one disk Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Towers of Hanoi The number of moves increases exponentially as the number of disks increases The recursive solution is simple and elegant to express and program, but is very inefficient However, an iterative solution to this problem is much more complex to define and program Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Towers of Hanoi Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * SolveTowers uses recursion to solve the Towers of Hanoi puzzle. * Java Foundations 4.0 */ public class SolveTowers { /** * Creates a TowersOfHanoi puzzle and solves it. */ public static void main(String[] args) { TowersOfHanoi towers = new TowersOfHanoi(4); towers.solve(); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * TowersOfHanoi represents the classic Towers of Hanoi puzzle. * Java Foundations 4.0 */ public class TowersOfHanoi { private int totalDisks; /** * Sets up the puzzle with the specified number of disks. * disks the number of disks */ public TowersOfHanoi(int disks) { totalDisks = disks; } /** * Performs the initial call to moveTower to solve the puzzle. * Moves the disks from tower 1 to tower 3 using tower 2. */ public void solve() { moveTower(totalDisks, 1, 3, 2); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Moves the specified number of disks from one tower to another * by moving a subtower of n-1 disks out of the way, moving one * disk, then moving the subtower back. Base case of 1 disk. * numDisks the number of disks to move start the starting tower end the ending tower temp the temporary tower */ private void moveTower(int numDisks, int start, int end, int temp) { if (numDisks == 1) moveOneDisk(start, end); else { moveTower(numDisks-1, start, temp, end); moveOneDisk(start, end); moveTower(numDisks-1, temp, end, start); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

/** * Prints instructions to move one disk from the specified start * tower to the specified end tower. * start the starting tower end the ending tower */ private void moveOneDisk(int start, int end) { System.out.println("Move one disk from " + start + " to " + end); } Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Analyzing Recursive Algorithms To determine the order of a loop, we determined the order of the body of the loop multiplied by the number of loop executions Similarly, to determine the order of a recursive method, we determine the the order of the body of the method multiplied by the number of times the recursive method is called In our recursive solution to compute the sum of integers from 1 to N, the method is invoked N times and the method itself is O(1) So the order of the overall solution is O(n) Java Foundations, 3rd Edition, Lewis/DePasquale/Chase

Analyzing Recursive Algorithms For the Towers of Hanoi puzzle, the step of moving one disk is O(1) But each call results in calling itself twice more, so for N > 1, the growth function is f(n) = 2 n – 1 This is exponential efficiency: O(2 n ) As the number of disks increases, the number of required moves increases exponentially Java Foundations, 3rd Edition, Lewis/DePasquale/Chase