assignment 6: lists - radboud...

19
Assignment 6: Lists Algorithmic Thinking and Structured Programming (in Greenfoot) © Renske Smetsers-Weeda & Sjaak Smetsers Contents Introduction Learning objectives Instructions Theory . Object types and variables ............................................ . Calling a method from another class ..................................... . Lists ......................................................... . For-each Plan ................................................... . Average loop plan ................................................. Challenges . Walking through a list .............................................. . Java methods for lists .............................................. . Print coordinates and values of all eggs in a list .............................. . Print value of most valuable egg in a list ................................... . Print coordinates of most valuable egg in a list ............................... . Print average value of list ............................................ . Reversing a list .................................................. . Sorting a list: Selection sort ........................................... . Calculate distance ................................................ . Goto the most distant egg in the world ................................... . Re-factoring .................................................... Reection Saving and Handing in Licensed under the Creative Commons Attribution . license: https://creativecommons.org/licenses/by/4.0/

Upload: others

Post on 03-Feb-2020

13 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Assignment 6: Lists - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment6-student.pdf · Assignment 6: Lists Algorithmic Thinking and Structured Programming

Assignment 6: Lists

Algorithmic Thinking and Structured Programming (in Greenfoot)© 2017 Renske Smetsers-Weeda & Sjaak Smetsers1

ContentsIntroduction 1

Learning objectives 1

Instructions 1

Theory 26.1 Object types and variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26.2 Calling a method from another class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36.3 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46.4 For-each Plan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66.5 Average loop plan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Challenges 96.1 Walking through a list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96.2 Java methods for lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106.3 Print coordinates and values of all eggs in a list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116.4 Print value of most valuable egg in a list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136.5 Print coordinates of most valuable egg in a list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136.6 Print average value of list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136.7 Reversing a list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136.8 Sorting a list: Selection sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146.9 Calculate distance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156.10 Goto the most distant egg in the world . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156.11 Re-factoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15Reflection 17

Saving and Handing in 18

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

Page 2: Assignment 6: Lists - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment6-student.pdf · Assignment 6: Lists Algorithmic Thinking and Structured Programming

Lists Assignment 6

IntroductionLists are commonly used to store data that belongs together. Lists can comprise of almost anything.Think of the lists that you use in every day life: Shopping lists, homework lists, lists of favorite websites.In challenge 5.1 you wrote the a method to count all the eggs in the world: Dodo walks through theentire world and counts all the eggs she finds. However, there’s an even smarter way to look for andhatch eggs. For this, we will use a List. You could use a list to help a lazy Dodo hatch all the eggsin the world using the least amount of steps. Using a List gives you the opportunity to come up withsmarter algorithms. By having a list of all of the Egg objects in the world, you would be also have theircoordinates and their values at your fingertips (using getter methods).In this assignment you will first learn how to use a List to store variables. You will then learn howto do specific things with a list, like walk through its elements, swap elements, or sort the elements.Later you will learn how to use lists with object types such as Eggs. This will be helpful for Dodo’s racein the assignment that follows.

Learning objectivesAfter completing this assignment, you will be able to:

• declare and use List variables;• use Java Library Documentation to look for and use existing Java methods;• apply existing List methods, such as adding and removing elements from a list;• use a for-each-loop for traversing the elements of a list;• swap elements in a list.• sort objects in a list.• apply plans for calculating the average of a list of values;• explain what null means and what it is used for;• use a list to store both with primitive types (such as int, String)and object types (such as Egg).

InstructionsFor this assignment you will need:

• scenario ’DodoScenario6’: to be downloaded from the course website2.Throughout the assignment you will also need to answer some questions. The following must behanded in:• All flowcharts: use pencil and paper, or go to https://www.draw.io/;• Your code: the file MyDodo . jav contains all your code and must be handed in;• The reflection sheet: complete and hand it in.

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

Algorithmic thinking and structured programming (in Greenfoot) 1

Page 3: Assignment 6: Lists - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment6-student.pdf · Assignment 6: Lists Algorithmic Thinking and Structured Programming

Lists Assignment 6

You must discuss all other answers with a programming partner. Jot down a short answer on (theassignment) paper.There are three types of challenges:

Recommended. Students who need more practice or with limited programming experienceshould complete all of these.Mandatory. Everyone must complete these.Excelling. More inquisitive tasks, designed for students who completed 2 star tasks and areready 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 the MyDodo class;• You may use methods from the MyDodo or Dodo class, not from the Actor class;• Teleportation is not permitted: if Mimi needs to get somewhere, she must walk there!

