week91 apcs-ab: java problem solving november 1, 2005

46
week9 1 APCS-AB: Java Problem Solving November 1, 2005

Upload: betty-fox

Post on 04-Jan-2016

229 views

Category:

Documents


3 download

TRANSCRIPT

week9 1

APCS-AB: Java

Problem Solving

November 1, 2005

week9 2

How you problem solve

• What do you do when faced with a new problem?

• For the logic puzzles yesterday, how did you figure out a solution?

• For the Scheme and Java projects in Q1, how did you come up with a good solution?

week9 3

Today

• We are going to look at a general method of problem solving You can compare this with what you already

do

• This may or may not improve what you already instinctively do, and if nothing else, it might help you help a friend who’s struggling with a problem

week9 4

Problem Solving – 4 phases

• Understanding the problem

• Devising a plan

• Carrying out the plan

• Looking back (testing solution)

From “How to Solve It” By G. Polya

week9 5

Understanding the problem

• Read it – do you understand what it is asking?

• Think about what it is asking you to do What are the inputs to the problem? What are the outputs of your solution? Are there any conditions?

• Draw a figure, show a sample of the problem.

week9 6

Devising a plan

• Have you seen a similar problem before? Or have you seen something like this problem in a different form?

• Can you restate the problem?• Can you think of a more general problem? A more special

problem? Can you solve part of the problem?

• Draw out what you think might work• Think about and name the variables you might need• Think about what kind of conditional structures might be

suited to the problem

• Pseudocode your plan

week9 7

Carrying out the plan

• Program your plan, checking each step.

• Is that line of code correct?

• Is it doing what you want/expect it to?

week9 8

Looking back (testing solution)

• Examine your solution • Make sure that you get the expected output

• Step through your program and trace its state at each step Follow through your code and make sure you didn’t

stop earlier, and that your variables get the value that you expected

For problems with loops, draw a grid and trace each step through the code

week9 9

Method Level Problem Solving• Understanding the problem

What exactly does this method need to do?• What are the inputs to the problem?• What are the outputs of your solution?

Are there any conditions?• What must be true before this method starts (pre-

conditions) Could assert they are true before the method continues:

• What will be true when this method finished (post-conditions)

week9 10

Method Level Problem Solving

• Devising a plan Is there a related method we could modify? PSEUDOCODE

• Identify and name variables, Think about the conditional structures you need

• lay out the steps the method needs to do

• Carrying out the plan Turn the pseudocode into Java code

• Looking Back (testing solution) Step through your program. Do the pre-conditions hold? Do the

post-conditions?

week9 11

APCS-AB: Java

Problem Solving cont’d

November 2, 2005

week9 12

Codebreaker Example

• Let’s look at how we solved the odd character substitution problem:

• For this method you are going to replace every other letter by its “pair” letter. A pair letter is the letter that is 13 letters away from the letter (like a-n, b-o, c-p, etc).

a. For example, “string” becomes “fteiag”

• Let’s try to apply the strategy from today to this problem• Then let’s look at one solution I received that didn’t quite work

and see if we can figure it out what went wrong

week9 13

Odd Character Substitution

• Understanding the problem

• Devising a plan Have we done anything in the past that may

help us with this? Is there any previously written code that we

can re-use?

• Carrying out the plan

• Looking back (testing solution)

week9 14

A Buggy Approach

int

b

int

a

String

x

String

z

String

y

String

c

start 1 0 (param)

computer

x.substring(0, b)

cx.substring(a, b)

c“”

begin loop

(x.length() - z.length() >=

1)

(x.length() - z.length() >= 1)

(x.length() - z.length() >= 1)

… DONE

week9 15

What happened?

• What was the error with the code?

• What else did we notice about the code that could have been better?

week9 16

Problem Solving

• So far we have looked at problem solving at the method level

• What about at the higher levels? The Object level The Project level (multiple objects)

week9 17

Project Level Problem Solving

• Program/project level: HIGHEST level• Essentially making a model, deciding what

parts are related What are the key components of this problem? What kind of information needs to be known?

What objects do you need to do the task? How do they interact? Where is your key data going to be stored?

week9 18

Problem Solving

• Lay out the big picture (high level design)

• Break that into objects (object level design)

• Break each object into components (method level design)

week9 19

Sudoku Task

• Represent programmatically Sudoku

• Understanding the problem• Devising a plan

• Carrying out the plan• Looking back (testing solution)

week9 20

APCS-AB: Java

Arrays

(related information in Chapter 7 of Lewis & Loftus)

November 2, 2005

week9 21

Homework Preview

• One Dimensional Arrays: Lights Out! Maybe a grade program with analysis For practice…before moving on to…

• Two Dimensional Arrays: Sudoku

week9 22

Grouping objects

• Fixed-sized collections When you know in advance how many items will be

stored in a collection (and that stays fixed for the life of the collection)

A fixed-sized collection is an array• It’s kind of like a tray of cups – each cup can hold an object

or a primitive data type• Note: the array itself is an object

• Flexible-sized collections When you don’t know in advance how many items

you will need to store Will go into more details about these in a few weeks

week9 23

Arrays

• An array is a group of variables (called elements or components) containing values that all have the same data type

• To refer to a particular element in an array, use the array’s name and the position number of the element in the array

54

32

2

9

4

3453

34

3

-423

int array called c

c[0]

c[3]

c[4]

c[5]

c[6]

c[7]

c[8]

c[1]

c[2]

week9 24

Anatomy of an array

• Array names are the same as any other variable name

• An array with 9 elements (or variables)

• First element has index zero (the zeroth element)

