Assignment 6: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6...

21
Assignment 6: Lists Algorithmic Thinking and Structured Programming (in Greenfoot) c 2017 Renske Smetsers-Weeda & Sjaak Smetsers 1 Contents Introduction 1 Learning objectives 1 Instructions 1 Theory 2 6.1 Object types and variables ......................................... 2 6.2 Calling a method from another class ................................... 3 6.3 Lists ...................................................... 4 6.4 For-each Plan ................................................ 6 6.5 Surprise eggs ................................................ 7 6.6 Average loop plan .............................................. 7 6.7 Selection Sort ................................................ 8 Challenges 10 6.1 Walking through a list ........................................... 10 6.2 Java methods for lists ........................................... 11 6.3 Print coordinates and values of all eggs in a list ............................ 12 6.4 Which is is the most valuable? ...................................... 14 6.5 Where is the most valuable egg? ..................................... 14 6.6 Print average value of list ......................................... 14 6.7 Reversing a list ............................................... 14 6.8 Sort a list with Selection Sort ....................................... 16 6.9 Calculate distance .............................................. 16 6.10 Goto the most distant egg in the world ................................. 16 6.11 Re-factoring ................................................ 16 Reection 18 Saving and Handing in 20 1 Licensed under the Creative Commons Attribution 4.0 license: https://creativecommons.org/licenses/by/4.0/

Transcript of Assignment 6: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6...

Page 1: Assignment 6: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6 Figure2:Toseealistofallavailablemethods,use:’Ctrl+Space’ Theory6.3:Lists ...

Assignment 6: Lists

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

ContentsIntroduction 1Learning objectives 1Instructions 1Theory 26.1 Object types and variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26.2 Calling a method from another class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36.3 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46.4 For-each Plan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66.5 Surprise eggs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76.6 Average loop plan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76.7 Selection Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8Challenges 106.1 Walking through a list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106.2 Java methods for lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116.3 Print coordinates and values of all eggs in a list . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126.4 Which is is the most valuable? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146.5 Where is the most valuable egg? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146.6 Print average value of list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146.7 Reversing a list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146.8 Sort a list with Selection Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166.9 Calculate distance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166.10 Goto the most distant egg in the world . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166.11 Re-factoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Reflection 18Saving and Handing in 201Licensed under the Creative Commons Attribution 4.0 license: https://creativecommons.org/licenses/by/4.0/

Page 2: Assignment 6: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6 Figure2:Toseealistofallavailablemethods,use:’Ctrl+Space’ Theory6.3:Lists ...

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 allthe eggs. For this, we will use a List. Using a List gives you the opportunity to come up with smarteralgorithms. By having a list of all of the Egg objects in the world, you would also have their coordinatesand values at your fingertips (using getter methods). You could use a list to help a lazy Dodo find allthe eggs in the world using the least amount of steps.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 Listmethods, 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 nullmeans and what it is used for;• use a list to store primitive types (such as int, String) or 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: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6 Figure2:Toseealistofallavailablemethods,use:’Ctrl+Space’ Theory6.3:Lists ...

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 experi-ence should complete all of these.Mandatory. Everyone must complete these.

Excelling. More inquisitive tasks, designed for students who completed 2 star tasks andare 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 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!

TheoryTheory 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 typesYou 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 variablesYou have also already seen object types. For example, previously we gently skipped over the following(from Assignment 4):

World myWorld = getWorld( );

Here the variablewith 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 lookingat the signature public World getWorld( ). Because World is a class, its type is an object type (ratherthan a primitive type). A variable’s type determines the values it may contain. For example, a variable

Algorithmic thinking and structured programming (in Greenfoot) 2

Page 4: Assignment 6: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6 Figure2:Toseealistofallavailablemethods,use:’Ctrl+Space’ Theory6.3:Lists ...

Lists Assignment 6

