• No results found

Learning objectives

N/A
N/A
Protected

Academic year: 2021

Share "Learning objectives"

Copied!
18
0
0

Bezig met laden.... (Bekijk nu de volledige tekst)

Hele tekst

(1)

Algorithmic Thinking and Structured Programming (in Greenfoot)

2017 Renske Smetsers-Weeda & Sjaak Smetsersc 1

Contents

Introduction 1

Learning objectives 1

Instructions 1

Theory 2

3.1 Using sub-methods . . . 2

3.2 Decomposing problems . . . 3

3.3 Code Alignment . . . 3

3.4 Logical Operators . . . 4

3.5 Loading a world . . . 4

3.6 Saving a world . . . 5

3.7 Using Strings . . . 5

Challenges 7 3.1 Using sub-methods . . . 7

3.2 Practicing with logical operators . . . 8

3.3 Lay an egg in each nest . . . 9

3.4 No double eggs . . . 9

3.5 Walk through a tunnel . . . 10

3.6 Walk to nest, climbing over any fences . . . 11

3.7 Walk around a fenced area . . . 11

3.8 Find the nest by following a trail of eggs . . . 12

3.9 Simple Maze . . . 12

3.10 Complex Maze . . . 13

3.11 Dodo goes wild . . . 14

Reflection 16

Saving and Handing in 17

1Licensed under the Creative Commons Attribution 4.0 license:https://creativecommons.org/licenses/by/4.0/

(2)

Introduction

In the previous assignments you have become acquainted with Greenfoot and algorithmic thinking.

You are able to read, write and debug your own code. You also practiced devising generic solutions and implementing them. In this assignment you will learn how to design code as separate components:

making it easier to write, test and re-use your solution. Splitting problems into smaller parts makes it easier to solve complex problems.

This assignment’s goal is: decompose problems into manageable parts.

Learning objectives

After completing this assignment, you will be able to:

• decompose a (complex) problem into subproblems;

• apply decomposition in flowcharts and code by identifying sub-methods;

• design, write and test sub-methods separately;

• describe the role of a method’s result type and parameter(s);

• re-use existing sub-methods and solutions;

• create conditional expressions by combining logical operators;

• apply nesting as a strategy for solving problems;

• design generic solutions;

• assess and evaluate your solution.

Instructions

In this assignment you will carry on with your code from the previous assignment. Make a copy of that scenario to continue working with. To make a copy follow the next steps:

• Open your scenario from the previous assignment.

• In the Greenfoot menu at the top of the screen, select ’Scenario’ and then ’Save As ...’.

• Check that the window opens in the folder where you want to save your work.

• Choose a file name containing your own name(s) and the current assignment number, for exam- ple:

Asgmt3_John.

Note: We recommend that you to continue working with your own code. If it is absolutely impossible to carry on working with your own code from the previous assignment, then you may download a new scenario from the course website2.

Throughout the assignment you will also need to answer some questions. The following must be handed in:

• All flowcharts: use pencil and paper, or go to https://www.draw.io/;

2http://course.cs.ru.nl/greenfoot/

(3)

• Your code: the fileMyDodo.javcontains all your code and must be handed in;

• The reflection sheet: complete and hand it in.

You must discuss all other answers with a programming partner. Jot down a short answer on (the assignment) paper.

There are three types of challenges:

Recommended. Students who need more practice or with limited programming experi- ence should complete all of these.

Mandatory. Everyone must complete these.

Excelling. More inquisitive tasks, designed for students who completed 2 star tasks and are ready for a bigger challenge.

Students who skip 1-star challenges should complete all 3-star challenges.

A note in advance:

• In this assignment you may only make changes to theMyDodoclass;

• You may use methods from theMyDodoorDodoclass, not from theActorclass;

• Teleportation is not permitted: if Mimi needs to get somewhere, she must walk there!

Theory

Theory 3.1: Using sub-methods

If a particular set of instructions are repeated several times, it can be useful to place them in a sub- method. When the set of instructions is required, only the sub-method needs to be called. This saves a lot of error-prone typing, and moreover, makes testing and re-use easier.

Example

To take a step backwards, Mimi has to:

• turn 180 degrees (by calling:turnRight( )andturnRight( )),

• move, and then

• turn 180 degrees again (again by calling:turnRight( )andturnRight( )).

For Mimi to take several steps backwards, would lead to a repetition of lots of steps. In this case, it would be better to write a sub-method calledstepOneCellBackwards( ).

