week 10 recursion, external application interfacingen1811/13s1/lects/week10-recursion.pdf ·...

23
ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers Week 10 Recursion, External Application Interfacing

Upload: others

Post on 07-Oct-2020

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1

ENGG1811 Computing for Engineers

Week 10

Recursion, External Application

Interfacing

Page 2: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 2

This Week

• Wednesday am:

– Will include discussion about assignment 2

• Wednesday pm:

– Will include VBA exam revision examples

References

• Recursion is covered quite nicely at

http://www.cs.princeton.edu/introcs/23recursion/

• not quite so well in Chapra

– Section 12.4 Recursion

Page 3: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 3

Recursive Factorial

• Recursion is implemented through functions or subprograms calling themselves rather than another procedure

• Works provided the base case is handled and there are sufficient resources to sustain the calculation

Function fact(n As Integer) As Long

If n = 0 Then

fact = 1

Else

fact = n * fact(n-1)

End If

End Function

Page 4: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 4

Tracing Factorial

Trace the calculation as with other procedure calls

fact(5) = 5 * fact(4)

fact(4) = 4 * fact(3)

fact(3) = 3 * fact(2)

fact(2) = 2 * fact(1)

fact(1) = 1 * fact(0)

fact(0) = 1

fact(1) = 1 * 1 = 1

fact(2) = 2 * 1 = 2

fact(3) = 3 * 2 = 6

fact(4) = 4 * 6 = 24

fact(5) = 5 * 24 = 120

Each function waits for the recursive call

to return

Each function uses the value from the recursive

call to calculate and return its factorial

Page 5: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 5

Tail Recursion

The Factorial function is an example of what’s called tail recursion, where each call results in either

– no recursion (the base case), or

– one recursive call in an expression

Tail recursion produces a sequence, called a stack of pending procedure calls

Tail recursion can always be replaced by iteration, which generally consumes less resources

Page 7: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 7

Why BadFib is Bad

Tracing calls on BadFib produces a tree rather than

a simple stack of calls:

F(6)

F(5)

F(4) F(3)

F(3) F(2)

F(1) F(0) F(2)

F(1) F(0)

F(1)

F(4)

F(3) F(2)

F(1) F(0) F(2)

F(1) F(0)

F(1) F(2)

F(1) F(0)

F(1)

tree h

as n

levels

F(3) is evaluated three times independently

Page 8: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 8

Recursion in Nature

Some things in nature contain elements that are smaller copies of themselves (this is called self-similarity). The branching patterns of creeks and rivers, ferns, cloud patterns and blood vessels

are all examples.

Anne Burns (Long

Island University) has a nice paper on the web (ref below) describing general techniques for creating images such as this one.

Nothing in the picture is real.

http://www.mi.sanu.ac.yu/vismath/bridges2005/burns/index.html

Page 9: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 9

Fractals

Although fractals are not necessarily recursive, they also show self-similarity. This is my favourite, a Newton-Raphson fractal:

The picture shows part

of the complex plane

(Re ±1.6, Im ±1.2).

Colours represent how

many iterations the N-R

algorithm* takes to find

a cube root of 1 given

that starting point. The

dark blue dots are the

three roots. Colour

coding: blue=1 to 3

iterations, yellow=8,

red=12, white=16+.

* The Newton-Raphson algorithm for finding the roots of f (x) was described in the

lecture on iteration (week 7, slide 8). It applies to complex as well as real functions.

Page 10: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 10

Fractal Self-Similarity

More detail is revealed (with the

same repeated alien patterns) as the

limits are adjusted. The final

version’s area is 0.06 x 0.04, and

white now represents 21+ iterations.

Page 11: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 11

Recursive Drawings

• We can do a tiny bit of this with the simple drawing tools available in VBA

• Draw a simple figure, then one or more smaller copies positioned relative to the larger one

• Copies are drawn recursively

• Recursion stops when the elements get small enough that the detail can’t be seen

• Can’t (easily) convert to iteration unless only one copy (e.g., picture of A-series paper sizes)

Source: Wikipedia

Page 12: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 12

Sierpinski Gasket

One of the simplest fractals is the Sierpinski gasket, which consists of a triangle with smaller inverted triangular cutouts.

http://ejad.best.vwh.net/java/fractals/sierpinski.shtml

• Each level removes (or overlays) a white triangle, then applies the same algorithm recursively to each of the surrounding black regions

• Number of black triangles at depth n is 3n, but how many white inverted triangles are there?

• try the Java applet at

pic

: htt

p:/

/renam

bot.

lakephoto

.org

/cla

sses/4

88/l

ectu

re13.h

tml

Page 13: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 13

Recursive Drawing Procedure

Sub DrawThing(x As Single, y As Single, size As Single)

If size < MIN_SIZE Then

Exit Sub

End If

draw figure at position (x, y)

' calculate position of first copy

x1 = … : y1 = …

DrawThing(x1, y1, size*SCALE_FACTOR)

' same for other copies

DrawThing(x1, y1, size*SCALE_FACTOR)

End Sub

General approach:

Constant describing the reduction in size

for each copy

Constant describing the smallest effective size

Page 14: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 14

H-Trees

The following is from the Princeton reference.

Recursive graphics.

