CSC-140 Assignment 4

Size: px
Start display at page:

Download "CSC-140 Assignment 4"

Transcription

1 CSC-140 Assignment 4 Please do not Google a solution to these problem, cause that won t teach you anything about programming - the only way to get good at it, and understand it, is to do it! 1 Introduction This assignment deals with 3 major topics. Method invocation (writing your own methods), using static fields (think of these as global variables that all methods can see and use), and recursive methods (method calling itself.) 1.1 Recursive Exponential Function Remember you wrote a for loop to compute x y. We will start by implementing that same method again, but in a recursive fashion. Consider the following definition of the exponential function - let us call it f: { 1 if x = 0 f(x, y) = x f(x, y 1) otherwise With this definition, we can implement a Java method f with the following header: public static int f ( int x, int y ) { // do what f does above. Question 1: Implement this function, and test it with a few calls to make sure it works correctly. What happens if you give it a negative value for y? Would it also work if you changed the value of x and the return type to double? 1

2 1.2 Fibonacci Numbers Next, let us look at the well known Fibonacci number sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,... This is a sequence that comes up all over many different branches of science. It is used in biology as well as math; most famously perhaps it relates to the golden ratio (φ) in the way that the limit of the ratio of two consecutive Fibonacci numbers approaches the golden ratio. Let us formally define the n th Fibonacci number as follows: 0 if n = 0; F ib(n) = 1 if n = 1; F ib(n 1) + F ib(n 2) otherwise We see that F ib(2) can be calculated by calculating F ib(1) and F ib(0) and then adding them together: or F ib(2) = F ib(1) + F ib(0) = = 1 F ib(3) = F ib(2) + F ib(1) = F ib(2) + 1 = F ib(1) + F ib(0) + 1 = = 2 Question 2: Using recursion, and the following Java method header, implement a Java method that can calculate the n th Fibonacci number (remember, the 0 th number is 0): public static long f i b ( int n) { // your code here (We use long variables, because the result gets big fast!) If we want to count the number of additions in the fib method, we can add a global variable that can be accessed both from the fib method and from the main method. Let us add such a global variable (in reality called a static field ), by placing the following declaration above (or below; where doesn t matter as long as it is not inside a method) the fib method: 2

3 public static int f i b c o u n t = 0 ; We initialize it to 0, but if we call fib more than once in the main method, you must remember to reset it back to 0; naturally, this is because it is global and only gets initialized once, namely when the entire program starts, so be careful about using such variables. We can increment this counter every time we do an addition in the fib code, and then print it out in the main method. Question 3: Add this to your code and check that it works. Here are a few examples from my code for you to check your output against: fib(1) = 1 and took 0 additions to compute. fib(2) = 1 and took 1 additions to compute. fib(10) = 55 and took 88 additions to compute. fib(25) = and took additions to compute. Question 4: Can your code compute f ib(100), or f ib(1000)? My guess is that you probably get tired of waiting at best. f ib(100) = Recursion is simple, and easy, but not always the fastest way of doing things; the main reason as you can see is the sheer amount of additions it takes to compute a large Fibonacci number. With the recursion in the method you implemented, we work our way backwards in the sequence, but if you were to compute it by hand you would work your way forwards. You would start by adding 0 and 1 and get 1, then add 1 and 1 and get 2, then add 1 and 2 and get 3, then add 2 and 3 and get 5 and so on. This looks very much like a for loop, and it can indeed be implemented much more efficiently with a for loop. Question 5: Implement f ibf ast with the following header: public static void f a s t F i b ( int n) { // your code here that uses a for loop and some if statements (you may not call any other 3

4 methods) to compute the same numbers as fib. Test your code and shows that it works. Can you compute fibf ast(100)? Add a new counter to your code to count the number of additions for fibf ast. What would the count be for fibf ast(1000)? (I don t think you can calculate that number, it is way too big to fit in a long variable it has 209 digits and is 26,863,810,024,485,359,386,146,727,202,142,923,967,616,609,318,986,952,340, 123,175,997,617,981,700,247,881,689,338,369,654,483,356,564,191,827,856, 161,443,356,312,976,673,642,210,350,324,634,850,410,377,680,367,334,151, 172,899,169,723,197,082,763,985,615,764,450,078,474,174,626 ;-) Recall the definition of the golden ration (φ): fib(n) φ = lim n > fib(n 1) Naturally, we cannot compute an infinite limit like that, but we can approximate it; the best value we can get to is One approach is to write a do loop that keeps running until the difference between two consecutive approximations of φ is less than some small number ɛ, that is: fib(i) fib(i 1) fib(i 1) fib(i 2) < ɛ When comparing such small differences, it is always a good idea to use absolute values ( ). You can calculate the absolute value of a number by using Math.abs(). Question 6: Implement a method called goldenratio that takes in a and returns a double, and has a do loop that calculates an estimate of φ, try with different ɛ values. Also try with ɛ = How many iterations did that take? (mine took 43) Remember, to be able to compute fib(n 2) you need to start your counter a at least 2. Remember a long divided by a long is a long, so make sure you convert your longs to doubles before dividing. Also, use fastfib rather than fib. 4

5 1.3 Towers of Hanoi Remember this game: The objective is to move all the discs from peg 1 to peg 3 using peg 2. The rules are simple: You cannot place a larger disc on top of a smaller one. The puzzle was invented by the French mathematician douard Lucas in There is a legend about an Indian temple which contains a large room with three time-worn posts in it surrounded by 64 golden disks. Brahmin priests, acting out the command of an ancient prophecy, have been moving these disks, in accordance with the rules of the puzzle, since that time. (from Wikipedia; its ok for me to quote Wikipedia in an assignment, but you cannot ever do so in a serious publication!) You are to write a Java method called move that produces the following output (here run with just 4 discs): Move a disk from peg 3 to peg 2 5

6 Move a disk from peg 2 to peg 1 This might seem like a complicated piece of code, but using recursion, it is super simple. Consider how we can break the task into smaller tasks (we call that divide-and-conquer). To move 4 discs from peg 1 to peg 3 we can do the following: 1. Move 3 discs from peg 1 to peg 2 (via peg 3 if necessary). 2. Move 1 disc from peg 1 to peg Move 3 discs on peg 2 to peg 3 (via peg 1 if necessary). A recursive procedure must always be able to solve some of the problems directly without calling itself again, we call that the base case. For the exponential function, the base case was when y = 0, and we knew the result to be 1. For the Towers of Hanoi, the base case is when we have to move just one disc. We can do that directly by moving it from the peg on which it is, onto the peg to which it is going. Another important thing about recursion is that you should always call the recursive procedure with a smaller problem than what you are trying to solve; else the recursion never ends! Look at the 3 steps above. The middle one is the base case and the two others are recursive calls (they solve a simpler/smaller problem). We can use the following Java header: public static void move( int n, int from, int to, int via ) { i f (n == 1) // p r i n t out the move else // your code f o r the r e c u r s i v e c a l l here and it can be called as follows (to move the 4 discs from peg 1 to peg 3 via peg 2): move(4, 1, 3, 2). Look at the output again: 6

7 Move a disk from peg 3 to peg 2 <---- Move a disk from peg 2 to peg 1 The arrow point to the move of the largest disc directly from peg 1 to peg 3; the output before and after represent the output of the two recursive calls. Also note, if you made the original call with 3 discs: move(3, 1, 2, 3), that is, move 3 discs from peg 1 to peg 2 via peg 3, you would get the output you see before the arrow. The output after the arrow corresponds to the call move(3, 2, 3, 1). Cool, huh? Hint, the recursive case will have 3 calls; one to move n 1, then 1 and then n 1 again. Question 7: Implement the move method. An alternative implementation is as follows: do nothing if n = 0, but the middle case in the else part of that if statement does the printing. This solution is a little more efficient. Question 8: Test your code with different values to make sure it works. What is the maximum number your code works for? (The answer here probably depends on how much patience you have) 7

8 Question 9: Now, add another counter to your class. Remember to initialize it to 0 every time you call move (from the main method - not from within the move method itself!) Increment this counter every time you print a move, and after the call to move (from main) print out the number of moves made. If the monks can move one disc a second, how many years does it take to move all 64 discs? You can t run your code, cause you don t have that much time to wait, but if you look at it you probably come up with the following idea: to move n discs I have to move n 1 twice plus the one at the bottom, so if we make a function to count we get: T C(n) = 2 T C(n 1) + 1; Question 10: Implement a recursive Java method towercount that has the following header: public static long towercount ( int n) { // your code here Use this method to produce the following output: Moving 3 towers takes 7; that would take 0 years. Moving 4 towers takes 15; that would take 0 years. Moving 5 towers takes 31; that would take 0 years. Moving 6 towers takes 63; that would take 0 years. Moving 7 towers takes 127; that would take 0 years. Moving 8 towers takes 255; that would take 0 years. Moving 9 towers takes 511; that would take 0 years. Moving 10 towers takes 1023; that would take 0 years. Moving 11 towers takes 2047; that would take 0 years. Moving 12 towers takes 4095; that would take 0 years. Moving 13 towers takes 8191; that would take 0 years. Moving 14 towers takes 16383; that would take 0 years. Moving 15 towers takes 32767; that would take 0 years. Moving 16 towers takes 65535; that would take 0 years. Moving 17 towers takes ; that would take 0 years. Moving 18 towers takes ; that would take 0 years. Moving 19 towers takes ; that would take 0 years. Moving 20 towers takes ; that would take 0 years. 8

9 Moving 21 towers takes ; that would take 0 years. Moving 22 towers takes ; that would take 0 years. Moving 23 towers takes ; that would take 0 years. Moving 24 towers takes ; that would take 0 years. Moving 25 towers takes ; that would take 1 years. Moving 26 towers takes ; that would take 2 years. Moving 27 towers takes ; that would take 4 years.... Moving 63 towers takes... Moving 64 towers takes... the... represent output that I have redacted. I want you to compute the right value. Remember a year is 60*60*24*365 seconds. Question 11: What value do you get for 63? What about 64? Explain! (You ll see what I mean when you see the output!) 1.4 Fibonacci - Again! You probably realized that your fib code is much nicer than than your fastf ib code. Take a look at this implementation: public static long t a i l F i b ( int n, long acc1, long acc2 ) { i f (n == 0) return acc1 ; else i f (n == 1) return acc2 ; else { return t a i l F i b (n 1, acc2, acc1 + acc2 ) ; A call to fib with the value n is the same as a call to tailf ib with the values n, 0 and 1. So fib(n) = tailf ib(n, 0, 1). Question 12: Type the code in and try it. Explain how it works and related it to your own fastf ib code. 9

10 2 Topics Covered Methods. Recursion. Static fields (global variables.) 3 Work List 1. Make sure you read the Topics Covered section and familiarize yourself with all the topics. 2. Create a file Assignment4.java, and implement the code from the questions above. 3. Test your program with a number of different values. 4. Once you are happy with your solution, go to csgfms.cs.unlv.edu and hand it in. Just the.java file! 5. Bring to class (along with the printout of your solution) a write up in which you explain how you solved the problem, and show output from a couple of tests; enough to convince me that it works. 4 Due Date The Assignment4.java file must be uploaded to csgfms.cs.unlv.edu no later than Monday March 7th before midnight (midnight between Monday and Tuesday), and the write up should be brought to class the day after. 10

11 5 Sample Output from my Solution QUESTION 1: f(3,4) = 81 f(2,0) = 1 f(2,25) = QUESTION 2 & 3: fib(1) = 1 and took 0 additions to compute. fib(2) = 1 and took 1 additions to compute. fib(10) = 55 and took 88 additions to compute. fib(25) = and took additions to compute. QUESTION 5: fastfib(100) = and took 99 additions to compute. QUESTION 6: It took 43 iterations to compute phi, which is QUESTION 7 & 9: Move a disk from peg 3 to peg 2 Move a disk from peg 2 to peg 1 It took 15 moves for 4 discs. 11

12 Move a disk from peg 3 to peg 2... It took 1023 moves for 10 discs. QUESTION 10: Moving 3 towers takes 7 moves; that would take 0 years. Moving 4 towers takes 15 moves; that would take 0 years. Moving 5 towers takes 31 moves; that would take 0 years. Moving 6 towers takes 63 moves; that would take 0 years. Moving 7 towers takes 127 moves; that would take 0 years. Moving 8 towers takes 255 moves; that would take 0 years. Moving 9 towers takes 511 moves; that would take 0 years.... Moving 63 towers takes... Moving 64 towers takes... QUESTION 11: tailfib(0,0,1) = 0 tailfib(1,0,1) = 1 tailfib(2,0,1) = 1 tailfib(10,0,1) = 55 tailfib(100,0,1) = Again, the output in questions 7, 9, and 10 have been shortened a little (else this handout would be 30 pages long!) 12

CSC-140 Assignment 5

CSC-140 Assignment 5 CSC-140 Assignment 5 Please do not Google a solution to these problems, cause that won t teach you anything about programming - the only way to get good at it, and understand it, is to do it! 1 Introduction

More information

APCS-AB: Java. Recursion in Java December 12, week14 1

APCS-AB: Java. Recursion in Java December 12, week14 1 APCS-AB: Java Recursion in Java December 12, 2005 week14 1 Check point Double Linked List - extra project grade Must turn in today MBCS - Chapter 1 Installation Exercises Analysis Questions week14 2 Scheme

More information

def F a c t o r i a l ( n ) : i f n == 1 : return 1 else : return n F a c t o r i a l ( n 1) def main ( ) : print ( F a c t o r i a l ( 4 ) )

def F a c t o r i a l ( n ) : i f n == 1 : return 1 else : return n F a c t o r i a l ( n 1) def main ( ) : print ( F a c t o r i a l ( 4 ) ) 116 4.5 Recursion One of the most powerful programming techniques involves a function calling itself; this is called recursion. It is not immediately obvious that this is useful; take that on faith for

More information

mith College Computer Science Week 13 CSC111 Spring 2018 Dominique Thiébaut

mith College Computer Science Week 13 CSC111 Spring 2018 Dominique Thiébaut mith College Computer Science Week 13 CSC111 Spring 2018 Dominique Thiébaut dthiebaut@smith.edu Recursion Continued Visiting a Maze Start Exit How do we represent a maze in Python? mazetext = """ #########################...#

More information

Recursive Definitions

Recursive Definitions Recursion Objectives Explain the underlying concepts of recursion Examine recursive methods and unravel their processing steps Explain when recursion should and should not be used Demonstrate the use of

More information

Recursion. Dr. Jürgen Eckerle FS Recursive Functions

Recursion. Dr. Jürgen Eckerle FS Recursive Functions Recursion Dr. Jürgen Eckerle FS 2008 Recursive Functions Recursion, in mathematics and computer science, is a method of defining functions in which the function being defined is applied within its own

More information

Recursion. Jordi Cortadella Department of Computer Science

Recursion. Jordi Cortadella Department of Computer Science Recursion Jordi Cortadella Department of Computer Science Recursion Introduction to Programming Dept. CS, UPC 2 Principle: Reduce a complex problem into a simpler instance of the same problem Recursion

More information

Recursion (Rosen, 6 th edition, Section 4.3, 4.4)

Recursion (Rosen, 6 th edition, Section 4.3, 4.4) Recursion (Rosen, 6 th edition, Section 4.3, 4.4) Carol Zander For recursion, the focus is mostly on recursive algorithms. While recursive definitions will sometimes be used in definitions (you already

More information

Hanoi, Counting and Sierpinski s triangle Infinite complexity in finite area

Hanoi, Counting and Sierpinski s triangle Infinite complexity in finite area Hanoi, Counting and Sierpinski s triangle Infinite complexity in finite area Math Circle December 5, 2017 1. Per usual we are going to be watching a video today, but we aren t going to be watching it right

More information

UNIT 5A Recursion: Basics. Recursion

UNIT 5A Recursion: Basics. Recursion UNIT 5A Recursion: Basics 1 Recursion A recursive operation is an operation that is defined in terms of itself. Sierpinski's Gasket http://fusionanomaly.net/recursion.jpg 2 1 Recursive Definitions Every

More information

Summary. csci 210: Data Structures Recursion. Recursive algorithms. Recursion. Topics READING:

Summary. csci 210: Data Structures Recursion. Recursive algorithms. Recursion. Topics READING: Summary csci 210: Data Structures Recursion Topics recursion overview simple eamples Sierpinski gasket counting blobs in a grid Hanoi towers READING: LC tetbook chapter 7 Recursion Recursive algorithms

More information

csci 210: Data Structures Recursion

csci 210: Data Structures Recursion csci 210: Data Structures Recursion Summary Topics recursion overview simple eamples Sierpinski gasket counting blobs in a grid Hanoi towers READING: LC tetbook chapter 7 Recursion A method of defining

More information

UNIT 5A Recursion: Basics. Recursion

UNIT 5A Recursion: Basics. Recursion UNIT 5A Recursion: Basics 1 Recursion A recursive function is one that calls itself. Infinite loop? Not necessarily. 2 1 Recursive Definitions Every recursive definition includes two parts: Base case (non

More information

CSC 8301 Design and Analysis of Algorithms: Recursive Analysis

CSC 8301 Design and Analysis of Algorithms: Recursive Analysis CSC 8301 Design and Analysis of Algorithms: Recursive Analysis Professor Henry Carter Fall 2016 Housekeeping Quiz #1 New TA office hours: Tuesday 1-3 2 General Analysis Procedure Select a parameter for

More information

Outline. Simple Recursive Examples Analyzing Recursion Sorting The Tower of Hanoi Divide-and-conquer Approach In-Class Work. 1 Chapter 6: Recursion

Outline. Simple Recursive Examples Analyzing Recursion Sorting The Tower of Hanoi Divide-and-conquer Approach In-Class Work. 1 Chapter 6: Recursion Outline 1 A Function Can Call Itself A recursive definition of a function is one which makes a function call to the function being defined. The function call is then a recursive function call. A definition

More information

CSC-140 Assignment 6

CSC-140 Assignment 6 CSC-140 Assignment 6 1 Introduction In this assignment we will start out defining our own classes. For now, we will design a class that represents a date, e.g., Tuesday, March 15, 2011, or in short hand

More information

Recursive Methods and Problem Solving. Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms

Recursive Methods and Problem Solving. Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Recursive Methods and Problem Solving Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Review: Calling Methods int x(int n) { int m = 0; n = n + m + 1; return n; int y(int

More information

Algorithmic Methods Tricks of the Trade

Algorithmic Methods Tricks of the Trade Algorithmic Methods Tricks of the Trade 5A Recursion 15-105 Principles of Computation, Carnegie Mellon University - CORTINA 1 Recursion A recursive operation is an operation that is defined in terms of

More information

Recursion. Let s start by looking at some problems that are nicely solved using recursion. First, let s look at generating The Fibonacci series.

Recursion. Let s start by looking at some problems that are nicely solved using recursion. First, let s look at generating The Fibonacci series. Recursion The programs we have discussed so far have been primarily iterative and procedural. Code calls other methods in a hierarchical manner. For some problems, it is very useful to have the methods

More information

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion CSC 148 Lecture 3 Dynamic Typing, Scoping, and Namespaces Recursion Announcements Python Ramp Up Session Monday June 1st, 1 5pm. BA3195 This will be a more detailed introduction to the Python language

More information

Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson

Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson Lecture Notes 4 More C++ and recursion CSS 501 Data Structures and Object-Oriented Programming Professor Clark F. Olson Reading for this lecture: Carrano, Chapter 2 Copy constructor, destructor, operator=

More information

Algorithm. Building blocks of algorithm

Algorithm. Building blocks of algorithm UNIT I ALGORITHMIC PROBLEM SOLVING 9 Algorithms, building blocks of algorithms (statements, state, control flow, functions), notation (pseudo code, flow chart, programming language), algorithmic problem

More information

# track total function calls using a global variable global fibcallcounter fibcallcounter +=1

# track total function calls using a global variable global fibcallcounter fibcallcounter +=1 Math 4242 Fibonacci, Memoization lecture 13 Today we talk about a problem that sometimes occurs when using recursion, and a common way to fix it. Recall the Fibonacci sequence (F 0, F 1, F 2,...) that

More information

Taking Stock. IE170: Algorithms in Systems Engineering: Lecture 5. The Towers of Hanoi. Divide and Conquer

Taking Stock. IE170: Algorithms in Systems Engineering: Lecture 5. The Towers of Hanoi. Divide and Conquer Taking Stock IE170: Algorithms in Systems Engineering: Lecture 5 Jeff Linderoth Department of Industrial and Systems Engineering Lehigh University January 24, 2007 Last Time In-Place, Out-of-Place Count

More information

Recursion Chapter 3.5

Recursion Chapter 3.5 Recursion Chapter 3.5-1 - Outline Induction Linear recursion Example 1: Factorials Example 2: Powers Example 3: Reversing an array Binary recursion Example 1: The Fibonacci sequence Example 2: The Tower

More information

Lecture 24 Tao Wang 1

Lecture 24 Tao Wang 1 Lecture 24 Tao Wang 1 Objectives Introduction of recursion How recursion works How recursion ends Infinite recursion Recursion vs. Iteration Recursion that Returns a Value Edition 2 Introduction If we

More information

Chapter 10: Recursive Problem Solving

Chapter 10: Recursive Problem Solving 2400 COMPUTER PROGRAMMING FOR INTERNATIONAL ENGINEERS Chapter 0: Recursive Problem Solving Objectives Students should Be able to explain the concept of recursive definition Be able to use recursion in

More information

Recursion. Chapter 7. Copyright 2012 by Pearson Education, Inc. All rights reserved

Recursion. Chapter 7. Copyright 2012 by Pearson Education, Inc. All rights reserved Recursion Chapter 7 Contents What Is Recursion? Tracing a Recursive Method Recursive Methods That Return a Value Recursively Processing an Array Recursively Processing a Linked Chain The Time Efficiency

More information

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Module 02 Lecture - 45 Memoization

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Module 02 Lecture - 45 Memoization Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute Module 02 Lecture - 45 Memoization Let us continue our discussion of inductive definitions. (Refer Slide Time: 00:05)

More information

Reading 8 : Recursion

Reading 8 : Recursion CS/Math 40: Introduction to Discrete Mathematics Fall 015 Instructors: Beck Hasti, Gautam Prakriya Reading 8 : Recursion 8.1 Recursion Recursion in computer science and mathematics refers to the idea of

More information

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur Functions CS10001: Programming & Data Structures Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur 1 Recursion A process by which a function calls itself

More information

ECE 2400 Computer Systems Programming Fall 2018 Topic 2: C Recursion

ECE 2400 Computer Systems Programming Fall 2018 Topic 2: C Recursion ECE 2400 Computer Systems Programming Fall 2018 Topic 2: C Recursion School of Electrical and Computer Engineering Cornell University revision: 2018-09-13-21-07 1 Dictionary Analogy 2 2 Computing Factorial

More information

26 How Many Times Must a White Dove Sail...

26 How Many Times Must a White Dove Sail... Lecture 26 c 2005 Felleisen, Proulx, et. al. 26 How Many Times Must a White Dove Sail... From Here to Eternity According to an old legend the priests in the Temple of Brahma got the task of measuring the

More information

recursive algorithms 1

recursive algorithms 1 COMP 250 Lecture 11 recursive algorithms 1 Oct. 2, 2017 1 Example 1: Factorial (iterative)! = 1 2 3 1 factorial( n ){ // assume n >= 1 result = 1 for (k = 2; k

More information

Assignment #1 Simple C++

Assignment #1 Simple C++ Eric Roberts Handout #5 CS 106B January 7, 2015 Assignment #1 Simple C++ Due: Friday, January 16 Part 1. Get Qt Creator working Parts of this handout were written by Julie Zelenski. Your first task is

More information

Practice Problems for the Final

Practice Problems for the Final ECE-250 Algorithms and Data Structures (Winter 2012) Practice Problems for the Final Disclaimer: Please do keep in mind that this problem set does not reflect the exact topics or the fractions of each

More information

CS221: Algorithms and Data Structures Lecture #11 Recursion vs. Iteration Proofs about Recursion/Iteration

CS221: Algorithms and Data Structures Lecture #11 Recursion vs. Iteration Proofs about Recursion/Iteration CS221: Algorithms and Data Structures Lecture #11 Recursion vs. Iteration Proofs about Recursion/Iteration Alan J. Hu (Borrowing slides from Steve Wolfman) 1 Programming Project #1 First Milestone due

More information

COMP 250 Fall Recursive algorithms 1 Oct. 2, 2017

COMP 250 Fall Recursive algorithms 1 Oct. 2, 2017 Recursion Recursion is a technique for solving problems in which the solution to the problem of size n is based on solutions to versions of the problem of size smaller than n. Many problems can be solved

More information

Recursive Algorithms II

Recursive Algorithms II Recursive Algorithms II Margaret M. Fleck 23 October 2009 This lecture wraps up our discussion of algorithm analysis (section 4.4 and 7.1 of Rosen). 1 Recap Last lecture, we started talking about mergesort,

More information

Resources matter. Orders of Growth of Processes. R(n)= (n 2 ) Orders of growth of processes. Partial trace for (ifact 4) Partial trace for (fact 4)

Resources matter. Orders of Growth of Processes. R(n)= (n 2 ) Orders of growth of processes. Partial trace for (ifact 4) Partial trace for (fact 4) Orders of Growth of Processes Today s topics Resources used by a program to solve a problem of size n Time Space Define order of growth Visualizing resources utilization using our model of evaluation Relating

More information

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling Recursion Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling With reference to the call stack Compute the result of simple recursive algorithms Understand

More information

6.00 Notes On Big-O Notation

6.00 Notes On Big-O Notation 6.00 Notes On Big-O Notation April 13, 2011 Sarina Canelake See also http://en.wikipedia.org/wiki/big O notation We use big-o notation in the analysis of algorithms to describe an algorithm s usage of

More information

COMP-202. Recursion. COMP Recursion, 2013 Jörg Kienzle and others

COMP-202. Recursion. COMP Recursion, 2013 Jörg Kienzle and others COMP-202 Recursion Recursion Recursive Definitions Run-time Stacks Recursive Programming Recursion vs. Iteration Indirect Recursion Lecture Outline 2 Recursive Definitions (1) A recursive definition is

More information

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch

CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch CSCI 1100L: Topics in Computing Lab Lab 11: Programming with Scratch Purpose: We will take a look at programming this week using a language called Scratch. Scratch is a programming language that was developed

More information

CS1 Lecture 15 Feb. 19, 2018

CS1 Lecture 15 Feb. 19, 2018 CS1 Lecture 15 Feb. 19, 2018 HW4 due Wed. 2/21, 5pm (changed from original 9am so people in Wed. disc. sections can get help) Q2: find *any* solution. Don t try to find the best/optimal solution or all

More information

Clicker Question What will this print? def blah(x): return x+1 def main(): z = blah(3) print(z) main() A) 3 B) 4 C) 5 D) It causes an error

Clicker Question What will this print? def blah(x): return x+1 def main(): z = blah(3) print(z) main() A) 3 B) 4 C) 5 D) It causes an error Recursion Clicker Question What will this print? def blah(x): return x+1 def main(): z = blah(3) print(z) main() A) 3 B) 4 C) 5 D) It causes an error So how about this? def foo(s): if len(s) == 1: return

More information

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015 COMP-202: Foundations of Programming Lecture 13: Recursion Sandeep Manjanna, Summer 2015 Announcements Final exams : 26 th of June (2pm to 5pm) @ MAASS 112 Assignment 4 is posted and Due on 29 th of June

More information

Data Structures And Algorithms

Data Structures And Algorithms Data Structures And Algorithms Recursion Eng. Anis Nazer First Semester 2016-2017 Recursion Recursion: to define something in terms of itself Example: factorial n!={ 1 n=0 n (n 1)! n>0 Recursion Example:

More information

Chapter 15: Recursion

Chapter 15: Recursion Chapter 15: Recursion Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 15 discusses the following main topics: Introduction to Recursion

More information

CSE 2123 Recursion. Jeremy Morris

CSE 2123 Recursion. Jeremy Morris CSE 2123 Recursion Jeremy Morris 1 Past Few Weeks For the past few weeks we have been focusing on data structures Classes & Object-oriented programming Collections Lists, Sets, Maps, etc. Now we turn our

More information

Algorithm Design and Recursion. Search and Sort Algorithms

Algorithm Design and Recursion. Search and Sort Algorithms Algorithm Design and Recursion Search and Sort Algorithms Objectives To understand the basic techniques for analyzing the efficiency of algorithms. To know what searching is and understand the algorithms

More information

CS201 - Assignment 3, Part 2 Due: Wednesday March 5, at the beginning of class

CS201 - Assignment 3, Part 2 Due: Wednesday March 5, at the beginning of class CS201 - Assignment 3, Part 2 Due: Wednesday March 5, at the beginning of class For this assignment we will be developing a text-based Tic Tac Toe game 1. The key to this assignment is that we re going

More information

Programming Languages. Streams Wrapup, Memoization, Type Systems, and Some Monty Python

Programming Languages. Streams Wrapup, Memoization, Type Systems, and Some Monty Python Programming Languages Streams Wrapup, Memoization, Type Systems, and Some Monty Python Quick Review of Constructing Streams Usually two ways to construct a stream. Method 1: Use a function that takes a(n)

More information

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion: Principle Recursion is useful in expressing solutions to problems that can be recursively defined: Base Cases:

More information

Agenda. The worst algorithm in the history of humanity. Asymptotic notations: Big-O, Big-Omega, Theta. An iterative solution

Agenda. The worst algorithm in the history of humanity. Asymptotic notations: Big-O, Big-Omega, Theta. An iterative solution Agenda The worst algorithm in the history of humanity 1 Asymptotic notations: Big-O, Big-Omega, Theta An iterative solution A better iterative solution The repeated squaring trick Fibonacci sequence 2

More information

CMSC 451: Lecture 10 Dynamic Programming: Weighted Interval Scheduling Tuesday, Oct 3, 2017

CMSC 451: Lecture 10 Dynamic Programming: Weighted Interval Scheduling Tuesday, Oct 3, 2017 CMSC 45 CMSC 45: Lecture Dynamic Programming: Weighted Interval Scheduling Tuesday, Oct, Reading: Section. in KT. Dynamic Programming: In this lecture we begin our coverage of an important algorithm design

More information

2: Complexity and Recursion

2: Complexity and Recursion 2: Complexity and Recursion Today About CS1 Complexity Introduction Examples Homework 1 Solutions Project 1 2 CS1 Exam Problem 4: Another cipher No problem for most students Highest average score Want

More information

CmpSci 187: Programming with Data Structures Spring 2015

CmpSci 187: Programming with Data Structures Spring 2015 CmpSci 187: Programming with Data Structures Spring 2015 Lecture #9 John Ridgway February 26, 2015 1 Recursive Definitions, Algorithms, and Programs Recursion in General In mathematics and computer science

More information

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet. Mr G s Java Jive #2: Yo! Our First Program With this handout you ll write your first program, which we ll call Yo. Programs, Classes, and Objects, Oh My! People regularly refer to Java as a language that

More information

11/2/2017 RECURSION. Chapter 5. Recursive Thinking. Section 5.1

11/2/2017 RECURSION. Chapter 5. Recursive Thinking. Section 5.1 RECURSION Chapter 5 Recursive Thinking Section 5.1 1 Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain kinds of problems that are difficult

More information

1.7 Limit of a Function

1.7 Limit of a Function 1.7 Limit of a Function We will discuss the following in this section: 1. Limit Notation 2. Finding a it numerically 3. Right and Left Hand Limits 4. Infinite Limits Consider the following graph Notation:

More information

Math 2250 Lab #3: Landing on Target

Math 2250 Lab #3: Landing on Target Math 2250 Lab #3: Landing on Target 1. INTRODUCTION TO THE LAB PROGRAM. Here are some general notes and ideas which will help you with the lab. The purpose of the lab program is to expose you to problems

More information

2.3 Recursion. Overview. Mathematical Induction. What is recursion? When one function calls itself directly or indirectly.

2.3 Recursion. Overview. Mathematical Induction. What is recursion? When one function calls itself directly or indirectly. 2.3 Recursion Overview Mathematical Induction What is recursion? When one function calls itself directly or indirectly. Why learn recursion? New mode of thinking. Powerful programming paradigm. Many computations

More information

2.3 Recursion. Overview. Greatest Common Divisor. Greatest Common Divisor. What is recursion? When one function calls itself directly or indirectly.

2.3 Recursion. Overview. Greatest Common Divisor. Greatest Common Divisor. What is recursion? When one function calls itself directly or indirectly. Overview 2.3 Recursion What is recursion? When one function calls itself directly or indirectly. Why learn recursion? New mode of thinking. Powerful programming paradigm. Many computations are naturally

More information

2.3 Recursion. Overview. Greatest Common Divisor. Greatest Common Divisor. What is recursion? When one function calls itself directly or indirectly.

2.3 Recursion. Overview. Greatest Common Divisor. Greatest Common Divisor. What is recursion? When one function calls itself directly or indirectly. Overview 2.3 Recursion What is recursion? When one function calls itself directly or indirectly. Why learn recursion? New mode of thinking. Powerful programming paradigm. Many computations are naturally

More information

CS 171: Introduction to Computer Science II. Quicksort

CS 171: Introduction to Computer Science II. Quicksort CS 171: Introduction to Computer Science II Quicksort Roadmap MergeSort Recursive Algorithm (top-down) Practical Improvements Non-recursive algorithm (bottom-up) Analysis QuickSort Algorithm Analysis Practical

More information

Introduction to Programming I

Introduction to Programming I Still image from YouTube video P vs. NP and the Computational Complexity Zoo BBM 101 Introduction to Programming I Lecture #09 Development Strategies, Algorithmic Speed Erkut Erdem, Aykut Erdem & Aydın

More information

Odds and Ends. Think about doing research Programming grading. Assignment 3 due Tuesday

Odds and Ends. Think about doing research Programming grading. Assignment 3 due Tuesday Odds and Ends Think about doing research Programming grading Correctness, Documentation, Style, Testing Working in pairs/groups; acknowledge accordingly Assignment 3 due Tuesday ...? Questions on HW Review

More information

Dynamic Programming Homework Problems

Dynamic Programming Homework Problems CS 1510 Dynamic Programming Homework Problems 1. Consider the recurrence relation T(0) = T(1) = 2 and for n > 1 n 1 T(n) = T(i)T(i 1) i=1 We consider the problem of computing T(n) from n. (a) Show that

More information

LOOPS. Repetition using the while statement

LOOPS. Repetition using the while statement 1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while

More information

Lecture Transcript While and Do While Statements in C++

Lecture Transcript While and Do While Statements in C++ Lecture Transcript While and Do While Statements in C++ Hello and welcome back. In this lecture we are going to look at the while and do...while iteration statements in C++. Here is a quick recap of some

More information

For this chapter, switch languages in DrRacket to Advanced Student Language.

For this chapter, switch languages in DrRacket to Advanced Student Language. Chapter 30 Mutation For this chapter, switch languages in DrRacket to Advanced Student Language. 30.1 Remembering changes Suppose you wanted to keep track of a grocery shopping list. You could easily define

More information

Extended Introduction to Computer Science CS1001.py

Extended Introduction to Computer Science CS1001.py Extended Introduction to Computer Science CS1001.py Lecture 11: Recursion and Recursive Functions (cont.) Instructors: Daniel Deutch, Amir Rubinstein Teaching Assistants: Michal Kleinbort, Yael Baran,

More information

Recursion. Recursion [Bono] 1

Recursion. Recursion [Bono] 1 Recursion Idea A few examples wishful thinking method Recursion in classes Ex: palindromes Helper functions Computational complexity of recursive functions Recursive functions with multiple calls Recursion

More information

#23: Sequences March 28, 2009

#23: Sequences March 28, 2009 #23: Sequences March 28, 2009 a mysterious rule easy peasy Suppose n is an integer, and consider this simple rule: if n is even, divide it by two; otherwise, multiply n by 3, and add one. Pretty simple,

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

To illustrate what is intended the following are three write ups by students. Diagonalization

To illustrate what is intended the following are three write ups by students. Diagonalization General guidelines: You may work with other people, as long as you write up your solution in your own words and understand everything you turn in. Make sure to justify your answers they should be clear

More information

FOR Loops. Last Modified: 01 June / 1

FOR Loops. Last Modified: 01 June / 1 FOR Loops http://people.sc.fsu.edu/ jburkardt/isc/week04 lecture 08.pdf... ISC3313: Introduction to Scientific Computing with C++ Summer Semester 2011... John Burkardt Department of Scientific Computing

More information

5.5 Completing the Square for the Vertex

5.5 Completing the Square for the Vertex 5.5 Completing the Square for the Vertex Having the zeros is great, but the other key piece of a quadratic function is the vertex. We can find the vertex in a couple of ways, but one method we ll explore

More information

Lesson 12: Recursion, Complexity, Searching and Sorting. Modifications By Mr. Dave Clausen Updated for Java 1_5

Lesson 12: Recursion, Complexity, Searching and Sorting. Modifications By Mr. Dave Clausen Updated for Java 1_5 Lesson 12: Recursion, Complexity, Searching and Sorting Modifications By Mr. Dave Clausen Updated for Java 1_5 1 Lesson 12: Recursion, Complexity, and Searching and Sorting Objectives: Design and implement

More information

CSE 143. Complexity Analysis. Program Efficiency. Constant Time Statements. Big Oh notation. Analyzing Loops. Constant Time Statements (2) CSE 143 1

CSE 143. Complexity Analysis. Program Efficiency. Constant Time Statements. Big Oh notation. Analyzing Loops. Constant Time Statements (2) CSE 143 1 CSE 1 Complexity Analysis Program Efficiency [Sections 12.1-12., 12., 12.9] Count number of instructions executed by program on inputs of a given size Express run time as a function of the input size Assume

More information

Variables and Data Representation

Variables and Data Representation You will recall that a computer program is a set of instructions that tell a computer how to transform a given set of input into a specific output. Any program, procedural, event driven or object oriented

More information

Lecture P6: Recursion

Lecture P6: Recursion Overview Lecture P6: Recursion What is recursion? When one function calls ITSELF directly or indirectly. Why learn recursion? Powerful programming tool to solve a problem by breaking it up into one (or

More information

CMPSCI 187 / Spring 2015 Hanoi

CMPSCI 187 / Spring 2015 Hanoi Due on Thursday, March 12, 2015, 8:30 a.m. Marc Liberatore and John Ridgway Morrill I N375 Section 01 @ 10:00 Section 02 @ 08:30 1 Contents Overview 3 Learning Goals.................................................

More information

Repetition Structures

Repetition Structures Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements

More information

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution. Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes

More information

RANDOM NUMBER GAME PROJECT

RANDOM NUMBER GAME PROJECT Random Number Game RANDOM NUMBER GAME - Now it is time to put all your new knowledge to the test. You are going to build a random number game. - The game needs to generate a random number between 1 and

More information

The Knapsack Problem an Introduction to Dynamic Programming. Slides based on Kevin Wayne / Pearson-Addison Wesley

The Knapsack Problem an Introduction to Dynamic Programming. Slides based on Kevin Wayne / Pearson-Addison Wesley The Knapsack Problem an Introduction to Dynamic Programming Slides based on Kevin Wayne / Pearson-Addison Wesley Different Problem Solving Approaches Greedy Algorithms Build up solutions in small steps

More information

Assignment 4. Aggregate Objects, Command-Line Arguments, ArrayLists. COMP-202B, Winter 2011, All Sections. Due: Tuesday, March 22, 2011 (13:00)

Assignment 4. Aggregate Objects, Command-Line Arguments, ArrayLists. COMP-202B, Winter 2011, All Sections. Due: Tuesday, March 22, 2011 (13:00) Assignment 4 Aggregate Objects, Command-Line Arguments, ArrayLists COMP-202B, Winter 2011, All Sections Due: Tuesday, March 22, 2011 (13:00) You MUST do this assignment individually and, unless otherwise

More information

Below is the simple C program with recursive approach for Towers of Hanoi problem

Below is the simple C program with recursive approach for Towers of Hanoi problem Dear Users, I would like to put before you with an explanation that would convince you all about recursively solving the famous problem - Towers of Hanoi. Usually, we mug it up just because the code length

More information

i.e.: n! = n (n 1)

i.e.: n! = n (n 1) Recursion and Java Recursion is an extremely powerful problemsolving technique. Problems that at first appear difficult often have simple recursive solutions. Recursion breaks a problems into several smaller

More information

CS61A Summer 2010 George Wang, Jonathan Kotker, Seshadri Mahalingam, Eric Tzeng, Steven Tang

CS61A Summer 2010 George Wang, Jonathan Kotker, Seshadri Mahalingam, Eric Tzeng, Steven Tang CS61A Notes Week 6B: Streams Streaming Along A stream is an element and a promise to evaluate the rest of the stream. You ve already seen multiple examples of this and its syntax in lecture and in the

More information

Solving problems by recursion

Solving problems by recursion Solving problems by recursion How can you solve a complex problem? Devise a complex solution Break the complex problem into simpler problems Sometimes, the simpler problem is similar to (but smaller than)

More information

Counting Problems; and Recursion! CSCI 2824, Fall 2012!

Counting Problems; and Recursion! CSCI 2824, Fall 2012! Counting Problems; and Recursion! CSCI 2824, Fall 2012!!! Assignments To read this week: Sections 5.5-5.6 (Ensley/Crawley Problem Set 3 has been sent out today. Challenge problem today!!!!! So, to recap

More information

9/16/14. Overview references to sections in text RECURSION. What does generic mean? A little about generics used in A3

9/16/14. Overview references to sections in text RECURSION. What does generic mean? A little about generics used in A3 Overview references to sections in text 2 Note: We ve covered everything in JavaSummary.pptx! What is recursion 7.1-7.39 slide 1-7 Base case 7.1-7.10 slide 13 How Java stack frames work 7.8-7.10 slide

More information

Discussion 11. Streams

Discussion 11. Streams Discussion 11 Streams A stream is an element and a promise to evaluate the rest of the stream. You ve already seen multiple examples of this and its syntax in lecture and in the books, so I will not dwell

More information

Math 4242 Fibonacci, Memoization lecture 13

Math 4242 Fibonacci, Memoization lecture 13 Math 4242 Fibonacci, Memoization lecture 13 Today we talk about a problem that sometimes occurs when using recursion, and a common way to fix it. Recall the Fibonacci sequence (F 1, F 2,...) that occurs

More information

Recursion Chapter 17. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Recursion Chapter 17. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Scope Introduction to Recursion: The concept of recursion Recursive methods Infinite recursion When to use (and

More information

Sets. Sets. Examples. 5 2 {2, 3, 5} 2, 3 2 {2, 3, 5} 1 /2 {2, 3, 5}

Sets. Sets. Examples. 5 2 {2, 3, 5} 2, 3 2 {2, 3, 5} 1 /2 {2, 3, 5} Sets We won t spend much time on the material from this and the next two chapters, Functions and Inverse Functions. That s because these three chapters are mostly a review of some of the math that s a

More information

Overview. What is recursion? When one function calls itself directly or indirectly.

Overview. What is recursion? When one function calls itself directly or indirectly. 1 2.3 Recursion Overview What is recursion? When one function calls itself directly or indirectly. Why learn recursion? New mode of thinking. Powerful programming paradigm. Many computations are naturally

More information