with type int (such as int nrOfEggs) can only store integers. It can’t store a boolean or String. Thesame applies to object types. A variable whose type is an object type, such as Egg, can store Egg objects,but it can’t store a Fence object or an int value. Any attempt to assign an object to a variable with adifferent type will result in a compiler error. However, there is an exception to this rule, namely, wecan store a BlueEgg or a GoldenEgg object in an Egg variable. This is because each BlueEgg or GoldenEggobject is also an Egg (have a look back at the theory 1.5 on ’Inheritance’). An example of a variabledeclaration and 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 classWhen calling a method, the method can either belong to the object itself or belong to another object.How you call the method depends on who the method belongs to: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. To be able to call a method from another class, you firstneed to have an object from that class.

General explanation: Consider an object from that class called object, and a method from object’s class called method.Assuming that the method has no parameters, use object.method( ); to call the method. You canread the instruction as follows: object is asked to execute his method method.Example of calling a method from a different class: Imagine there is a BlueEgg object called babyBlueEgg. The BlueEgg class has a method int getX( )(inherited from Actor) which returns the egg’s x-coordinate.Mimi wants to know where the egg is (its coordinates). Mimi can ask babyBlueEgg’s x-coordinate byusing: babyBlueEgg.getX( );. This call is done from Mimi’s MyDodo class.

NoteTip: After typing the object’s name followed by ’.’ (in the example above: ’babyBlueEgg.’), use ’Ctrl+Space’to see a list of all the methods available for that object.

Algorithmic thinking and structured programming (in Greenfoot) 3

Page 5: Assignment 6: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6 Figure2:Toseealistofallavailablemethods,use:’Ctrl+Space’ Theory6.3:Lists ...

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. However,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 listsAll 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 listsThe 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 JavaThe 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: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6 Figure2:Toseealistofallavailablemethods,use:’Ctrl+Space’ Theory6.3:Lists ...

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’tmuch with an empty list, this is a very useful check beforetrying to do anything with 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 lotof time. 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/8/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 listThe 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 used to indicate the type of the elements: the element-type is placed between’<’ and ’>’ as a parameter.Formally, this is called a generic type or a parameterized types, because it accepts an additional type(surrounded by < . . . >) as parameter. Generic types require that such a type parameter is an objecttype, and not a primitive type. In the previous example this is okay because String is indeed an objecttype. List<int>, however, would be illegal because int is primitive. In case you need a list of integers,you should use the object type Integer instead of int. As a matter of fact, Java provides object typesfor 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 listTo use this list of eggs, a variable to store the list itself must first be declared:

Algorithmic thinking and structured programming (in Greenfoot) 5

Page 7: Assignment 6: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6 Figure2:Toseealistofallavailablemethods,use:’Ctrl+Space’ Theory6.3:Lists ...

Lists Assignment 6

List<Egg> eggsInTheWorld = getListOfEggsInWorld( );

In the code above:• A variable with the name eggsInTheWorld is declared;• The type of eggsInTheWorld is List<Egg> (a list of eggs);• The variable eggsInTheWorld is set to the result of getListOfEggsInWorld (so the eggsInTheWorldis a 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-loopNote: A for-each is should not be used for actions which change the list during the loop, such asswapping elements. If the intention is to change the list during the loop, use a while.Example: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 eggsfor ( Egg egg: eggList ) { // get an egg from the list

int currentEggValue = egg.getValue( ); // get the value of the current eggcurrentEggValue ++; // and increment its value

Algorithmic thinking and structured programming (in Greenfoot) 6

Page 8: Assignment 6: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6 Figure2:Toseealistofallavailablemethods,use:’Ctrl+Space’ Theory6.3:Lists ...

Lists Assignment 6

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

}

In this example, the method getListOfEggsInWorld( ) returns a list of eggs in the world. The listvariable eggList is declared and initialized, it stores the list of eggs. In the for-each-loop, one-by-one,we take a look at each Egg in the eggList. For this egg the methods getValue and setValueare bothcalled. So, at the end of the for-each-loop, each of the eggs in the world will have an increased valued.Note: The code above can be written shorter, and without a helper-variable:public void incrementValueOfEachEggInWorld ( ) {

List<Egg> eggList = getListOfEggsInWorld( ); //get the list of eggsfor ( Egg egg: eggList ) { // get an egg from the list

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

}}

