33
Chair of Software Engineering 1 Introduction to Programming Exercise Session Week 10 M. Piccioni 24/25 November 2008

Chair of Software Engineering 1 Introduction to Programming Exercise Session Week 10 M. Piccioni 24/25 November 2008

  • View
    215

  • Download
    0

Embed Size (px)

Citation preview

Chair of Software Engineering

1

Introduction to Programming

Exercise Session Week 10M. Piccioni

24/25 November 2008

Chair of Software Engineering2

Announcement

In two weeks (December 9th)...

Mock exam 2

Chair of Software Engineering3

Featuring today

GenericityRecursion

Recursion

Recursion

Recursion

Recursion

Recursion and Trees!

Chair of Software Engineering4

Genericity: Type parametrization

LIST_OF_ANIMALS

LIST_OF_PEOPLE

LIST_OF_CARS

Type parameterization Type parameterization

Chair of Software Engineering5

Genericity - why?

To parametrize a class, abstracting away all the

operations in common

A single class text may be reused for many different

objects types.

To provide an implementation of type safe containers

Helps avoiding objects-test/assignment attempt

Chair of Software Engineering6

A Generic List

class LINKED_LIST[G]feature

item: G-- the element cursor is pointing atdo ... end

append(value: G)-- append a value to the listdo ... end

end

G will be replaced by the compiler with the needed type that has to be specified at some point.

Generic parameter

Chair of Software Engineering7

A “natural” exampleclass ANIMAL

createmake

feature -- Initialization

make (a_genus: STRING)dogenus := a_genus

end

feature -- Status

genus: STRING

...

end

Chair of Software Engineering

the animals:from ____________________until__________________ _______________ loop

x := _____________ print(x.genus)________________

end

8

Type safe Containers

x: ANIMALanimal_list: LINKED_LIST [ANIMAL]a_rock: MINERAL animal_list.put(a_rock) -- does this rock?

Hands-On

animal_list.startanimal_list.after

animal_list.item

animal_list.forth

Chair of Software Engineering

Constrained generic parameter

note: “Storage for resources”

class STORAGE [G ->RESOURCE] inherit LIST[G]

consume_all

do

from start until after loop

item.consume

forth

end

end

...

end

9

A Constrained Generic List

item is checked for conformance with

RESOURCE

-- client codesf: STORAGE [FISH]sg: STORAGE [GRAIN]

Chair of Software Engineering10

The Waldgarten Project

We need to associate each plant in thesame category (categories are trees, bushes,herbs and mosses) to a unique id.

Suggest one or more classes for the specifiedcontext.

Hands-On

Chair of Software Engineering11

Yes, we can (constrain) Solutionclass PLANT ...species: STRING...

end

Usage:

herbs: HASH_TABLE [HERB, STRING]bushes: HASH_TABLE [BUSH, STRING]

...herbs.add(myherb, myherb.species)

Chair of Software Engineering

Today

Recursion

12

Chair of Software Engineering

Thoughts

13

„To iterate is human, to recurse - divine!“

but … computers are built by humans

Better use iterative approach if reasonable?

Chair of Software Engineering

Iteration vs. Recursion

Every recursion could be rewritten as an iteration

and vice versa.

BUT, depending on how the problem is formulated,

this can be difficult or might not give you a

performance improvement

14

Chair of Software Engineering

Recursion warm-up exercise 1

If we pass n=4, how many numbers will be

printed and in which order? print_int (n: INTEGER)do

print (n)if n>1 then

print_int (n-1) end

end

15

Hands-On

Chair of Software Engineering

Recursion warm-up exercise 2

If we pass n=4, how many numbers will be

printed and in which order? print_int (n: INTEGER)do

if n>1 then print_int (n-1)

endprint (n)

end

16

Hands-On

Chair of Software Engineering

Recursion exercise 3

Print a given string

in reverse order

using a recursive function

17

Hands-On

Chair of Software Engineering

Sequences and Recursion

Write a recursive and an iterative program to print the following:

111,112,113,121,122,123,131,132,133,211,212,213,221,222,223,231,232,233, 311,312,313,321,322,323,331,332,333.

18

Hands-On

Chair of Software Engineering

Magic Squares

The sums in every row and column is constant

Numbers are all different

19

4 3 8

9 5 1

2 7 6

Chair of Software Engineering

Magic Squares and Permutations

Finding a magic square 3x3 is related to finding the permutations of 1 to 9

123456789 123456798 123456879 123456897 123456978 123456987 ... 987654321

20

There exist 72 magic 9x9

squares (8 of which distinct)

Chair of Software Engineering

Find the Magic Squares

Write a program that finds all the eight 9x9 magic squares.

Hint 1: Refactor the previous recursive algorithm applying it to permutations (enforce no repetitions)

Hint 2: Use two arrays of 9 elements, one for the current permutation and one to know if a number has already been used or notHint 3: If you are desperate, have a look at the postedsolution with the debugger

21

Hands-On

Chair of Software Engineering

Going backwards pays off

When the program finds, at the 9th recursion, that a square is not magical, it goes back on the call stack to the previous instance of the function, and even more back if needed.

This technique is called BackTracking and is used in many recursive programs.

22

Chair of Software Engineering

Data structures

You have seen several data structures

ARRAY, LINKED_LIST, HASH_TABLE, …

We will now look at another data structure

(Binary) tree and its recursive traversal

23

Chair of Software Engineering

Tree

24

Chair of Software Engineering

Tree

25

Chair of Software Engineering

Tree – in a more abstract way

Node

Tree:

One root

Typically several leaves

“ROOT”

“LEAF”

26

Chair of Software Engineering

Binary Tree

Node

Binary tree:

One root

Typically several leaves

Each node can have at most 2 children (possibly 0 or 1)

“ROOT”

“LEAF”

27

Chair of Software Engineering

Recursive traversal of a binary tree

Implement class NODE with an INTEGER attribute

In NODE implement a recursive feature that traverses

the tree and prints out the INTEGER value of each

NODE object

Test your code by class APPLICATION which builds a

binary tree and calls the traversal feature

28

Hands-On

Chair of Software Engineering

Binary Search Tree

10

8 13

4 9 20

Binary search tree:

Binary tree where each node has a COMPARABLE value

Left sub-tree of a node contains only values less than the node’s value

Right sub-tree of a node contains only values greater than or equal to the node’s value

“ROOT”

“LEAF”

29

Chair of Software Engineering

Creating a binary search tree

Implement command put (n: INTEGER) in class NODE

which creates and links a new NODE object at the

right place in the binary search tree rooted by Current

Test your code by class APPLICATION which builds a

binary search tree using put and prints out the values

using the traversal feature

Hint: you might need to adapt the traversal feature

such that the values are printed out in order

30

Hands-On

Chair of Software Engineering31

Questions?

Chair of Software Engineering32

Backup slides

Chair of Software Engineering

Searching in a binary search tree

Implement feature has(n: INTEGER): BOOLEAN

in class NODE which returns true if and only if n is in

the tree rooted by Current

Test your code by class APPLICATION which builds a

binary search tree and calls has

33

Hands-On