Simple recursive drawing schemes can lead to pictures that are remarkably intricate. For example, an H-tree of order n is defined as follows: The base case is do nothing for n = 0. The reduction step is to draw, within the unit square three lines in the shape of the letter H [then] four H-trees of order n1, one connected to each tip of the H with the additional provisos that the H-trees of order n1 are centered in the four quadrants of the square, halved in size.

Question: What size will the entire picture be compared to the first H? (This is related to Zeno’s Paradox about Achilles and the Tortoise)

Page 15: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 15

H-Trees

Apart from drawing a canvas, the algorithm for drawing an H-Tree centred on (x,y) is just

HTree(x,y,size) :-

If size < MIN_SIZE Then

Exit Sub

End If

hsize = size/2 ' half-size

Draw horizontal line through (x,y) of length size

Draw vertical lines through (x-hsize,y) and (x+hsize,y)

HTree x-hsize, y+hsize, hsize ' bottom left

HTree x-hsize, y-hsize, hsize ' top left

HTree x+hsize, y-hsize, hsize ' top right

HTree x+hsize, y+hsize, hsize ' bottom right

Use a separate subprogram to draw the lines, so you can apply the attributes consistently and once only

(x,y)

(x+hsize,y-hsize)

size h

size

Page 16: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 16

H-Tree Demo

• See the demo workbook. To make it more useful as a learning tool, the following have been added

– a ClearDrawing subroutine

– a DrawCanvas subroutine (shape reference saved)

– a depth parameter, indicating how many calls are active

– colours, derived from the depth

– a visible stack, showing the depth in boxes

– timings, to demonstrate inefficiencies in VBA’s collections

• Most important parts are the subprograms DrawHTree, HTree itself and DrawLine

• Depending on your processor, the picture will take a couple of minutes to draw, and the drawing rate will slow down as each line is added to the shape collection.

Page 17: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 17

Office Interfacing

All MS Office applications can start and interact with any other Office app

– For example, Excel can start Word and transfer data from a sheet to a table

– Word can start Outlook and send emails (if an email server is available)

– Excel can obtain data from an Access database (though this requires a lot of fiddling around)

Other kinds of interface (if you’re interested)

– Loading data into Excel from a table on a web page (but easier via the UI)

– Opening a browser window with a specified URL (which may include parameters)

Page 18: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 18

Example: Creating a Word Doc

' Example adapted from Shepherd, Excel VBA

Sub Test_Word()

Dim objWordApp As Word.Application ' reference to Word (the app)

Dim objWordDoc As Word.Document ' ref to a newly created doc

Set objWordApp = CreateObject("Word.Application")

Set objWordDoc = objWordApp.Documents.Add

With objWordDoc

.Sections(1).Range.Text = "My new Word Document"

.SaveAs "c:\MyTest.doc" ' must use full pathname

.Close

End With

' These are required to make sure MS Word shuts down completely

Set objWordDoc = Nothing

Set objWordApp = Nothing

End Sub

Page 19: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 19

Object Reference Settings

Unfortunately this fails to satisfy the compiler.

The error points to

Word.Application

Select Tools – References

on the VBE menu, scroll to Microsoft Word 12*

Object Library and check.

Press OK.

* or largest value: 10=Office2002,

11=Office2003, 12=Office2007, 14 = Office2010 (there is no 13!)

Page 20: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 20

Worked Examples

This is the end of the new VBA material (all together now, a big groan of disappointment)

Some short worked examples of the kind that could be set for the final exam will follow.

A bearing is an angle measured clockwise from North

A back bearing is the bearing that is exactly opposite a given bearing. Bearings lie between 0 and 360 degrees.

For example, if I'm sighting a landmark at that has a compass bearing of 110 degrees (slightly South of East), the back bearing is 290 degrees (slightly North of West). The back bearing is the bearing from the landmark back to me.

Write a VBA function BackBearing that returns the back bearing for

any given bearing, expressed in degrees between 0.0 (inclusive) and 360.0 (exclusive).

1

Page 21: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 21

Worked Examples

Write a VBA subprogram that candy-stripes the active worksheet.

Candy-striping fills the background of every second row with a faint grey colour. Stop with the first empty cell in column A.

Use the macro recorder to gather information about colouring rows, then work on the loop to apply the fills.

2

Page 22: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 22

Worked Examples

A worksheet contains rainfall data for Liverpool, NSW for the

month of April 2009, downloaded from http://www.bom.gov.au/climate/dwo/

A domestic water tank is fed from the guttering of a house. Given the roof area, tank capacity and initial amount of water in the tank, complete the worksheet using a VBA procedure. Assume no water is drawn from the tank over the month.

3

Named cells RoofArea and TankCapacity

VBA fills in this column

Analysis: how much water does 1mm of

rain produce per m2 of area?

Page 23: Week 10 Recursion, External Application Interfacingen1811/13s1/lects/week10-recursion.pdf · ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 1 ENGG1811 Computing for Engineers

ENGG1811 © UNSW, CRICOS Provider No: 00098G W10 slide 23

Summary

• Recursion is a natural way to express some algorithms

– tail recursion can be replaced by iteration

– care must be taken to avoid recursion that re-evaluates the same thing over and over

– drawing recursive pictures may help in understanding how recursion works

• Sometimes you need to think creatively about solutions

• Office apps can create and manipulate documents and data through the use each other’s object models expressed in VBA.