• ith element of array c is c[i -1]

• Index must be a positive integer (or an integer expression that can be promoted to an int)

54

32

2

9

4

3453

34

3

-423

int array called c

c[0]

c[3]

c[4]

c[5]

c[6]

c[7]

c[8]

c[1]

c[2]

week9 25

Advantages to using arrays

• It is easy to access individual items in an array (and it’s efficient)

• Arrays are able to store objects or primitive type values (int, double, float, etc) (We’ll see later that the flexible-sized

collections can only store objects)

week9 26

Declaring and creating arrays

• Array objects occupy space in memory. All objects in Java must be created with a keyword new

• When you declare an array you must tell Java the type of the array elements and the number of the elements that will appear in the array

• Example declaration for an integer array called hourArray:

int hourArray[] = new int[24]; // declares and creates an array to hold 24 int elements

week9 27

An array

hourArray

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

:int[ ]

week9 28

How do we fill an array?

• All values are initially set to zero/null when we initialize an array

• One way to fill the array is to use an array initializer, a comma-separated list of expression enclosed in braces: when you declare it

int n[] = {10, 23, 34, 235, 234};

The array length is automatically determined by the number of elements in the initializer list

week9 29

Class Exercise

• Write code to declare and initialize an array to hold the months of a year

• Write code to declare and initialize an array to hold the number of days in each month of the year

week9 30

How else do we fill an array?

• Arrays and for-loops go together like peanut butter and jelly!

• We could use a for loop and access each array element to set a value to it:int myArray = new int[10];for(int i =0; i < myArray.length; i++){

myArray[i] = 5 * i; } Note: unlike the String class when we access the length of the array we

are not calling a method, rather we are accessing one of the array’s instance variables

week9 31

Exercise

• Suppose we wish to print out the names and lengths of each of the months

week9 32

Mistakes

• It is not uncommon to make a programming mistake that causes the bounds of a loop to be mis-defined and the loop index variable to stray beyond the range of the array.

• For example, what if in your for loop you wrote:for(int i = 0; i <= array.length; i++){

System.out.println(array[i]);

}

week9 33

Passing data to methods

• We’ve all passed values to methods to be used in calculation (parameters)

• We’ve returned item back from methods

• But how does this all work?

week9 34

Pass by Value

• When we pass an argument by value to a method, a copy of the argument’s value is made and passed to the called method

public void method1(){int x = 5;System.out.println(“X is: “ + x);method2(x);System.out.println(“X is: “ + x);

}public void method2(int param){

param = 20;}

week9 35

Pass by Value

x

int

int x = 7;

00000111

Declare an int value and assign it the value ‘7’. The bit pattern for 7 goes into the variablenamed x.

z

int

void go(int z) { } Declare a method with an int parameter named z.

x

int

00000111

z

int

00000111

Copy of x Call the go() method, passing the variablex as the argument. The bits in x are copied, and the copy lands in z.

go(x);

week9 36

Pass by reference• When we pass by reference, the caller gives the called method the

ability to access the caller’s data directly and possibly modify that data (it is not copied) -- Basically a pointer (the address) to the object is given to the method

public void method1(){int array[] = {1, 2, 3, 4, 5};//print array – what would it showmethod2(array);//print array – what would it show?method3(array[2]); //what is array[2] before this call? After it?

}public void method2(int param[]){

for(int i = 0; i< param.length; i++){param[i] *=2;

}}public void method3(int element){

element *= 4;}

week9 37

Pass by reference

hourArray

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

:int[ ]

array2

int hourArray = new int[24];changeArray(hourArray);

void changeArray(int array2[]) { }Ptr is copied

week9 38

Creating an array of objects

Dog pets[ ]; //declare a Dog array variable

pets = new Dog[7]; //create the array

note, we have an array of Dog references, but no actual Dog objects! Need to make the Dog objects…

pets[0] = new Dog(“Fido”);

pets[1] = new Dog(“Goldy”);

week9 39

The pets array

0 1 2 3 4 5 6 7

Fido Goldy

pets

What does pets[0].bark(); do?

week9 40

And Now…

Entering Multiple Dimensions!

week9 41

2D arrays

• Used to represent tables of values in rows and columns

0 1 2 3 4 5 6 7 8

0

1

2

week9 42

2d arrays in Java

• Actually are one-dimensional arrays whose elements are also one-dimensional arrays

• Usually referred to as rows by columns So the example from the last slide is a 3-by-9

array To refer to an element is: a[row][col]

week9 43

Array Initializers for 2d arrays

• int b [ ][ ] = { {1,2}, {3,4}} Grouped by rows in braces

• int b [ ] [ ] = {{ 1, 2} , { 3, 4, 5}} Creates an array with a row of two elements

and a row of three elements Row 0 is a 1-d array with two elements Row 1 is a 1-d array with three elements

0 10

11 2

3 4

0 10

11 2

3 4 5

week9 44

Array-Creation Expressions

• To create a square array:int b[ ] [ ];b = new int [3] [4];

• To create an array in which each row has a different number of columns:

int c [ ] [ ];c = new int[2][]; //create 2 rowsc[0] = new int [5]; // row 0 has 5 columnsc[1] = new int [3]; // row 1 has 3 columns

week9 45

And remember: for loops and arrays go together!

• For a 2d array, we will need nested for loops:

for(int row = 0; row < array.length; row++){for(int col = 0; col < array[row].length; col++){

System.out.print(array[row][col] + “ “);}System.out.println();

}

week9 46

Homework

• One Dimensional Arrays: Lights Out! Maybe a grade program with analysis

• Two Dimensional Arrays: Sudoku