1 / 9

CPSC 233 Tutorial

CPSC 233 Tutorial. Xin Mar 7, 2011. A trap in Asgn 4. Each element of the grid is a reference to ForestItem , not a character Different from the example program Define class ForestItem , and used it in the grid!!!. Recursion. The concept Call itself inside a function Components

reid
Download Presentation

CPSC 233 Tutorial

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CPSC 233 Tutorial Xin Mar 7, 2011

  2. A trap in Asgn 4 • Each element of the grid is a reference to ForestItem, not a character • Different from the example program • Define class ForestItem, and used it in the grid!!!

  3. Recursion • The concept • Call itself inside a function • Components • A method definition • Call itself inside the method with a smaller-scaled argument • An ending condition int sum (intarg) { if (arg > 0) return sum (arg – 1) + arg; else return 0; }

  4. What’s good? • Logically simple program (for certain problems) • What’s bad? • Hard to understand for new learners • Spend some time to feel comfortable with it • Believe the function works • Don’t confuse yourself by expanding the recursion • memory consuming

  5. Example 1 -- SUM public class sum { intsumup(intn) { if (n > 0) return sumup (n - 1) + n; else return 0; } } public class sum_driver { public static void main (String args []) { sum aSum = new sum(); intn = 10; System.out.println("the sum from 0 to " + n + " is " + aSum.sumup(n)); } }

  6. Example 2 – Fibonacci number • Definition • F (n) = F (n - 1) + F (n – 2) • F (0) = 0; F(1) = 1;

  7. Example 2 -- code public class fibonacci { int fib (intn) { if (n < 0) { System.out.println ("n must be non-negative"); return 0; } else if (n == 0) return 0; else if (n == 1) return 1; else return fib ( n - 1) + fib (n - 2); } } public class fibonacci_driver { public static void main (String args []) { fibonacciaFib = new fibonacci(); intn = 10; System.out.println ("fibonacci(" + n + ") is " + aFib.fib(n)); } }

  8. Maze Solver • The idea: • Try an immediate neighbor • Accessible in one step • Is there a way from that neighbor to the EXIT? • Call recursively

  9. Improve grid programMove the party n = (dy + 1) * 3 + (dx + 1) dx = (n – 1) % 3 - 1 dy = (n – 1) / 3 - 1

More Related