CSE 143. Computer Programming II

Similar documents
CSE 143. Computer Programming II

Adam Blank Lecture 2 Winter 2017 CSE 332. Data Structures and Parallelism

Adam Blank Lecture 1 Winter 2017 CSE 332. Data Abstractions

Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi.

CSE 143X. Accelerated Computer Programming I/II

CS103 Handout 29 Winter 2018 February 9, 2018 Inductive Proofwriting Checklist

QUIZ: What value is stored in a after this

Introduction to Computation for the Humanities and Social Sciences. CS 3 Chris Tanner

What is the minimum number of letters that could have been changed?

Lecture 11: Recursion (hard)

CSE 120. Computer Science Principles

CSE 143. More ArrayIntList; pre/post; exceptions; debugging. Computer Programming II. CSE 143: Computer Programming II

Adam Blank Lecture 3 Autumn 2016 CSE 143. Computer Programming II

Types, Expressions, and States

Lecture 16 CSE July 1992

Lecture 4 CSE July 1992

Search Lesson Outline

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger.

CS 4349 Lecture October 18th, 2017

What can we do with Processing? Let s check. Natural Language and Dialogue Systems Lab Guest Image. Remember how colors work.

1.7 Limit of a Function

(Provisional) Lecture 22: Rackette Overview, Binary Tree Analysis 10:00 AM, Oct 27, 2017

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

1.00 Tutorial 1. Introduction to 1.00

CS150 - Sample Final

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

RECURSION (CONTINUED)

Arithmetic-logic units

CSE 113 A. Announcements - Lab

(Refer Slide Time: 01.26)

If Statements, For Loops, Functions

CSC 220: Computer Organization Unit 10 Arithmetic-logic units

Remember, this question was mis-worded: you could also add quoted words and sentences in the blanks below. This allowed for a solution to [4] below.

Turn in a printout of your code exercises stapled to your answers to the written exercises at 2:10 PM on Thursday, January 13th.

Question 0. (1 point) Write the correct ID of the section you normally attend on the cover page of this exam if you have not already done so.

Enums. In this article from my free Java 8 course, I will talk about the enum. Enums are constant values that can never be changed.

Loop structures and booleans

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

Classes, interfaces, & documentation. Review of basic building blocks

Propositional Logic:

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #06 Loops: Operators

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

6.189 Project 1. Readings. What to hand in. Project 1: The Game of Hangman. Get caught up on all the readings from this week!

Jalil Boudjadar, Tommy Färnqvist. IDA, Linköping University. 1 Recursive search Exhaustive search Backtracking

Enter the site Title: Student Name s eportfolio Choose your Website Domain: Use a Subdomain of Weebly.com

5 R1 The one green in the same place so either of these could be green.

CSE373 Fall 2013, Midterm Examination October 18, 2013

CS1 Lecture 5 Jan. 25, 2019

Text Input and Conditionals

CSE 331 Final Exam 3/12/12

Due: 9 February 2017 at 1159pm (2359, Pacific Standard Time)

hw6, BFS, debugging CSE 331 Section 5 10/25/12 Slides by Kellen Donohue

Control Structures 1 / 17

Why study algorithms? CS 561, Lecture 1. Today s Outline. Why study algorithms? (II)

Computer Science 210: Data Structures

4.1 Review - the DPLL procedure

Express Yourself. Writing Your Own Classes

CSE115 / CSE503 Introduction to Computer Science I. Dr. Carl Alphonce 343 Davis Hall Office hours:

CSE 332 Spring 2014: Midterm Exam (closed book, closed notes, no calculators)

// Body of shortestlists starts here y flatmap { case Nil => Nil case x :: xs => findshortest(list(x), xs)

Testing and Debugging

Q1: Multiple choice / 20 Q2: C input/output; operators / 40 Q3: Conditional statements / 40 TOTAL SCORE / 100 EXTRA CREDIT / 10

Building Java Programs

PRACTICE MIDTERM EXAM #2

CSE 143 Lecture 11. Decimal Numbers

Final Exam CS 251, Intermediate Programming December 13, 2017

1 ICS 161: Design and Analysis of Algorithms Lecture notes for January 23, Bucket Sorting

Algebraic Specifications

COP Programming Assignment #7

Review. CSE 143 Java. A Magical Strategy. Hash Function Example. Want to implement Sets of objects Want fast contains( ), add( )

CS 1301 Exam 1 Answers Fall 2009

CSCI-1200 Data Structures Spring 2018 Lecture 14 Associative Containers (Maps), Part 1 (and Problem Solving Too)

Lecture 4. CS118 Term planner. The simple if statement. Control flow: selection. The if... else statement cont... The if... else statement.

Lecture 1: CSE 373. Data Structures and Algorithms

Transcriber(s): Aboelnaga, Eman Verifier(s): Yedman, Madeline Date Transcribed: Fall 2010 Page: 1 of 9

