two examples of problem solving in programming h. chad lane university of pittsburgh cs7:...

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

Upload: marvin-shepherd

Post on 17-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Two examples of Problem Solvingin 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 = 0current = -1while (lastone !=

current) {lastone = currentread current

}

lastone current

3 8 6 14 14

-1

3

8

6

14

3

8

6

14

14

-1 0

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-rowlastone = 0current = -1count = 1while (count < 3) {

lastone = currentread currentif (current == lastone)

increment countelse

count = 1}

3 8 8 14 14 14

count

1

1

2

1

2

3

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.114-124)

• 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 instructionscreate initial pile of 21 stoneswhile (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 moveread (int) choice from consolewhile (choice is not legal) {

prompt user againread (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 < 1 || 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).