Theory

Theory 6.1: Object types and variablesWe have learned that Java has primitive types such as int and boolean . Primitive types are built-inJava: you get primitive types as a gift.In addition to primitive types, Java also has object types (sometimes called reference types). Objecttypes are types that belong to a class. You can make a new object type by writing (or importing) a newclass. Examples of object types are MyDodo and Egg.Use of object types

You can use object types in the same way as you use primitive types. As a reminder, the following tablesummarizes how you have already used types:Location Example Typeresult int methodName ( ) intparameter void methodName ( String text ) Stringlocal variable int value = 4 intinstance variable private int myNrEggsFound = 0 int

Object variables

You have also already seen object types. For example, previously we gently skipped over the following:World myWorld = getWorld ( ) ;

Here the variable with the name myWorld and type World is declared (made) and immediately initialised(given a value) with the result of getWorld ( ) . The result type is World. You can see this by looking at thesignature public World getWorld ( ) . Because World is a class, its type is an object type (rather thana primitive type). A variable’s type determines the values it may contain. For example, a variable withtype int (such as int nrOfEggs ) can only store integers. It can’t store a boolean or String . The sameapplies to object types. A variable whose type is an object type, such as Egg, can store Egg objects, but it

Algorithmic thinking and structured programming (in Greenfoot) 2

Page 4: Assignment 6: Lists - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment6-student.pdf · Assignment 6: Lists Algorithmic Thinking and Structured Programming

Lists Assignment 6

can’t store a Fence object or an int value. Any attempt to assign an object to a variable with a differenttype will result in a compiler error. However, there is an exception to this rule, namely, we can store aBlueEgg or a GoldenEgg object in an Egg variable. This is because each BlueEgg or GoldenEgg object isalso an Egg (have a look back at the Theory 1.5 on ’Inheritance’). An example of a variable declarationand initialization with an object type is: Egg firstEgg = new BlueEgg ( );In our figures, we draw variables storing objects using an arrow (Figure 1).

Figure 1: A variable referring to an objectHere, the variable firstEgg stores a reference to the egg object. In fact, object variables always storereferences to objects, and not the objects themselves.Theory 6.2: Calling a method from another classYou have seen that a world consists of objects, and each object is created (instantiated) from a spe-cific class. This class determines what an object can do in terms of methods. When defining a newmethod, you often want to re-use existing methods. When calling such an existing method, there aretwo possible situations:

1. The method belongs to an object’s own class (or a class that is inherited). In this case the objectcalls the method directly (as you have been doing all along).2. The method belongs to a different class. Such a method cannot be called directly. Instead, you firstneed to have an object from that class, which you can use to invoke the desired method.

General explanation

Consider an object from that class called obj, and a method from obj’s class called meth. Assuming thatthe method has no parameters, use obj . meth ( ); to invoke the method. You can read the instructionas follows: obj is asked to execute his method meth.Example of calling a method from a different class

Each Egg has a value. A Dodo and an Egg don’t belong to the same class. For the Dodo to get the valueof some egg, she must do two things:1. Dodo must get the egg: Egg thisEgg = getEgg ( );Here, the variable named thisEgg is used to store the Egg object returned by the method getEgg ( ) .Note that the latter method belongs to the class Dodo, and therefore can be called directly.2. Dodo must ask the value of thisEgg as follows: int valueOfThisEgg = thisEgg . getValue ( );The value of the egg is stored in the variable valueOfThisEgg .

Note

Tip: After typing the Egg variable’s name followed by ’.’ (in the example above: ’thisEgg . ’), use ’Ctrl+Space’to see a list of all the methods available for that object (Figure 2).

Algorithmic thinking and structured programming (in Greenfoot) 3

Page 5: Assignment 6: Lists - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment6-student.pdf · Assignment 6: Lists Algorithmic Thinking and Structured Programming

Lists Assignment 6

Figure 2: To see a list of all available methods, use: ’Ctrl+space’