CS 115 Lecture 8. Selection: the if statement. Neil Moore

CSE 373 OCTOBER 11 TH TRAVERSALS AND AVL

CS106B Final Exam Solutions

CSE 332 Winter 2018 Final Exam (closed book, closed notes, no calculators)

Australian researchers develop typeface they say can boost memory, that could help students cramming for exams.

EECE.2160: ECE Application Programming Spring 2016 Exam 1 Solution

Ex: If you use a program to record sales, you will want to remember data:

Instructions. Definitions. Name: CMSC 341 Fall Question Points I. /12 II. /30 III. /10 IV. /12 V. /12 VI. /12 VII.

The story so far. Elements of Programming Languages. Pairs in various languages. Pairs

Strings in Python: Cipher Applications CS 8: Introduction to Computer Science, Winter 2018 Lecture #9

Lecture 7: Primitive Recursion is Turing Computable. Michael Beeson

CSE 2123 Recursion. Jeremy Morris

Adam Blank Lecture 9 Autumn 2016 CSE 143. Computer Programming II

6.001 Notes: Section 8.1

CSE 331 Final Exam 3/16/15 Sample Solution

CSE 247 Data Structures and Algorithms Fall Exam I

CS314 Exam 2 - Spring Suggested Solution and Criteria 1

Programming Languages and Techniques (CIS120)

Please write your name and username here legibly: C212/A592 6W2 Summer 2017 Early Evaluation Exam: Fundamental Programming Structures in Java

CSE332: Data Abstractions Lecture 23: Programming with Locks and Critical Sections. Tyler Robison Summer 2010

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

CSE 143 Lecture 14 AnagramSolver and Hashing

for dequeue will be O(N). (Or words to that effect. Needed to mention both or -1.)

CSE 341, Autumn 2005, Assignment 3 ML - MiniML Interpreter

CS 61B Discussion 5: Inheritance II Fall 2014

Transcription:

Adam Blank Lecture 17 Winter 2015 CSE 143 Computer Programming II

CSE 143: Computer Programming II Recursive Backtracking Recursive Backtracking

Outline 1 Sentence Splitter 2 Playing With Boolean Expressions

Recursive Backtracking 1 Definition (Recursive Backtracking) Recursive Backtracking is an attempt to find solution(s) by building up partial solutions and abandoning them if they don t work. Recursive Backtracking Strategy If we found a solution, stop looking (e.g. return) Otherwise for each possible choice c... Make the choice c Recursively continue to make choices Un-make the choice c (if we got back here, it means we need to continue looking)

Implementing a Tiny Piece of Google 2 When you enter a query with no spaces like thisisasentence into Google: It fixes it into this is a sentence using recursive backtracking. Sentence Splitting Given an input string, sentence, containing no spaces, write a method: public static String splitsentence(string sentence) that returns sentence split up into words.

Sentence Splitting 3 Sentence Splitting Given an input string, sentence, containing no spaces, write a method: public static String splitsentence(string sentence) that returns sentence split up into words. To do recursive backtracking, we need to answer these questions: What are the choices we re making incrementally? How do we undo a choice? What are the base case(s)? It helps to answer these questions for a particular input. So, pretend we re working with: thisisasentence

Sentence Splitting 3 Sentence Splitting Given an input string, sentence, containing no spaces, write a method: public static String splitsentence(string sentence) that returns sentence split up into words. To do recursive backtracking, we need to answer these questions: What are the choices we re making incrementally?... which character to split at How do we undo a choice?... re-combine a string by the char we split at What are the base case(s)?... our left choice isn t a word and our right choice IS a word It helps to answer these questions for a particular input. So, pretend we re working with: thisisasentence

One More Important Choice 4 When doing recursive backtracking, we need to differentiate between: finding a result failing to find a result (e.g., backtracking) Generally, we do this by treating null as a failure. For example: On the input, thisisasentence, none of the recursive calls should return thisis, because it isn t a word. If we get down to an empty string, that would indicate a failure; so, we d return null

