Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 106 Introduction to Computer Science I 11 / 06 / 2006 Instructor: Michael Eckmann.

Similar presentations


Presentation on theme: "CS 106 Introduction to Computer Science I 11 / 06 / 2006 Instructor: Michael Eckmann."— Presentation transcript:

1 CS 106 Introduction to Computer Science I 11 / 06 / 2006 Instructor: Michael Eckmann

2 Michael Eckmann - Skidmore College - CS 106 - Fall 2006 Today’s Topics Comments and/or Questions? Recursion Exercise to design classes for Card and Deck How Object References work

3 Michael Eckmann - Skidmore College - CS 106 - Fall 2006 meetings to discuss topics Recall the homework --- you are to go over your exam and if you got a question wrong (or partially wrong) try to figure out why. Also do this for questions that you may have gotten correct but aren't fully sure why the answer is correct. Tonight at 8pm in this room I will have a go-over-the-exam / go- over-any-topics-we've-covered discussion. If you can't make it to this session, I want to meet with you personally. Please make an appt. to come see me if you can't make it to my office hours.

4 Factorial method using iteration // non-recursive solution to the factorial problem public int compute_factorial(int num) { int temp_factorial=1; while (num > 0) { temp_factorial = temp_factorial * num; num--; } return temp_factorial; }

5 Factorial method using iteration Let's put this in a program and call it.

6 Recursion Read secion 11.1 in your text for a discussion on recursion and a good example (inWords). I don't recommend the first example (getCount) of section 11.2 though.

7 Recursion A recursive method is a method that calls itself (directly or indirectly.) Recursion is often used when the problem to be solved can be easily implemented with recursion as opposed to an iterative technique. Another fact is though that all problems that can be solved recursively can be solved iteratively. Sometimes though the iterative solution might be very long and require lots of code. In that case recursion might be preferred because it is more readable and easier to write.

8 Recursion Let’s say we know the solution to some case of a problem. If we want to find a solution to a slightly more complex case of the problem, we might be able to use the solution to the easier problem as part of our solution. For example, if we know the factorial of the number 6, to find the factorial of 7, we can just multiply 7 * the factorial of 6, so 7! = 7 * 6!. Here, the solution we know (6! = 720) is used as part of the solution to 7!, which is 7*720 = 5040.

9 Recursion So, more generally, if we know the solution to (n-1)! We can easily find the solution to n! by just multiplying n*(n-1)!. In addition to knowing this though, we need to also know that 1! = 1. This is the simplest factorial. Now, powered with the knowledge that – 1! = 1 and – the fact that given (n-1)!, we can compute n! we have enough information to compute the factorial of any positive integer. Do we all agree?

10 Recursion This is a recursive solution to the factorial problem because –we know how to solve the simplest case (1!) and –we know how to solve a more complex case given a solution to a slightly less complex case n! = n*(n-1)!

11 Factorial method using recursion public int compute_factorial ( int num ) { if ( num <= 1 ) return 1; else return num * compute_factorial ( num - 1) ; } // this recursive method is based on figure 6.12 // in Deitel and Deitel.

12 Factorial method using recursion When the recursive method is called, if the number passed in as an argument is less than or equal to 1, then 1 is returned and the method ends. That is known as the base case. If the number passed in as an argument is greater than 1, then the else portion of the method is executed. This says to return that number times the result of another call to the method with the argument of one less than the original value. The else portion in this method is known as the recursion step.

13 Factorial method using recursion Let’s examine what happens when the number 2 is passed in as an argument to compute_factorial. int fact_value; fact_value = compute_factorial( 2 ); The method would check if 2 <= 1 and since that is false, the else portion would execute. The else portion calls compute_factorial(1). This second call to the method invokes another “copy” of the method. This second call checks if 1 <= 1 and this is true so it returns 1.

14 Factorial method using recursion This value of 1 gets returned to the most recent call (and hence the second call to the method ends its execution.) This value of 1 gets multiplied by 2. This happens in the else portion of the method. The result, 2, gets returned to the original call of the method (and hence the first call to the method ends its execution.) If compute_factorial was called with the number 3 as an argument, the method would end up being called three times.

15 Recursion When the method is recursively called in the else portion, the prior call to the method has not finished executing. It is waiting on the result of this new method call. There will be multiple active copies of the recursive method when the else portion executes. The recursion ends when the base case is finally met. The base case then returns a result to the previous call of the method and a sequence of returns occurs until the original method call gets its returned value.

16 Factorial method using recursion Let’s look at a program that will illustrate, through print statements, what happens in what order when a method is called recursively.

17 Recursion We may come back to recursion in other problems later in the semester. Understand that the Factorial example, was for instructional purposes only, since it is a very simple example of recursion. For the factorial method, in practice, we would always prefer the non-recursive (iterative) solution. It is more efficient in terms of both time and space. Recursive solutions often take more time to run, because making a method call is slower and requires more memory than doing the same statements without a method call.

18 Recursion Direct vs. indirect recursion – When a method calls itself, it is direct recursion – When method1 calls method2 and method2 calls method1, it is indirect. – There can be more than just two methods involved in the indirection.

19 Towers of Hanoi Three pegs Start with different size discs on first peg Move them all to the third peg using the following rules – Move only one disc at a time – Can't place a larger disc on a smaller disc – All discs must be on some peg except for the disc in transit between pegs Let's see an applet on the web.

20 Towers of Hanoi Do a solution with 3 discs. Do a solution with 4 discs. See any patterns emerging? Is it recursive?