Theory 6.3: ListsThe object variables that we used in the previous assignments could hold exactly one object. How-ever, sometimes it can be useful to store a whole series (or row) of objects, rather than just one object.Obviously you could make a separate variable for each object, but if you have lots of objects that’s notpractical. What you need is a way to group objects. There are several ways to do this in Java, the easiestis using a List.A List is a series of variables. These variables are the elements of a list. They are stored in sequence,and therefore you can number them. And that is exactly the way in which you can select an element.Namely, you can select (or find) an element by using its position or index. We start counting at 0. Thisis done as follows: the first element has index (is at position) 0, the second element has index 1, ... , thetenth element has index 9. So, you can select the 10th element out of a list by asking for the elementwith index 9.Elements in lists

All elements in a list are of the same type. You can’t store Eggs and Dodos in the same list: it is either alist of Eggs or a list of Dodos.Operations on lists

The number of elements in a list is called its size. You can add elements to a list. You can removeelements out of a list. You can add or remove anywhere in a list: the front, back, or somewhere in themiddle (using the index to indicate exactly where). A list with no elements is empty.Lists in Java

The Java class for lists is called List. Before using lists you must import a special library. This soundsmore complicated than it is: just add the following line of code to the top of the class document whereyou want to use lists: import java . util . List ; .The Java List library has lots of useful methods which you can use:

Algorithmic thinking and structured programming (in Greenfoot) 4

Page 6: Assignment 6: Lists - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment6-student.pdf · Assignment 6: Lists Algorithmic Thinking and Structured Programming

Lists Assignment 6

Method call Effectsize ( ) Returns the number of elements in the list (its length).get (int index ) Returns the element at position ’index’.add (int index , E element ) Adds ’element’ to the list at position ’index’, increasing thelength of the list.remove (E element ) Removes ’element’ from the list, decreasing the length of thelist.remove (int index ) Removes an element from list at position ’index’.isEmpty ( ) Returns whether or not the list is empty. Because you can’tremove elements from an empty list, this is a very usefulcheck before trying to remove any elements.contains ( Object o ) Returns whether or not object ’o’ is in the list.

Knowing which methods are available to you, and understanding how to use them can save you a lot oftime. Why reinvent the wheel when these methods have been written and tested for you!Have a look at the complete Java library List. To get an overview of all the methods available to you,you can do one of the following two steps:• Go to https://docs.oracle.com/javase/7/docs/api/java/util/List.html.• In the Greenfoot menu choose ’Help’, and then ’Java Library Documentation’. Then search for ’List’.A list can contain objects. But it’s important to realize that lists are objects too! A cookbook has alist of recipes and each recipe has a list of ingredients. So, a list can contain a list of other objects.

Declaring a list: an example

The same rules which apply to any other objects also apply to list objects. If you want to use a list,you first declare a variable in which you can store a reference to a list object. For example, a list ofcompliments for Mimi can be declared as follows:List<String> dodosCompliments ;

where dodosCompliments is the variable’s name and String is the type of the objects in the list. Noticethat a special notation is use to indicate the type of the elements. Formally, this is called a generic typeor a parameterized types, because it accepts an additional type (surrounded by < . . . >) as parameter.Generic types require that such a type parameter is an object type, and not a primitive type. In theprevious example this is okay because String is indeed an object type. List<int>, however, wouldbe illegal because int is primitive. In case you need a list of integers, you should use the object typeInteger instead of int. As a matter of fact, Java provides object types for all its primitive types.The MyDodo class has an example of lists:public List<Egg> getListOfEggsInWorld ( )This method returns a list of all the eggs in the world. This can be useful when programming Mimi tofind the eggs in the world which she has to hatch.Using a list: an example

To use this list of eggs, a variable to store the list itself must first be declared:List<Egg> eggsInTheWorld = getListOfEggsInWorld ( ) ;In the code above:

• A variable with the name eggsInTheWorld is declared;

Algorithmic thinking and structured programming (in Greenfoot) 5

Page 7: Assignment 6: Lists - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment6-student.pdf · Assignment 6: Lists Algorithmic Thinking and Structured Programming

Lists Assignment 6

• The type of eggsInTheWorld is List<Egg> (a list of eggs);• The variable eggsInTheWorld is set to the result of getListOfEggsInWorld (the eggsInTheWorld isa list of all the eggs in the world at that moment).

Theory 6.4: For-each PlanTo traverse a list (i.e. to go through each of the elements one-by-one), in Java a for-each-loop is used.

void methodDoSomethingWithList ( ) {for ( ElemType elemVar : listOfElems ) {

doSomethingWithElement ( elemVar ) ;}

}

