Two examples of Problem Solving in Programming H. Chad Lane University of Pittsburgh CS7: Introduction to Programming.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Computer and Programming
Building Java Programs
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 5: Program Logic and Indefinite Loops.
Algorithms and Problem Solving
Top-Down Design CSC 161: The Art of Programming Prof. Henry Kautz 9/16/2009.
Introduction to working with Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming.
Chapter 2: Algorithm Discovery and Design
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Methods: Functional Abstraction Structured Programming –The flow of control in a program should be as simple as possible – The construction of a program.
Classes, methods, and conditional statements We’re past the basics. These are the roots.
Introduction to Computer Science Exam Information Unit 20.
Computer Science 1620 Programming & Problem Solving.
Functional Abstraction (Chap 4) Structured Programming –The flow of control should be as simple as possible (Chapter 3). –The construction of a program.
Introduction to Computer Programming Looping Around Loops II : Conditional Loops.
Chapter 2: Algorithm Discovery and Design
Chapter 2: Algorithm Discovery and Design
CS305j Introduction to Computing Conditional Execution 1 Topic 12 Conditional Execution "We flew down weekly to meet with IBM, but they thought the way.
Methods (Functions) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
11 Finding Winners Using Arrays Session 8.2. Session Overview  Find out how the C# language makes it easy to create an array that contains multiple values.
Chapter 2: Algorithm Discovery and Design Invitation to Computer Science, C++ Version, Third Edition.
Invitation to Computer Science, Java Version, Second Edition.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Putting together a complete system Chapter 10. Overview  Design a modest but complete system  A collection of objects work together to solve a problem.
CSC 204 Programming I Loop I The while statement.
Section 3.1: Proof Strategy Now that we have a fair amount of experience with proofs, we will start to prove more difficult theorems. Our experience so.
By the end of this session you should be able to...
Repetition & Loops. One of the BIG advantages of a computer: ­It can perform tasks over and over again, without getting bored or making mistakes (assuming.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Making Decisions uCode: October Review What are the differences between: o BlueJ o Java Computer objects represent some thing or idea in the real.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
More on Logic Today we look at the for loop and then put all of this together to look at some more complex forms of logic that a program will need The.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 5: Control Structures II
COMP Flow of Control: Branching 1 Yi Hong May 19, 2015.
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
Georgia Institute of Technology More on Creating Classes part 2 Barb Ericson Georgia Institute of Technology Oct 2005.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Introduction to Computing Concepts Note Set 15. JOptionPane.showMessageDialog Message Dialog Allows you to give a brief message to the user Can be used.
 2002 Prentice Hall. All rights reserved. 1 Chapter 4 – Control Structures Part 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures.
Counting Loops.
Week 61 Introduction to Programming Ms. Knudtzon C Period Tuesday October 12.
M1G Introduction to Programming 2 3. Creating Classes: Room and Item.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Introduction to Computers and Programming Lecture 7:
CSE 143 Lecture 13 Recursive Backtracking slides created by Ethan Apter
More on Logic Today we look at the for loop and then put all of this together to look at some more complex forms of logic that a program will need The.
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Chapter 2: Algorithm Discovery and Design Invitation to Computer Science.
1 BUILDING JAVA PROGRAMS CHAPTER 5 PROGRAM LOGIC AND INDEFINITE LOOPS.
Chapter 5: Control Structures II
Chapter 4 – Control Structures Part 1
Repetition Chapter 6 12/06/16 & 12/07/16 1 1
Introduction to Programming
Building Java Programs
Building Java Programs
Truth tables: Ways to organize results of Boolean expressions.
Truth tables: Ways to organize results of Boolean expressions.
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Truth tables: Ways to organize results of Boolean expressions.
Building Java Programs
Building Java Programs
Presentation transcript:

Two examples of Problem Solving in Programming H. Chad Lane University of Pittsburgh CS7: Introduction to Programming

Solving “Small” Programming Problems Always use an example to guide you. Ask yourself questions, try to make observations about your own execution of the task. Think about what a program would need in order to do the same thing.

In-a-row Problem Statement Write a program that reads in numbers until the same number is typed twice in a row. Modify it to go until three in a row are typed. Modify it so that it first asks for “how many in a row should I wait for?” and then goes until some number is typed in that many times. Note: the numbers must be in a row.

Phase I: 2 in a row Example: 3, keep going? Of course. Why? 8, keep going? yes. Why? 14, keep going? yes. Why? 14, keep going? no. Why? IT MAY SEEM OBVIOUS, BUT THIS IS WHAT MUST BE UNDERSTOOD TO WRITE A PROGRAM

Important questions Which two values do you compare to find out if you need to keep going? –current number versus previous number What must be true in order to stop? –they must be equal.

Pseudocode for 2-in-a-row lastone = 0 current = -1 while (lastone != current) { lastone = current read current } lastonecurrent USER INPUT: PROGRAM COMPLETE

Java Version (full version, w/comments on the code web page) class Inarow { public static void main (String[] args) { int lastone = -1, current = -2; System.out.println("Please type integers.."); // will be true to start while (lastone != current) { lastone = current; current = Console.in.readInt(); } }//end main() }//end class

Going to 3-in-a-row 2-in-a-row just compared previous and current. To use this strategy for 3 in a row, we’d need another variable (previous previous) And the condition would become more complicated. A better solution is to keep a counter for how many in a row we’ve seen.

Example Looking for 3 in a row now: 7, count = 1, keep going? Why? 12, count = 1, keep going? Why? 12, count = 2, keep going? Why? 9, count = 1, keep going? Why? 8, count = 1, keep going? Why? 8, count = 2, keep going? Why? 8, count = 3, keep going? Why?

Important Observsations When does the loop stop now? –When the count reaches 3 –Loop while the count is less than 3 When do we increment? –When current equals previous When do we reset the counter? –When current is different than previous –Reset to 1 (always have 1 in a row)

Pseudocode for 3-in-a-row lastone = 0 current = -1 count = 1 while (count < 3) { lastone = current read current if (current == lastone) increment count else count = 1 } count

Java version of 3-in-a-row (full version w/comments on course web page) class Inarow { public static void main (String[] args) { int lastone=-1, current=-2, count=1; System.out.println("Please type integers.."); while (count < 3) { lastone = current; current = Console.in.readInt(); if (current == lastone) count++; else count = 1; } }//end main() }//end class

Going to n-in-a-row Minor change to 3-in-a-row code. Just replace 3 with a new variable whose value is provided by the user. What is a good name for this variable? –it’s job is to hold the number in a row the user is looking for. –we’ll call it “numrepeats” (many good alternatives)

Java version of n-in-a-row (full version w/comments on course web page) class Inarow { public static void main (String[] args) { int lastone=-1, current=-2, count=1, numrepeats; System.out.println(“How many in a row?"); numrepeats = Console.in.readInt(); System.out.println("Please type integers.."); while (count < numrepeats) { lastone = current; current = Console.in.readInt(); if (current == lastone) count++; else count = 1; } }//end main() }//end class

THMs Thinking about desired program behavior can really help. Go slow, ask questions, make observations. You can “program” a whole lot without a computer. The problem sits at the center of this process, not Java (or any other language).

Twenty-one Pickup Full example in Java By Dissection, section 4.9 (pp ) Problem Statement: Twenty-one pickup is a two-player game that starts with a pile of 21 stones. Each player takes turns removing 1, 2, or 3 stones from the pile. The player that removes the last stone wins. Play a game.

Questions to answer Does the computer play? –yes, computer vs. human user What will the interface be like? –could go graphical, but we’ll stick with text Play many games, or just one? –just a single game

High-level Analysis of Game Think about steps you do in a real game: 1.get player 1’s choice 2.if stones left, get player 2’s choice 3.if stones left, keep playing (goto 1) To write this as an algorithm, we’ll need: –to reduce the stones after each pickup –loop while the game is not over –print instructions & outcome

Top-level Pseudocode print instructions create initial pile of 21 stones while (there are stones left) { get the user’s move (1, 2, or 3) if (there are stones left) get the computer’s move (1, 2, or 3) } display winner

Method for User’s move Get user’s move: –parameter: # stones in pile –result: new # stones in pile –job: reduce pile by # user specifies static int playerMove(int numberOfStones)

Helper method: getUserMove() called by playerMove() method handles errors, returns 1, 2, or 3 for sure. What can go wrong? –user might give # less than 1 or bigger than 3. –user might choose more stones than are available.

Method for Computer’s move Get user’s move: –parameter: # stones in pile –result: new # stones in pile –job: reduce pile by # computer chooses static int computerMove(int numberOfStones)

Pseudocode for getUserMove() prompt for user’s next move read (int) choice from console while (choice is not legal) { prompt user again read (int) choice from console } return # of stones to remove

Big Picture so far playerMove() –calls getUserMove(), gets 1, 2, or 3 back. –returns new # of stones in pile. computerMove() –picks 1, 2, or 3 (somehow – randomly?) –returns new # of stones in pile

More Questions How can we tell if there are stones left? –numberOfStones variable > 0 How can we determine who won the game? –whoever moved last –keep a boolean variable to remember

Main() public static void main(String[] args) { printInstructions(); int numberOfStones = 21; boolean playerMovedLast = false; while (numberOfStones > 0) { numberOfStones = playerMove(numberOfStones); playerMovedLast = true; if (numberOfStones > 0) { numberOfStones = computerMove(numberOfStones); playerMovedLast = false; } if (playerMovedLast) System.out.println("Congratulations, you won."); else System.out.println("Better luck next time."); } CREATE THE PILE STONES REMAIN TRUE NOW BUT NOT NOW

playerMove() static int playerMove(int numberOfStones) { int move = getUserMove(numberOfStones); numberOfStones = numberOfStones - move; System.out.println("There are " + numberOfStones + " stones remaining."); return numberOfStones; }

getUserMove() static int getUserMove(int numberOfStones) { System.out.println("Your move - how many stones" + " do you wish to remove?"); int move = Console.in.readInt(); while (move > numberOfStones || move 3) { if (numberOfStones >= 3) System.out.println("Sorry," + " you can only remove 1 to 3 stones."); else System.out.println("Sorry, you can only " + "remove 1 to " + numberOfStones + " stones."); System.out.println("How many stones" + " do you wish to remove?"); move = Console.in.readInt(); } return move; }

computerMove() static int computerMove(int numberOfStones) { int move; if (numberOfStones <=3) { move = numberOfStones; } else { move = numberOfStones%4; if (move == 0) move = 1; } numberOfStones = numberOfStones - move; System.out.println("The computer removes " + move + " stones leaving " + numberOfStones + "."); return numberOfStones; } TAKE THE WIN ONE OF MANY OPTIONS

Summary Thought about how we play a game for real. Broke it down into steps. top-down Wrote methods to handle the non-trivial parts. Although we did not talk about testing, it is a critical aspect to this process (sec 4.9.4).