/**

* Move one cell backwards

*

* <p>Initial situation is same as final situation.

*

*/

public void stepOneCellBackwards( ) { turnRight( );

turnRight( );

move();

turnRight( );

(4)

turnRight( );

}

Now, to call this sub-method use:stepOneCellBackwards( );. See the code below.

public void methodUsingStepOneCellBackwards( ) { // part of a method

stepOneCellBackwards( );

// rest of a method }

Theory 3.2: Decomposing problems

A complex problem (and its solution), can be made easier when you break this down into several smaller problems. In code, these steps are written in asub-method, which can be designed and tested separately (see Theory 3.1). The sub-methods are then combined together to create a complete solution to the entire problem at hand. The process of breaking a large problem into smaller problems is called decomposition.

Figure 1: Decomposing a problem into parts and tackling each separately Decomposition is used in the following cases:

• complex problem: when a problem or set of instructions is so complex that it would be better (less error-prone) to design, develop and test them separately.

• repetition: if a particular series of steps repeat;

• many steps: when an algorithm becomes unclear and hard to follow by numerous amount of detailed steps (for example: more than seven).

• cohesive set of instructions: if a set of instructions form a fairly independent and complete set or module (which may in the future could be re-used elsewhere);

By means of decomposition the code becomes easier to understand, test, re-use modify, and extend.

(5)

Theory 3.3: Code Alignment

Logical and consistent use of style makes code more readable. Style conventions exist, just like naming conventions. Indenting is not required for the program to work and has no effect on how the program is executed. However it is a good programming practice. Examples are indenting blocks of code and consistently placing curly brackets. Greenfoot can help you align your code by using Ctrl-Shift-I.

Here is an example of code that is not aligned:

public void move() { if ( canMove() ) { step(); } else { showError( "I’m stuck!" ); //

prints to the console. } }

Here is an example of aligned code:

public void move( ) { if ( canMove( ) ) {

step( );

} else {

showError( "I’m stuck!" ); // prints to the console.

} }

See http://google-styleguide.googlecode.com/svn/trunk/javaguide.html for a complete list of style and naming conventions.

Theory 3.4: Logical Operators

The ’AND’ (in code: &&), the ’OR’ (in code: ||) and the ’NOT’ (in code: !) are called logical operators.

You have already seen (and used) a few of them. These are useful in decisions, and can be combined (withbooleanmethods) to make specific complex conditional statements.

Operator Meaning Example

&& AND facingNorth( )&& fenceAhead( )

|| OR fenceAhead( )|| borderAhead( )

! NOT !fenceAhead( )

Combining logical operators

You can combine logical operators to create more complex conditional expressions. As a result it can simplify your code. However, combining logical operators, especially with a negation (the NOT) can be tricky. In addition, you should use parentheses to be clear on what belongs together.

Expression Equal to Meaning

!( A && B ) !A || !B Is true as soon as either A or B is not true

!( A || B ) !A && !B Is only true if neither A or B are true

Examples

• NO (hitting OR kicking) ⇒ !(hitting || kicking)⇒ !hitting && !kicking. Which means (obviously), you may do neither of them.

• NO (skirt AND pants) ⇒ !(skirt && pants)⇒ !skirt || !pants.

Which means, you can have either of them, but not both of them (that would look silly).

(6)

Theory 3.5: Loading a world

To load a particular world each time you compile, follow this example. In the next steps we will load the world ’worldEmptyNestsTopRow’:

1. Right-click on ’Madagaskar’ in the class diagram.

2. Select ’Open Editor’.

3. Near the top you will find the following code fragment:

Figure 2: Opens an empty world (initial configuration)

4. Replace the filename (the part in front of ’.txt’) with the world you wish to open (for example:

’worldEmptyNestsTopRow’). It should then look like this:

Figure 3: Opens ’worldEmptyNestsTopRow’ file

Theory 3.6: Saving a world

To save a world, follow the next steps:

1. Right-click on an empty cell in the world.

2. Select ’saveToFile( )’.

3. The scenario has now been saved to a new file called ’saved.txt’, which can be found in the

’worlds’ folder.

Theory 3.5 describes how to load a particular world each time you compile.

Theory 3.7: Using Strings

In Java, text is called aString. Stringis atype, just likeintandboolean. Methods can have aString (or text) as a parameter. You have already used this to print tekst to a console (see also Theory 1.14).

To use a particular text in your program, you need to use quotation marks.

• define aStringas follows:String text1 = "Hello";

• use aStringas a parameter:

String textGreeting = "Hello"; System.out.println ( textGreeting );

(7)

This is the result:

• glue twoStringtogether (calledconcatenate) using ’ +’.

String textGreetingMimi = "Hello " + "Mimi";

System.out.println ( textGreetingMimi );

This is the result:

• also concatenate aStringand anintvariableint nrOfEggsFoundusing ’ +’.

int nrOfEggs = 5;

String textIFound = "I have found ";

System.out.println ( textIFound + nrOfEggs + " eggs today" );

This is the result of the compliment with a smiley is:

The methodshowCompliment( String compliment )has aStringparameter with the name ’com- pliment’. The following two code examples have exactly the same result. The result is shown in figure 4.

showCompliment( "Congradulations!" );}