Here a list named listOfElems is traversed. For each element in the list, the code in the loop is ex-ecuted. So for a list with 5 elements, the code in the loop is executed 5 times. During each loop thevariable elemVar attains the next object in the list. The object’s type is ElemType . In the method calldoSomethingWithElement , something is done with that particular object. The corresponding flowchartis as follows:

Figure 3: Flowchart for a for-each-loopExample:The following code traverses a list of Egg elements and increments their value by 1:

public void incrementValueOfEachEggInWorld ( ) {List<Egg> eggList = getListOfEggsInWorld ( ) ; //get the list of eggs

for ( Egg egg : eggList ) { // get an egg from the list

int currentEggValue = egg . getValue ( ) ; // get the value of the current egg

currentEggValue ++; // and increment its value

egg . setValue ( currentEggValue + 1 ) ; // store new value in egg

}}

In this example, the method getListOfEggsInWorld ( ) returns a list of eggs in the world. The list vari-able eggList is declared and initialized, it stores the list of eggs. In the for-each-loop, one-by-one, wetake a look at each Egg in the eggList . For this egg the methods setValue and getValueare both called.So, at the end of the for-each-loop, each of the eggs in the world will have an increased valued.

Algorithmic thinking and structured programming (in Greenfoot) 6

Page 8: Assignment 6: Lists - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment6-student.pdf · Assignment 6: Lists Algorithmic Thinking and Structured Programming

Lists Assignment 6

Note: A for−each is not suitable for actions which change the list during the loop, like swapping ele-ments. If the intention is to change the list during the loop, use a while.Note: The code above can be written shorter, and without a help-variable:

public void incrementValueOfEachEggInWorld ( ) {List<Egg> eggList = getListOfEggsInWorld ( ) ; //get the list of eggs

for ( Egg egg : eggList ) { // get an egg from the list

egg . setValue ( egg . getValue ( )+1 ) ; // get, increment and store the value of the current egg

}}

Theory 6.5: Average loop planFinding the average of a series of numbers is a common task in programming. To calculate the average,we need the number of items and their sum. Assuming we have these two values we calculate theaverage by dividing the sum by the number of items: average = sum / nrOfItems . For this plan, followthe next steps:

1. Declare the variables needed;(a) The number of items.(b) The sum of the items thus far (a running total).

2. Traverse all items using a for−each-loop;3. For each item, add its value to the running total (current sum) and increase the number of itemsby one;4. Check that the number of items is larger than 0 (to guard for a ’divide-by-zero’), if not report anerror;5. Calculate the average by dividing the sum by the number of items. Note that the average may bea decimal value (requiring a cast to double, see Theory 5.3);6. Return the average.

Algorithmic thinking and structured programming (in Greenfoot) 7

Page 9: Assignment 6: Lists - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment6-student.pdf · Assignment 6: Lists Algorithmic Thinking and Structured Programming

Lists Assignment 6

Figure 4: Flowchart for finding the average of several values in a list

Algorithmic thinking and structured programming (in Greenfoot) 8

Page 10: Assignment 6: Lists - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment6-student.pdf · Assignment 6: Lists Algorithmic Thinking and Structured Programming

Lists Assignment 6

Challenges

Please read Theory 6.1: Object types and variables.

Please read Theory 6.2: Calling a method from another class.

Please read Theory 6.3: Lists.

Please read Theory 6.4: For-each Plan.

Challenge 6.1: Walking through a listIn this challenge we will practice using a list of integers. We will now use the list created bycreateListOfNumbers to experiment with.

a) Find the List<Integer> createListOfNumbers ( ) method in MyDodo .b) The method has a helper method asList . A list can be created just by indicating the elementvalues. Add comments to the code explaining what this method does.c) Have a look at the method practiceWithLists .

i. Add comments explaining what the first line does.ii. The second line is supposed to print the first element to the console. What’s wrong? Fix thecode and add comments.

iii. Declare a variable to hold a list of integers. Initialize it with the list returned by createListOfNumbers .Tip: use List<Integer> listOfNumbers = createListOfNumbers ( );iv. Print the first element to the console.v. Add code to print the number of elements (size) to the console.

d) Write a new method void printNumberList ( List<Integer> listOfNumbers ) which prints allthe numbers in a given list. Tips:• Use a for-each-loop to step through each element in the list (use the For-each Plan describedin Theory 6.4);• Print the value of each element to the console (tip: to print a value without a new line, useSystem . out . print instead of println);