Sentence Splitter Solution 5 1 public String splitsentence(string sentence) { 2 // The entire sentence is a dictionary word! 3 if (words.contains(sentence)) { 4 return sentence; 5 } 6 7 // Try splitting at every character until we find one that works... 8 for (int i = sentence.length() 1; i > 0; i ){ 9 String left = sentence.substring(0, i); 10 String right = sentence.substring(i, sentence.length()); 11 12 // If the left isn t a word, don t bother recursing. 13 // If it is, split the remainder of the sentence recursively. 14 if (words.contains(left)) { 15 right = splitsentence(right); 16 // Since the left was a word, if the right is also an answer, 17 // then we found an answer to the whole thing! 18 if (right!= null) { 19 return left + " " + right; 20 } 21 22 // Undo our choice by going back to sentence 23 } 24 } 25 return null; 26 }

Client vs. Implementor, again 6 You may have noticed that many of the class examples I ve been showing involve me using a class that I ve already written. There are several reasons for this: Learning to read and use an API is a really important programming skill Switching between the client and implementor views is an important goal of this course The code I write is usually easy, but really tedious (so, it would be a waste of time to write in class) Take-Away Every time I print out an API for you, you should try to understand it from the comments. This will help you on the homework, on exams, and in any future programming endeavors.

BooleanExpression 7 Today s API is BooleanExpression. What is a BooleanExpression? The BooleanExpression class allows us to represent the conditions we write in if statements. For instance, to represent the following: 1 if (!(queue.size() > 0) && queue.peek() > 5) { 2... 3 } We would do new BooleanExpression("(!a && b)"); Notice that we use single letter variable names instead of queue.size() > 0. This is a simplification for implementation.

Evaluating BooleanExpression 8 Evaluating BooleanExpressions Remember when we took (1+2) 3 and evaluated it to 9 recursively? We can do a similar thing for BooleanExpressions: Consider the BooleanExpression from above: Suppose we know the following: a is true. b is false. "(!a && b)" What does this expression evaluate to? (!a && b) (!true && false) (false && false) false Suppose we wanted to write a method: public static boolean evaluate(booleanexpression e,??? assn) where assn represents the truth values of the variables. What type would assn be? It s a mapping from variables to truth values.

Evaluating BooleanExpression 9 Okay, so, we have: public static boolean evaluate(booleanexpression e, Map<String, Boolean> assignments) Consider the following case: evaluate return value? e is a && b assignments map is {a=true}. What should evaluate return? We can t answer the question. What seems like a good idea? null. So, we change the return type to Boolean.

Who Should Implement evaluate? 10 Who Writes evaluate? The implementor of BooleanExpression...if so, it should be inside the BooleanExpression class The client of BooleanExpression...if so, it should be outside the BooleanExpression class The implementor of BooleanExpression should write the method, because then all the clients can use it. That pesky static... If the implementor writes evaluate, then the method signature is: public Boolean evaluate(map<string, Boolean> assn) If the client writes evaluate, then the method signature is: public static Boolean evaluate( BooleanExpression e, Map<String, Boolean> assn )

Finally, Back To Recursive Backtracking... 11 canbetrue Write a method public static boolean canbetrue(booleanexpression b) that returns true if it is possible for the input to to evaluate to true and false otherwise. Some examples: a && b if we have {a=true, b=true}, then it is true. a &&!a no matter what a is, this will always be false. To do recursive backtracking, we need to answer these questions: What are the choices we re making incrementally? How do we undo a choice? What are the base case(s)?

Finally, Back To Recursive Backtracking... 11 canbetrue Write a method public static boolean canbetrue(booleanexpression b) that returns true if it is possible for the input to to evaluate to true and false otherwise. Some examples: a && b if we have {a=true, b=true}, then it is true. a &&!a no matter what a is, this will always be false. To do recursive backtracking, we need to answer these questions: What are the choices we re making incrementally?... assignments of each variable to true/false How do we undo a choice?... remove the assignment from the map What are the base case(s)?... the assignment must be true/false

Uh Oh... How can we try assignments? 12 We don t have a way of passing assignments through to the function. How can we fix this? public/private pair! Public/Private Recursive Pair public static boolean canbetrue(booleanexpression b) private static boolean canbetrue( BooleanExpression b, Map<String, Boolean> m )

canbetrue Solution 13 1 public static Map<String, Boolean> canbetrue(booleanexpression b) { 2 Map<String, Boolean> assignmentmap = new TreeMap<>(); 3 if (canbetrue(b, assignmentmap)) { // Some assignment works... 4 return assignmentmap; 5 } 6 return null; 7 } 8 9 private static boolean canbetrue(booleanexpression b, Map<String, Boolean> m) { 10 Boolean result = b.evaluate(m); // See if the current assignment works 11 if (result!= null) { // If we can t answer, backtrack 12 return result; 13 } 14 15 Set<String> variables = b.getvariables(); 16 variables.removeall(m.keyset()); 17 for (String variable : variables) { // Try to assign any 18 boolean[] choices = {true, false}; // variable we haven t 19 for (boolean assignment : choices) { // already assigned. 20 m.put(variable, assignment); 21 Boolean attempt = canbetrue(b, m); 22 if (attempt) { // If we found an 23 return true; // assignment, we re good. 24 } 25 m.remove(variable); // Otherwise, backtrack 26 } 27 } 28 29 return false; 30 }

BTW, Why does this problem matter? 14 Solving canbetrue quickly is the most important open problem in Computer Science. If you solve this problem in O(n k ) time for any k, the following happen: You get one million dollars. You get a PhD. You become the most famous Computer Scientist, pretty much ever You break all banks, credit cards, website encryption, etc.