and

String textCongradulations = "Congradulations!";

showCompliment( textCongradulations );}

Figure 4: Output for either piece of code

(8)

Challenges

Please read Theory 3.1: Using sub-methods.

Please read Theory 3.2: Decomposing problems.

Challenge 3.1: Using sub-methods

In challenge 2.5 you wrote a methodboolean grainAhead( )which tested whether there is a grain in the cell in front of Mimi (see flowchart 5).

Figure 5: Flowchart forgrainAhead

Your next challenge is to use sub-methods to clean up the code in the method boolean grainAhead( ).

a) Write a methodstepBack ( )which makes Mimi take one step back, facing in the original direc- tion. Also add JavaDoc comments.

b) Replace the circled code by a call ofstepBack, according to the following flowchart:

(9)

Figure 6: Flowchart forgrainAheadusing submethodstepBack c) Test your program.

d) Can you clean up any more code in thegrainAheadmethod?

e) Test your program after any (minor) modifications.

Please read Theory 3.3: Code Alignment.

Please read Theory 3.4: Logical Operators.

Challenge 3.2: Practicing with logical operators

The logical operators ’AND’ (in code: &&), the ’OR’ (in code: ||) and the ’NOT’ (in code: !) are often misinterpreted, especially when they are combined. That’s why we’re going to practice using them.

1. A sign on the bus says: ”Seating 15 Standing 3 OR 13 seated + 1 wheelchair”. Complete the follow- ing two statements:

• More specifically: ” (seated EQUALS 15 AND standing EQUALS 3)OR ...”

• Translating this to code: ” (seated == 15 && standing == 3)...”

2. What do you want for dinner? Insert brackets where appropriate and translate to an appropriate expression in code. ”French fries and mayo or ketchup and salad”.

3. Dogs and cats together results in a fight. Remove the brackets (parentheses) in the following statement: ”NOT (dogs AND cats)”, and adjust the statement so that it still means the same thing.

4. We can go outside if it’s not raining nor hailing. Remove the brackets (parentheses) in the follow- ing statement: ”NOT (raining OR hailing)”, and adjust the statement so that it still means the same thing.

(10)

Please read Theory 3.5: Loading a world.

Please read Theory 3.6: Saving a world.

Challenge 3.3: Lay an egg in each nest

Your mission is as follows:

”Mimi walks to the edge of the world. If she finds a nest, she lays an egg in it.”

Make sure your algorithm is generic. It must work in any similar world, so also if one of the nests is moved one position to the right or left, or an additional nest is added.

a) Open the ’worldEmptyNestsTopRow’ world.

b) Fill in the empty slots in the flowchart in figure 7.

Figure 7: Flowchart for walking to the edge of the world and laying an egg in each nest

c) Write the corresponding code (and comments) for your method. Also properly align your code (see Theory 3.3).

d) Test your method by right-clicking on Mimi in the world, and then selecting the method. Tip:

Theory 3.5 describes how to load a particular world each time you restart the scenario.

e) Does the program work as expected? There’s a problem with the flowchart. Can you find it?

f ) Propose a correction for the flowchart and change the code accordingly.

g) Test again.

You have now written anif..then..else..statement nested in awhileloop.

(11)

Challenge 3.4: No double eggs

The next mission is:

”Mimi walks to the edge of the world. If she finds a nest without an egg, then she must lay an egg.”

Obviously, Mimi should only lay an egg if there is no egg there yet.

a) Open the ’worldEmptyNestsTopRow’ world and place an egg in a few nests. Tip: Theory 3.5 describes how to load a particular world each time you want to run your code.

b) Describe the initial and final situations.

c) Sketch a suitable flowchart.

d) Write and test the corresponding code (and comments) for your method. Also properly align your code (see Theory 3.3).