• The following flowchart visualizes this algorithm:

Algorithmic thinking and structured programming (in Greenfoot) 9

Page 11: Assignment 6: Lists - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment6-student.pdf · Assignment 6: Lists Algorithmic Thinking and Structured Programming

Lists Assignment 6

e) Write a method which prints the sum of all the elements of a list to the console. Call the methodin your practiceWithLists method.The following flowchart visualizes the algorithm of the Sum Plan (described in Theory 5.1) usinga list:

Challenge 6.2: Java methods for listsWe will now have a look at List in the Java library. You will learn how to read the Java library docu-mentation so that you can use predefined methods.

a) Go to the Java Library for lists:https://docs.oracle.com/javase/8/docs/api/java/util/List.html. Scroll down until you see thefollowing summary of methods:

Algorithmic thinking and structured programming (in Greenfoot) 10

Page 12: Assignment 6: Lists - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment6-student.pdf · Assignment 6: Lists Algorithmic Thinking and Structured Programming

Lists Assignment 6

b) As you can see, there is a method called add ( int index , E element ) which adds the elementE at the position index.In your practiceWithLists method, add the value ’8’ in the third position in your list. Then callyour printNumberList to test your code.

c) Match the Java Library methods to the description in the following table:Method call Effectremoves an element from a list at a particular indexreturns the third element in the listadds an element to the front of the listadds an element to the end of the listreturns how many element a list has (i.e. how long it is)removes the last element in the listchecks if the list is emptychecks if the list exists (does the listOfNumbers variable point to a list?)

d) Add the following code to the practiceWithLists method:i. Add the value 6 to the end of the list.

ii. Call your printNumberList to print the list.iii. Remove the fourth value in the list.iv. Print the index of the ’8’.v. Test your method by printing the list after each modification.

Challenge 6.3: Print coordinates and values of all eggs in a listNew to Dodo’s world are surprise eggs. The class SurpriseEgg is a subclass of Egg (just like BlueEgg andGoldenEgg ). Blue eggs are worth one point, golden eggs are worth five points, and how many points asurprise egg is worth, well, that’s a surprise! In the constructor of SurpriseEgg its value is set randomly.This is done using the Greenfoot method getRandomNumber . So, every surprise egg has a (different)random value.There is a method for making a list of surprise eggs in the class SurpriseEgg . The first parameterindicates the number of eggs you want to have in the list, the second is the world.public static List<SurpriseEgg> generateListOfSurpriseEggs ( int size , World world ) ;

For example, the following code makes a list of 10 surprise eggs:

Algorithmic thinking and structured programming (in Greenfoot) 11

Page 13: Assignment 6: Lists - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment6-student.pdf · Assignment 6: Lists Algorithmic Thinking and Structured Programming

Lists Assignment 6

In the following challenge you will write several methods to print data stored in lists.a) Create a list of surprise eggs:

i. Come up with an appropriate name for this method.ii. Use the generateListOfSurpriseEggs method to make a list of 10 surprise eggs, just like inthe figure above.

b) Print the coordinates of the first element in the list:i. Write a sub-method to print the coordinates of an egg: void printCoordinatesOfEgg (Egg egg ) .This can be very useful in other parts of the program (as you will see later) or while debugging.Instead of restricting this method to surprise eggs only, we can make it slightly more generalby defining it for Egg objects. In that case, it can also be used for blue and golden eggs.

• Pass the egg to be printed as a parameter, and add this method to MyDodo . Tip: Withegg . getX ( ) and egg . getY ( ) you can get the coordinates of an egg (with the name egg);see also Theory 6.2.

• Test your sub-method by calling the method and then clicking on an egg.• Ensure that coordinates are printed as follows: (3,4)

ii. Write a method which prints the coordinates of the first surprise egg in a given list:printCoordinatesOfFirstSurpriseEgg ( List<SurpriseEgg> mySurpriseEggList ) .

• Get the first egg in the list (which is given as a parameter) and print it using the sub-method you just wrote.• To test your sub-method, write a method practicePrintingLists ( ) which creates alist of surprise eggs, and then calls your printCoordinatesOfFirstSurpriseEgg () sub-method:/**

* Method for practicing with printing data in lists

*/