21 Towers of Hanoi To move N discs from first peg to third – Move topmost N-1 discs from first peg to second – Move the largest disc from the first peg to third – Move the N-1 discs from the second peg to the third

22 Towers of Hanoi During the solution, each peg takes on a role – Either the start peg, end peg, or intermediate peg. – Notice: In the first and third parts, notice that they are the same as the whole, with the roles of the pegs changing. First part: – Move from: first peg (start) – To: second peg (end) – Using as intermediate: third peg (intermediate) Third part: – Move from: second peg (start) – To: third peg (end) – Using as intermediate: first peg (intermediate)

23 Towers of Hanoi void moveTower(int numDiscs, int start, int end, int intermed) { if (numDiscs == 1) moveOneDisc(start, end); else { moveTower(numDiscs – 1, start, intermed, end); moveOneDisc(start, end); moveTower(numDiscs – 1, intermed, end, start); } void moveOneDisc(int p1, int p2) { System.out.println(“Move the disc from peg “ + p1 + “ to peg “ + p2); }

24 Towers of Hanoi Let's put this in a program and run it. Does anyone think that an iterative solution would be possible? If so, do you think it'll be easier? You can think about this on your own if you wish and try to come up with an iterative (that is, non-recursive) solution.

25 User defined types to represent a Card and a Deck Let's create a class to represent a Card and one to represent a Deck. There are a variety of choices one can make about how to do this. I'll ask for suggestions and make decisions about how we'll implement these. Note that nothing game specific is desired to be in the classes.

26 Card/Deck implementation Purpose of these classes will be to create a general Card class and general Deck class that could be used for an arbitrary card game. What data describes a Card? What data describes a Deck? What behaviors does a Card exhibit? What behaviors does a Deck exhibit?

27 Card/Deck implementation What data describes a Card? – Value and suit (types for these?) What data describes a Deck? – An ordered group of some fixed number of cards What behaviors does a Card exhibit? – None really independent of a Deck What behaviors does a Deck exhibit? – Can shuffle it – Can cut it – Can deal a card from it

28 Card/Deck implementation Ideas for the deal method – in Deck, maintain a "top of Deck" index. – when deal is called, return the Card at that index and increment the "top of Deck" index. – In this way, we won't have to actually remove Cards from the Deck, we'll just keep track of "top of Deck" and if this index ever gets to the last valid index, then we are at the last Card in the Deck.

29 Shuffle method Ideas for the shuffle method – try to simulate human shuffling – or just swap 2 cards a bunch of times to get a mixed deck – or other ideas?

30 Cut method Ideas for the cut method Have another array of 52 Cards to copy into, then copy this array back into original. Generate some random number between 0 and 51 and use that as the place to cut the cards. Keeping track of starting and ending indicies is a challenge but its doable if we're careful. Draw copying idea on board. – How many loops and what will each one do?

31 Michael Eckmann - Skidmore College - CS 106 - Fall 2006 Object References When we declare an object to be of some Class type, we are declaring a REFERENCE to an object of that class. The reference stores the “memory address” of where the actual data for the object is stored. e.g –String s = “Mike”; –// s is the name of the reference to a String. –// The value in s is a memory address –// that memory address is where to find “Mike”

32 Michael Eckmann - Skidmore College - CS 106 - Fall 2006 Object References When we assign one object reference to another –the references both contain the same memory address A main implication is that changing one object's values will affect the other. Card c1 = new Card(1, 1); // Ace of Clubs Card c2; c2 = c1; c1.changeCard(2, 2); // 2 of Diamonds // since c1 and c2 both reference the SAME memory // address, changing one's values changes the others // because c1 and c2 are different names for the same memory

33 Michael Eckmann - Skidmore College - CS 106 - Fall 2006 Object References All variables passed into methods have a local copy of them made each time the method executes. –Primitive type variables When variables of primitive types are passed into a method the value that is copied is the actual value of the data in the variable –Object References (and array references) When we pass an object reference to a method the value that is copied is the memory address, NOT the contents at that memory address.

34 Michael Eckmann - Skidmore College - CS 106 - Fall 2006 Passing primitives Example with primitives: public static void meth1(int parm) { parm++; System.out.println(“value = “ + parm); } // Then in main method a call to it might be like: int x = 5; meth1(x); // parm has the value 5 copied into it when meth1 is called // meth1 works on that copy, so x's value isn't altered in meth1

35 Michael Eckmann - Skidmore College - CS 106 - Fall 2006 Passing References Example with arrays: public static void meth2(int parm[]) { parm[0] = 4; System.out.println(“value = “ + parm[0]); } // Then in main method a call to it might be like: int x[] = { 3, 1, 2, 5 }; meth2(x); // Array names like x here are references, parm gets a copy of // the memory address of x. meth2 works on that address, so x's // array values are altered in meth2

36 Michael Eckmann - Skidmore College - CS 106 - Fall 2006 Passing References Example with object references: public static void meth3(Card parm) { parm.changeCard(11, 1); // Jack of Clubs } // Then in main method a call to it might be like: Card acard = new Card(1, 1); // Ace of Clubs meth3(acard); // Object names like acard are references, parm gets a copy of // the memory address of acard. meth1 works on that address, so // acard's object values are altered in meth3


Download ppt "CS 106 Introduction to Computer Science I 11 / 06 / 2006 Instructor: Michael Eckmann."

Similar presentations


Ads by Google