Theory 6.5: Surprise eggsNew to Dodo’s world are surprise eggs. The class SurpriseEgg is a subclass of Egg (just like BlueEggand GoldenEgg). Blue eggs are worth one point, golden eggs are worth five points, and how manypoints a surprise egg is worth, well, that’s a surprise! In the constructor of SurpriseEgg its value is setrandomly. This is done using the Greenfoot method getRandomNumber. So, every surprise egg can havea different 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, Worldworld );

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

Theory 6.6: Average loop planFinding the average of a series of numbers is a common task in programming. This is called the Average-Loop Plan. To calculate the average, we need the number of items and their sum. The calculation isthen: average = sum / nrOfItems. We already used this in Challenge 5.6. However, this time we haveall the values in a list instead of the world. So now we need to traverse the list to find the sum and thenumber of elements. For this plan, follow the next steps:a) Declare and initialize the variables needed:

(a) The number of items.

Algorithmic thinking and structured programming (in Greenfoot) 7

Page 9: Assignment 6: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6 Figure2:Toseealistofallavailablemethods,use:’Ctrl+Space’ Theory6.3:Lists ...

Lists Assignment 6

(b) The sum of the items thus far (a running total).b) Traverse all items using a for-each-loop;c) For each item, add its value to the running total (current sum) and increase the number of itemsby one;d) Check that the number of items is larger than 0 (to guard for a ’divide-by-zero’), if not report anerror;e) 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);f) Return the average.

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

Theory 6.7: Selection SortA sorting algorithm is used to sort the elements in a list into a particular order. A sorting algorithm canbe used to sort numbers into order from smallest to largest, or largest to smallest. For example, a listof people’s lengths can be sorted from smallest to tallest. Or the results of a 100m race can be sortedfrom fastest to slowest.A 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.

Algorithmic thinking and structured programming (in Greenfoot) 8

Page 10: Assignment 6: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6 Figure2:Toseealistofallavailablemethods,use:’Ctrl+Space’ Theory6.3:Lists ...

Lists Assignment 6

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.The following site shows an animation of the selection sort algorithm: https://visualgo.net/

en/sorting.

Algorithmic thinking and structured programming (in Greenfoot) 9

Page 11: Assignment 6: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6 Figure2:Toseealistofallavailablemethods,use:’Ctrl+Space’ Theory6.3:Lists ...

Lists Assignment 6

ChallengesPlease 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 listnIn 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) Add comments to the code of createListOfNumbers( ) explaining what the method does. Tip:The method has a helper method asList which makes a list with the given values.c) We will now adjust the method practiceWithLists so that we can use it:

i. Add comments to the method practiceWithLists 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. Apply the For-each Plan de-scribed in 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) 10

Page 12: Assignment 6: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6 Figure2:Toseealistofallavailablemethods,use:’Ctrl+Space’ Theory6.3:Lists ...

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 practiceWithListsmethod.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.

Algorithmic thinking and structured programming (in Greenfoot) 11

Page 13: Assignment 6: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6 Figure2:Toseealistofallavailablemethods,use:’Ctrl+Space’ Theory6.3:Lists ...

Lists Assignment 6

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

b) Change your practiceWithListsmethod so that it adds the value ’8’ at the third position in yourlist. Tip: there is a method called add( int index, E element ) which adds the element E atposition index.c) Call your printNumberList to test your code.d) 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?)e) Add the following code to the practiceWithListsmethod:

i. Add the value 6 to the end of the list.ii. Call your printNumberList to print the list.iii. Print the index of the ’8’.iv. Remove the fifth value in the list.v. Test your method by printing the list after each modification.vi. What happens if you try to remove a number that isn’t in the list?

Please read Theory 6.5: Surprise eggs.

Challenge 6.3: Print coordinates and values of all eggs in a listIn 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.

Algorithmic thinking and structured programming (in Greenfoot) 12

Page 14: Assignment 6: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6 Figure2:Toseealistofallavailablemethods,use:’Ctrl+Space’ Theory6.3:Lists ...

Lists Assignment 6