public void practicePrintingLists ( ){List<SurpriseEgg> surpriseEggList =

SurpriseEgg . generateListOfSurpriseEggs ( 10 , getWorld ( ) ) ;

Algorithmic thinking and structured programming (in Greenfoot) 12

Page 14: Assignment 6: Lists - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment6-student.pdf · Assignment 6: Lists Algorithmic Thinking and Structured Programming

Lists Assignment 6

printCoordinatesOfFirstSurpriseEgg ( surpriseEggList ) ;}

c) Print the coordinates of all the eggs in the list:

(a) Write a method void printCoordinatesOfSurpriseEggList ( List<SurpriseEgg> surpriseEggList )which prints the coordinates of each egg in the list.(b) Use a for-each-loop traverse the eggs in a given list of surprise eggs.(c) For each egg, print its coordinates to the console (re-use your own sub-method for this).(d) Call your sub-method in practicePrintingLists for testing.

d) Print the values of all the elements in the list: For each surprise egg, get its value and print it inthe console. Again, write a sub-method and call it in practicePrintingLists for testing.

Challenge 6.4: Print value of most valuable egg in a listWrite a method which returns the value of the most valuable (surprise) egg in the world.

a) Fill the world with 10 surprise eggs.b) Come up with an algorithm to find (and return) the egg in the list that has the highest value. Tip:Use the Min/Max plan as explained in Theory 5.2.c) Implement this algorithm.d) Test your code, by calling it in your practicePrintingLists method. Tip: For testing purposes,first print the values of all the eggs in the surprise eggs list.e) Is the result correct? Execute the code several more times and check if the correct value is foundeach time. Fix any errors before you continue onto the next challenge.

Challenge 6.5: Print coordinates of most valuable egg in a listYour mission is:

”Print the coordinates of the most valuable egg in a list.”It may be possible for two eggs to have the maximum value. Come up with an appropriate strategy todeal with this case. Add appropriate (JavaDoc) comments to your codePlease read Theory 6.5: Average loop plan.

Challenge 6.6: Print average value of listYour mission is:

”Get the average of the egg-values in a list.”Tips:

• The Average Loop Plan is described in Theory 6.5;• Theory 5.3 describes how to cast an int value to a (decimal) double value.• Also test your method for an empty list (generate a list of 0 eggs using:

generateListOfSurpriseEggs (0, getWorld ( ) ) . Does your program deal with this situation ap-propriately?

Algorithmic thinking and structured programming (in Greenfoot) 13

Page 15: Assignment 6: Lists - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment6-student.pdf · Assignment 6: Lists Algorithmic Thinking and Structured Programming

Lists Assignment 6

Challenge 6.7: Reversing a listWrite a method that turns the list of surprise eggs around. That is to say, reorganizes the list so that thelast element is put in the front, followed by the second to last, etc.

a) Come up with a name for your method.b) Generate a new list of 10 surprise eggs, and print their values.c) Come up with an algorithm to reorder the elements in the list accordingly. Tips:

i. You already learned how to switch two values in Theory 4.4, the ’The Swap Plan’.ii. Have a look at the different methods available to you in the Java Library Documentation (suchas add, get, set, remove). Choose which one(s) you want to use in your algorithm.

iii. First implement a small part of the algorithm and test this:• Write a methodswapElements ( List<Integer> listOfNumbers , int indexFirstElement , int indexSecondElement )which swaps two elements in a list of integers. The method should use the List methodsget and set.• Start by swapping the first and last element.• Print the list again.• Test this. Also check if, in the end, the list still has just as many elements (size).

iv. Think about the rest of the algorithm, without implementing it:

• Place 5 items in front of you. Organise them from smallest to largest. Mark their indexes(see the figure above). Then use your algorithm to sort them (thus by only swapping) fromlargest to smallest.• After the first swap, which are the next two elements that must be swapped? Name theelements using their indexes.• How many swaps do you need all together?• Test your algorithm with 6 (an even number of) items.d) Now, implement the algorithm to turn the whole list around. Tips:

• Use a while−loop (and not a for-each-loop).• Use a variable called eggIndex to keep track of where you are in the list. Don’t forget to incre-ment this variable in the while loop.

e) Compile and test your code by printing the values of each element in the list.f) Does your program work as you expect it to? If not, think of why it doesn’t work properly. Tohelp debugging, print the list of values throughout the code to figure out what happens. Fix yourprogram.g) Does your program also work if there are 11 eggs in your list? And also if there are 0?

Algorithmic thinking and structured programming (in Greenfoot) 14