You have now used either nesting or logical operators to test for certain conditions.

Challenge 3.5: Walk through a tunnel

Your mission is to teach Mimi to walk through a tunnel of fences (see figure 8), and stop when she gets clear of the tunnel (see figure 9).

Figure 8: Initial situation Figure 9: Final situation First we break the problem down into sub-problems which can each be tackled separately:

Figure 10: Decomposing the problem into sub-problems which can be tackled separately

(12)

a) Write and test a sub-method which checks whether Mimi has a fence to her left side.

b) Write and test a similar sub-method which checks whether Mimi has a fence to her right side.

c) Using these sub-methods, write and test methodvoid walkThroughTunnel( ). You can use ’world- Tunnel’ file for testing the world (Theory 3.5 explains how to load the world).

You have now applied abstraction to break a large problem down into smaller parts. Using the divide-and-conquer principle, you have designed, implemented, and tested sub-problems (fenceOnRight

( )andfenceOnLeft ( )). You used your solution to the sub-problems inwalkThroughTunnel( )and tested your program as a whole.

Who knows, maybe you can use one of your methods (such asfenceOnRight ( )) in a following challenge. That would be convenient, after all, you’ve tested the methods and are convinced they work properly. This is calledmodularization.

Please read Theory 3.7: Using Strings.

Challenge 3.6: Walk to nest, climbing over any fences

Mimi is looking for her nest. On her way there, she must climb over any fences she comes across. If she finds her nest, she should lay an egg in it and stop. If she reaches the end of the world before she finds her nest, she should stop and show a pop-up window with an appropriate error message.

Tips:

• Sketch a high-level flowchart first.

• It may be useful to have a look back at challenge 2.9 where you designed code for walkToWorldEdgeClimbingOverFences( ).

• Load world ’worldFencesAndNest’.

• For an error pop-up, use:showError( String message)

Challenge 3.7: Walk around a fenced area

Your mission is to teach Mimi to walk around a fenced area.

a) Open the ’worldFencedArea’ world.

b) Determine the initial and final situations. Come up with a suitable algorithm. Tip: To avoid Mimi walking around the fenced area for ever, we will assume that there is an egg in the very last square on her route: if she finds the egg she will know that she’s done.

(13)

c) Write the corresponding methodvoid walkAroundFencedArea( )which makes Mimi walk around the fenced area. Also add comments.

d) Compile and test your method. Also check if your program works with a larger fenced area.

e) Test in which initial situations your program works. If necessary, adjust your description of the initial situation.

f ) Also test if your method works in another world, such as: ’worldOtherFencedArea’. If necessary, modify your algorithm (and thus flowchart and code) so that it also works in this world.

Figure 11: Another fenced area

You have now written a generic method with which Mimi can walk around any fenced area. You applied modularization by re-using (existing and tested) methods.

Challenge 3.8: Find the nest by following a trail of eggs

Your mission is to help Mimi follow a trail of eggs until she reaches her nest (see world: ’worldEggTrail- ToNest’).

Figure 12: Task: follow the egg trail until nest Break the problem down into more manageable sub-problems.

a) Draw a high-level flowchart showing which sub-methods you need to design and write.

b) For each sub-method:

• Choose an appropriate name (and return-type);

• Determine the initial and final situations;

• Write and test.

c) Using these sub-methods, write and test your solution as a whole.

d) Test if your method works for another trail of eggs, for example in the ’worldEggTrailToNest2’

world. You may discover that you still need to make some changes.

e) Assess your approach. What went well? What could you do better next time?

(14)

Challenge 3.9: Simple Maze

Can you help Mimi find her way to her nest through the maze to her nest? Give Mimi a compliment when she finds her nest. Of course, your solution has to be generic: Mimi has to be able to find her way through any arbitrary maze.

You may assume the following:

• The world is surrounded by a fence.

• There is exactly one nest.

• The nest is located next to a fence.

• A route to the nest exists.

• At most one route exists (there are no dead-ends, and no ’islands’ of fences).

• From the initial position, Mimi can only walk in one direction.

Write a method helping Mimi find her nest:

a) Come up with a suitable algorithm and draw a high-level flowchart.

b) Design, implement, and test sub-methods for your algorithm.

c) Write the code for your solution and test it. Also test using the following mazes:

• ’worldMazeLevel1a’.

• ’worldMazeLevel1b’.

• ’worldMazeLevel1c’.