ii. Use the generateListOfSurpriseEggs method to make a list of 10 surprise eggs. See alsoTheory 6.5.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(Eggegg). This can be very useful in other parts of the program (as you will see later) or whiledebugging.• Instead of restricting this method to surprise eggs only, we can make it slightly moregeneral by defining it for Egg objects. In that case, it can also be used for blue and goldeneggs.• 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 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 (the list is given as a parameter) and print it using theprintCoordinatesOfEgg( ) 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( ) );printCoordinatesOfFirstSurpriseEgg( surpriseEggList );

}

c) Print the coordinates of all the eggs in the list:i. Write amethod void printCoordinatesOfSurpriseEggList(List<SurpriseEgg> surpriseEggList

) which prints the coordinates of each egg in the list.ii. Use a for-each-loop traverse the eggs in a given list of surprise eggs.iii. For each egg, print its coordinates to the console (re-use your own sub-method for this).

Algorithmic thinking and structured programming (in Greenfoot) 13

Page 15: Assignment 6: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6 Figure2:Toseealistofallavailablemethods,use:’Ctrl+Space’ Theory6.3:Lists ...

Lists Assignment 6

iv. 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 itin the console. Again, write a sub-method and call it in practicePrintingLists for testing.

Challenge 6.4: Which is is the most valuable?Write a method which prints 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 theMin/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: Where is the most valuable egg?Your 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.6: 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.6;• 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) 14

Page 16: Assignment 6: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6 Figure2:Toseealistofallavailablemethods,use:’Ctrl+Space’ Theory6.3:Lists ...

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 thatthe last 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(such as add, get, set, remove). Choose which one(s) you want to use in your algorithm.

d) First implement a small part of the algorithm and test this:i. Write a method

swapElements(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.

ii. Start by swapping the first and last element.iii. Print the list again.iv. Test this. Also check if, in the end, the list still has just as many elements (size).

e) 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.

f) Now, implement the algorithm to turn the whole list around. Tips:• Because you want to change the list within a loop, use a while-loop. Don’t use a for-each-loop).

• Use a variable called eggIndex to keep track of where you are in the list. Don’t forget toincrement this variable in the while loop.g) Compile and test your code by printing the values of each element in the list.

Algorithmic thinking and structured programming (in Greenfoot) 15

Page 17: Assignment 6: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6 Figure2:Toseealistofallavailablemethods,use:’Ctrl+Space’ Theory6.3:Lists ...

Lists Assignment 6

h) 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.i) Does your program also work if there are 11 eggs in your list? And also if there are 0?

Please read Theory 6.7: Selection Sort.

Challenge 6.8: Sort a list with Selection SortWrite a method which sorts a list of numbers using selection sort (see Theory 6.7). 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 swapElementsmethod that you wrote in Challenge 6.7.Answer the following questions for your Selection Sort algorithm.a) If you have a list of four numbers, how often are two values compared?b) For a list with five values, how many comparisons are mare?c) For a list which is twice as big (having ten numbers), how often are two values compared?d) For a list which is ten times as big, how often are two values compared?e) 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 howmany 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 newmethods, re-use existing methods, and testeach individually. Tip: check the coordinates of an egg by ’inspecting’ it.

Algorithmic thinking and structured programming (in Greenfoot) 16

Page 18: Assignment 6: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6 Figure2:Toseealistofallavailablemethods,use:’Ctrl+Space’ Theory6.3:Lists ...

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 separatemethod to determine the distance fromMimi’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) 17

Page 19: Assignment 6: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6 Figure2:Toseealistofallavailablemethods,use:’Ctrl+Space’ Theory6.3:Lists ...

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 it

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

I didn’t get it at all

Algorithmic thinking and structured programming (in Greenfoot) 18

Page 20: Assignment 6: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6 Figure2:Toseealistofallavailablemethods,use:’Ctrl+Space’ Theory6.3:Lists ...

Lists Assignment 6

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) 19

Page 21: Assignment 6: Listscourse.cs.ru.nl/greenfoot/docs/Opdrachten v3.1.1...Lists Assignment6 Figure2:Toseealistofallavailablemethods,use:’Ctrl+Space’ Theory6.3:Lists ...

Lists Assignment 6

Saving and Handing inYou have just finished the assignment. Save your work! You will need this for future assignments. Inthe Greenfoot menu at the top of the screen, select ’Scenario’ and then ’Save’. You now have all thescenario components 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) 20