Page 16: Assignment 6: Lists - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment6-student.pdf · Assignment 6: Lists Algorithmic Thinking and Structured Programming

Lists Assignment 6

Challenge 6.8: Sorting a list: Selection sortA well known sorting algorithm is called selection sort. This is how it’s done:

a) Determine where (at which index) the unsorted list starts (initially this is at the front of the list,0).b) Traverse the unsorted part of the list and find the smallest element.c) Swap that smallest element with the element in the front of the unsorted list.d) Update the index where the unsorted list starts.e) Repeat the last three steps until the entire list has been sorted.Write a method which sorts a list of numbers using selection sort. Tips:• Write a sub-method which returns the position of the smallest value in a part of the list (for theunsorted part of the list).• Use a while loop• Make use of your swapElements method that you wrote in Challenge 6.7.Answer the following questions assuming you would have a list of 5 numbers:

a) How often are two values compared?b) For a list which is twice as big (having 10 numbers), how often are two values compared?c) For a list which is 100 times as big, how often are two values compared?d) Can you write a general formula to calculate the number of comparisons needed for a list with nelements?

Challenge 6.9: Calculate distanceHelp Mimi figure out how many steps it takes to get from where she is to any place she wishes to go to.Write a method int determineDistance ( int x_coord , int y_coord ) which calculates the numberof steps (or moves) from the current location to another. Note:

• You don’t have to use Pythagoras’s theorem to calculate the distance, just count the number ofmoves she will need to take.• If you need to turn a negative number into a positive number, the method Math . abs ( number )will return the absolute value of any given number.

Challenge 6.10: Goto the most distant egg in the worldHelp Mimi to determine which egg requires the most steps to get to, and walk to that egg. Break youralgorithm down into several logical modules. Program new methods, re-use existing methods, and testeach individually. Tip: check the coordinates of an egg by ’inspecting’ it.

Algorithmic thinking and structured programming (in Greenfoot) 15

Page 17: Assignment 6: Lists - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment6-student.pdf · Assignment 6: Lists Algorithmic Thinking and Structured Programming

Lists Assignment 6

Challenge 6.11: Re-factoringAn important part of programming is creating code that is made up of logical modules. Amongst otherthings, this makes re-using and testing so much easier.Have a look back at the code you wrote in the previous Challenge 6.10 for ”Goto the most distantegg in the world”. Are there any fragments of code in your method that could have been written as aseparate sub-method?If you have not written a separate method to determine the distance from Mimi’s position to anotherlocation, do that now. Test your sub-method. Replace the code in your method for going to the mostdistant egg (Challenge 6.10) by your sub-method determineDistance .

Algorithmic thinking and structured programming (in Greenfoot) 16

Page 18: Assignment 6: Lists - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment6-student.pdf · Assignment 6: Lists Algorithmic Thinking and Structured Programming

Lists Assignment 6

ReflectionIn this assignment you practiced using list to store values. You also learned about the for-each-loop totraverse lists and how to use a list to store (Egg) objects. One of the most important steps in becominggood at anything is to evaluate and reflect on what you did and how it went:ResultI know my solution works because . . .I am proud of my solution because . . .I could improve my solution by . . .

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

Fill the following table with smileysindicating how things went. I can do itI did it a bit but didn’t fully get itI didn’t get it at all

I can use lists to store either primitive types or object types.

I can use a for-each-loop to walk through a list.

I can use the Java Library Documentation to look for and use existingJava methods.I can swap elements in a list.

I can sort objects in a list.

I can calculating the average of a list of values.

I can break a complex algorithm down into subtasks and implement andtest these separately.

Algorithmic thinking and structured programming (in Greenfoot) 17

Page 19: Assignment 6: Lists - Radboud Universiteitcourse.cs.ru.nl/greenfoot/docs/Opdrachten3.0/DodoAssignment6-student.pdf · Assignment 6: Lists Algorithmic Thinking and Structured Programming

Lists Assignment 6

Saving and Handing inYou have just finished the assignment. Save your work! You will need this for future assignments. In theGreenfoot menu at the top of the screen, select ’Scenario’ and then ’Save’. You now have all the scenariocomponents in one folder. The folder has the name you chose when you selected ’Save As ...’.Handing inHand in the following:

• Your code: The java file MyDodo . jav;• Flowcharts: paste (photo’s of) your flowcharts in a Word document;• The reflection sheet: complete and hand it in.

Algorithmic thinking and structured programming (in Greenfoot) 18