CSC 1351: Quiz 6: Sort and Search

Similar documents
CSC 1351: Exam On Everything

CSC 1351: Exam 2: Midterm

CSC 1351: Final. The code compiles, but when it runs it throws a ArrayIndexOutOfBoundsException

Recursion. What is Recursion? Simple Example. Repeatedly Reduce the Problem Into Smaller Problems to Solve the Big Problem

8. Functions (II) Control Structures: Arguments passed by value and by reference int x=5, y=3, z; z = addition ( x, y );

We cover recursion in 150. Why do it again in 151?

COMP 110 Programming Exercise: Simulation of the Game of Craps

CSCI 136 Data Structures & Advanced Programming. Fall 2018 Instructors Bill Lenhart & Bill Jannen

Recursion and collections

CS 139 Practice Midterm Questions #2

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3...

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

Examination Questions Midterm 1

Chapter 7: Arrays CS 121. April 9, Department of Computer Science College of Engineering Boise State University. Chapter 7: Arrays CS / 41

FORM 2 (Please put your name and form # on the scantron!!!!)

Loops. CSE 114, Computer Science 1 Stony Brook University

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

CS205: Scalable Software Systems

Recursion (Part 2) 1

CSE 143 SAMPLE MIDTERM

Recursion. Fundamentals of Computer Science

Basics of Programming with Python

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

CS 106 Introduction to Computer Science I

CS302: Self Check Quiz 2

Function Call Stack and Activation Records

LAB: WHILE LOOPS IN C++

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Pace University. Fundamental Concepts of CS121 1

CSCE 206: Structured Programming in C++

Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

Java Errors and Exceptions. Because Murphy s Law never fails

Fun facts about recursion

CSC Java Programming, Fall Java Data Types and Control Constructs

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Solutions to Quiz 2 (April 27, 2018)

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

Introduction to Object-Oriented Programming

COT 3100 Spring 2010 Midterm 2

Java Simple Data Types

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

Mat 2170 Week 9. Spring Mat 2170 Week 9. Objects and Classes. Week 9. Review. Random. Overloading. Craps. Clients. Packages. Randomness.

Chapter 13. Recursion. Copyright 2016 Pearson, Inc. All rights reserved.

Prelim 1. CS 2110, October 1, 2015, 5:30 PM Total Question Name True Short Testing Strings Recursion

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

COMP520 - GoLite Type Checking Specification

Lecture 7. Random number generation More randomized data structures Skip lists: ideas and implementation Skip list time costs

ArrayList. Introduction. java.util.arraylist

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

Chapter 1: Introduction to Computers, Programs, and Java

CONDITIONAL EXECUTION

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

CIS 110 Introduction To Computer Programming. February 29, 2012 Midterm

CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims. Lecture 10: Asymptotic Complexity and

CS111: PROGRAMMING LANGUAGE II

Student Responsibilities. Mat 2170 Week 9. Notes About Using Methods. Recall: Writing Methods. Chapter Six: Objects and Classes

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Module 2: Choice and Iteration

Linked List Implementation of Queues

Controls Structure for Repetition

CSC 1052 Algorithms & Data Structures II: Recursion

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

LAB: FOR LOOPS IN C++

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

1.3 Conditionals and Loops

Lab5. Wooseok Kim

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

CS180 Review. Recitation Week 15

Computer Science E-119 Fall Problem Set 1. Due before lecture on Wednesday, September 26

Computational Expression

APCS Semester #1 Final Exam Practice Problems

Java Outline (Upto Exam 2)

Chapter 12 Supplement: Recursion with Java 1.5. Mr. Dave Clausen La Cañada High School

Condition Controlled Loops. Introduction to Programming - Python

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 4 Certificate in IT SOFTWARE DEVELOPMENT

CSCI 136 Data Structures & Advanced Programming. Lecture 12 Fall 2018 Profs Bill & Jon

Repetition, Looping. While Loop

Condi(onals and Loops

Thomas Jefferson Invitational Open in Informatics 2012

Names and Functions. Chapter 2

COMP520 - GoLite Type Checking Specification

CS 314 Exam 2 Fall 2017

Object Oriented Programming Exception Handling

CS159. Nathan Sprague. November 9, 2015

Chapter 4 Introduction to Control Statements

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion

Key Java Simple Data Types

COMP520 - GoLite Type Checking Specification

JAVA OPERATORS GENERAL

Lecture Transcript While and Do While Statements in C++

Recursion. Chapter 11. Chapter 11 1

Java Coding 3. Over & over again!

Transcription:

CSC 1351: Quiz 6: Sort and Search Name: 0.1 You want to implement combat within a role playing game on a computer. Specifically, the game rules for damage inflicted by a hit are: In order to figure out damage from one hit, you throw a N-sided die. The result of one throw will be between 1 and N (including both, e.g., a 6-sided die has six sides, labled 1 to 6). If the result is 1 to N-1, that is the resulting damage from the hit. If the result in N, however, you hit critically, and you throw again, adding the results. If you throw again, the same rules apply, potentially resulting in doubly or more critical hits. For example, if you use a 4-sided die and throw a 3, the damage is 3. If you throw a 4 instead, you throw again. If that results in a 3, the total damage is 7. If you happen to throw two 4s after each other and then a 2, the total damage is 10. Fill in the missing code. The number of lines corresponds to the answer key. Your code may vary. final static Random rand = new Random (); public static int damage ( int n) { int result = rand. nextint ( n) + 1; if ( result < n) return result ; return result + damage ( n); 0.2 You want to implement flipping a coin on a computer. However, you want to be fancy and include the possibility of the coin standing on edge, with a probability of 2%. In that case you flip it again, until the coin lands on either side. Heads give 1 point, Tails give 0 points, and an edge gives an additional 2 points (potentially multiple times). Most of the time the return value will be 0 or 1. However, if the coin landed on edge once, the return value will be either 2 or 3, depending on the final toss. If it landed on edge twice, it could be either 4 or 5, in a similar way. Fill in the missing code. The number of lines corresponds to the answer key. Your code may vary. final static Random rand = new Random (); public static int flip () { int randompercentage = rand. nextint ( 100) ; if ( randompercentage < 2) return 2 + flip (); if ( randompercentage < 51) return 0; return 1; 0.3 This task involves a game with plush owls. You start the game with a given number of owls. You can then give back some of the owls, according to the rules below. If multiple rules apply, it is your choice which to use. If none applies, you loose. The goal is to end up with exactly 42 owls. n is the number of owls you currently have. If n is even, you may give back exactly n/2 owls. 1

If n is divisible by 3 or 4, you may multiply the last two digits of n and give back this many owls. (the last digit of n is n%10, the next-to-last digit is ((n%100)/10). If n is divisible by 5, then you may give back exactly 42 owls. For example, suppose you start with 250 owls, you could do the following moves: Since 250 is divisible by 5, you may return 42 owls, leaving you with 208. Since 208 is even, you may return half of them, leaving you with 104. Since 104 is even again, you may do the same again, leaving you with 52. Since 52 is didisible by 4, you may multiply the last two digits (2*5=10), and return 10 owls, leaving you with 42 owls, and resulting in a win. Write a recursive function to meet this specification: // The return value should indicate whether it is possible to win this game if // you start with n owls. For example : // owls ( 250) is true // owls ( 42) is true // owls ( 84) is true // owls ( 53) is false // owls ( 41) is false public class Owls { public static boolean owls ( int n) { // smaller than 42 if ( n <42) return false ; // equal 42 if ( n ==42) return true ; // divisible by 2 if (n %2==0 && owls (n /2) ) return true ; // divisible by 3 or 4 if ((n %3==0 n %4==0) && owls (n -(( n %10) *(( n %100) /10) ))) return true ; // divisible by 5 if (n %5==0 && owls (n -42) ) return true ; return false ; 0.4 This task involves a game with plush bunnies. You start the game with a given number of bunnies. You can then give back some of the bunnies, according to the rules below. If multiple rules apply, it is your choice which to use. If none applies, you loose. The goal is to end up with exactly 42 bunnies. n is the number of bunnies you currently have. If n is even, you may give back exactly n/2 bunnies. If n is divisible by 3 or 4, you may multiply the last two digits of n and give back this many bunnies. (the last digit of n is n%10, the next-to-last digit is ((n%100)/10). If n is divisible by 5, then you may give back exactly 42 bunnies. For example, suppose you start with 250 bunnies, you could do the following moves: Since 250 is divisible by 5, you may return 42 bunnies, leaving you with 208. Since 208 is even, you may return half of them, leaving you with 104. Since 104 is even again, you may do the same again, leaving you with 52. Since 52 is didisible by 4, you may multiply the last two digits (2*5=10), and return 10 bunnies, leaving you with 42 bunnies, and resulting in a win. Write a recursive function to meet this specification:

// The return value should indicate whether it is possible to win this game if // you start with n bunnies. For example : // bunnies ( 250) is true // bunnies ( 42) is true // bunnies ( 84) is true // bunnies ( 53) is false // bunnies ( 41) is false public class Bunnies { public static boolean bunnies ( int n) { // smaller than 42 if ( n <42) return false ; // equal 42 if ( n ==42) return true ; // divisible by 2 if (n %2==0 && bunnies (n /2) ) return true ; // divisible by 3 or 4 if ((n %3==0 n %4==0) && bunnies (n -(( n %10) *(( n %100) /10) ))) return true ; // divisible by 5 if (n %5==0 && bunnies (n -42) ) return true ; return false ; 0.5 What is wrong with the following program, what happens when you run it? If this method would have been implemented using a loop, and would have a similar error, what would happen then if run? public class JavaIsToJavascriptWhatCarIsToCarpet { public static int factorial ( int n) { return (n * factorial (n -1) ); factorial (4) ; There is an exit-condition missing in the recursive function. When run, you get a stack overflow. This is similar to infinite loops, so the same in an iterative program would result in a hang during execution. 0.6 What is wrong with the following program, what happens when you run it? If this method would have been implemented recursively, and would have a similar error, what would happen then if run? public class JavaIsToJavascriptWhatCarIsToCarpet { public static int factorial ( int n) { int result = 1; while (n > 1) { result *= n; return result ; assert ( factorial (4) == 24) ; There is an exit-condition missing in the while loop. When run, the program hangs. This is similar to infinite recursions, so the same in a recursive program would result in a stack overflow. 0.7 Implement the factorial() method in the JavaIsToJavascriptWhatCarIsToCarpet class above recursively, correctly.

public static int factorial ( int n) { if ( n < 1) return 1; return (n * factorial (n -1)); 0.8 What is wrong with the following program, what happens when you run it? If this method would have been implemented recursively, and would have a similar error, what would happen then if run? public class JavaIsToJavascriptWhatCarIsToCarpet { public static int factorial ( int n) { int result = 1; while (n > 1) { result *= n; return result ; assert ( factorial (4) == 24) ; There is an exit-condition missing in the while loop. When run, the program hangs. This is similar to infinite recursions, so the same in a recursive program would result in a stack overflow. 0.9 Given an List of Integers, is it possible to choose a group of Integers, such that the sum of all Integers in that group matches a given target with this additional constraint: If a value in the List is chosen to be in the group, the value immediately following it in the List must not be chosen. Do not use loops. Example inputs and returns for groups(): [],0 false [1],0 false [1],1 true [1,2], 1 true [1,2], 3 false [1,0], 1 true [1,0], 0 true [1,2,3], 4 true You may (but don t have to) use the sublist method, defined in java.util.list, which is declared as follows, and returns a part (slice) of the input array (fromindex inclusive, toindex exclusive): List <E > sublist ( int fromindex, int toindex ) Fill in the missing code. The number of lines corresponds to the answer key. Your code may vary. public static boolean groups ( List < Integer > list, int target ) { if ( list. size () == 0) return false ; if ( list. get (0) == target ) return true ; if ( list. size () >= 2 && groups ( list. sublist (2, list. size ()), target - list. get (0) ) == true ) return true ; return groups ( list. sublist (1, list. size ()), target );

0.10 Write a recursive program to compute a double factorial, n!! = n*(n-2)!!, 0!! = 1, 1!! = 1. public class DFac { static int dfac ( int n) { if( n < 2) return 1; return n* dfac (n -2); public static void main ( String [] args ) { assert dfac (7) == 7* 5* 3* 1; 0.11 Does the following code compile? If it does not, how can it be fixed? If it does, what is it s output? Does it throw an exception? If so, how can it be fixed? public class Series { public static int func ( int j) { System. out. println (j); if ( j ==1) return 1; return 2* func (j -1) + 5* func (j -2) ; public static void main ( String [] args ) { int N = Integer. parseint ( args [0]) ; if (N <1) { System. out. println (" invalid argument "); return ; System. out. println ( func (N)); The code compiles, but when it runs it throws a StackOverflowError replace the code : if ( j ==1) return 1; with the code : if ( j <1) return 1; 0.12 Which of these will happen if recursive method does not have a base case? 1. An infinite loop occurs, hanging forever. 2. The program stops after some time with an error. 3. After 1000000 calls it will be automatically stopped. 4. None of the mentioned The program stops after some time with an error. (stack overflow) 0.13 What is the output of this program? class recursion { int func ( int n) { int result ; result = func ( n - 1); return result ; public class Output {

recursion obj = new recursion () ; System. out. print ( obj. func (12) ); 1. 0 2. 1 3. 12 4. Compilation Error 5. Runtime Error Runtime Error: Exception in thread main java.lang.stackoverflowerror 0.14 What is recursion? 1. Recursion is a generic class. 2. Recursion is a process of setting a value based on it s previous value. 3. Recursion is a process of defining a method that calls itself. 4. Recursion is a process of repeatedlty calling other methods. Recursion is a process of defining a method that calls itself.