d) Assess your program. Which improvements can you suggest? You don’t necessarily need to im- plement them, just list them.

Challenge 3.10: Complex Maze

Can you help Mimi find her way to her nest through a complicated maze? Give Mimi a compliment (using a pop-up) when she finds her nest. Of course, your solution has to be generic: Mimi has to be able to find her way through any arbitrary maze.

(15)

You may now assume the following:

• The world is surrounded by a fence.

• There is exactly one nest.

• The nest is located next to a fence.

• A route to the nest exists.

• There are no ’islands’ of fences.

Write a method helping Mimi find her nest:

a) Come up with a suitable algorithm and draw a high-level flowchart.

b) Design, implement, and test sub-methods for your algorithm.

c) Write the code for your solution and test it. Also test using the following mazes:

• ’worldMazeLevel2a’.

• ’worldMazeLevel2b’.

• ’worldMazeLevel2c’.

d) Make your own maze. Test a classmate’s program with it.

e) Exchange your solution with a classmate and give each other feedback.

Hint: In one of the previous exercises you used a ’trick’ to determine if Mimi had been in that spot before.

Challenge 3.11: Dodo goes wild

Now on to a more challenging algorithmic thinking puzzle. Suppose we have a methodjumpToEnd( ). This makes Mimi repeatedly take steps until she cannot move any further (either a fence is blocking her path or she has reached the end of the world):

public void jumpToEnd( ) {

while ( ! borderAhead( ) && ! fenceAhead( ) ){

step( );

} }

ThejumpToEnd( )method is called in the methodgoWild( ).

(16)

Figure 13: Flowchart for methodgoWild( )

The scenario is executed by runninggoWild. Three different initial configurations are shown below:

Figure 14: A Figure 15: B Figure 16: C

a) Does Mimi stop for configuration A? If so, how often was thejumpToEnd( )method called?

b) Does Mimi stop for configuration B? If so, how often was thejumpToEnd( )method called?

c) Verify your answers by adding print statements to the code. (See Theory 1.14 and Theory 3.7 on how to print to the console).

d) What happens with the program if Mimi doesn’t stop?

e) Suppose we want to Mimi to find the egg in configuration C. We can do this by placing fences in the world, at carefully selected locations. You may not place a fence immediately next to the border. Place the fences in figure C such that you need no more than 5 fences for Dodo to find the egg after thegoWild( )method is called.

(17)

Reflection

In this assignment you practiced designing code as separate components, making it easier to write, test and re-use your solution. One of the most important steps in becoming good at anything is to evaluate and reflect on what you did and how it went:

Result

I know my solution works because . . . I am proud of my solution because . . . I could improve my solution by . . .

Method

My approach was good because . . . What I could do better next time is . . .

Fill the following table with smileys

indicating how things went. I can do it

I did it a bit but didn’t fully get it

I didn’t get it at all

I can describe an algorithm by drawing a high-level flowchart

I can identify sub-methods in an algorithm

I can design, write and test sub-methods separately

I can combine logical operators to create conditional expressions

I can design generic solutions

(18)

Saving and Handing in

You have just finished the assignment. Save your work! You will need this for future assignments. In the Greenfoot menu at the top of the screen, select ’Scenario’ and then ’Save’. You now have all the scenario components in one folder. The folder has the name you chose when you selected ’Save As ...’.

Handing in

Hand in the following:

• Your code: The java fileMyDodo.jav;

• Flowcharts: paste (photo’s of) your flowcharts in a Word document;

• The reflection sheet: complete and hand it in.

Referenties

GERELATEERDE DOCUMENTEN

According to the respondents, the standard that supervision of the participant and the body implementing the programme must be such that violation of one of the conditions of the

Yet this idea seems to lie behind the arguments last week, widely reported in the media, about a three- year-old girl with Down’s syndrome, whose parents had arranged cosmetic

These functionalities include (1) removal of a commu- nity from the data (only available on the top-most hierarchy level to avoid a mis-match between parent size and children

Based on the result that the participants referred to either leadership, organizational structure and reward systems, and/or characteristics and personalities of the

(c) (0.5 pts.) Explain why your results do not contradict a theorem, seen in class, stating that some American call options have optimal exercise time at maturity and, hence, cost

Belgian customers consider Agfa to provide product-related services and besides these product-related services a range of additional service-products where the customer can choose

[r]

\pIIe@code In this case the code inserted by the driver on behalf of the \Gin@PS@restored command performs a “0 setgray” operation, thus resetting any colour the user might have set