Date post: | 26-Dec-2015 |
Category: |
Documents |
Upload: | hugh-rogers |
View: | 216 times |
Download: | 3 times |
1COMP3100e
Developing Microsoft .Net
Applications for Windows (Visual
Basic .Net)Class 7
COMP3100E
2COMP3100e
Objectives
Homework Recursion
3COMP3100e
Recursion
From Wikipedia, the free encyclopedia. In mathematics and computer science, recursion
specifies (or constructs) a class of objects (or an object from a certain class) by defining a few very simple base cases (often just one), and then defining rules to break down complex cases into simpler cases.
Recursion is sometimes mistaken for circular reasoning. However, the crucial difference is that its base cases are defined in terms that are not part of the system. Since all the cases break down into base cases, and the base cases are in different terms, the analysis stops. That is, it is not circular.
An example of a recursive imageFor example, the following is a recursive definition of person's ancestors:– One's parents are one's ancestors (base case); – The parents of any ancestor are also ancestors of
the person under consideration (recursion step). For instance, your ancestors are:
– your parents, and – your parents' parents (= grandparents), and – your grandparents' parents, and – everyone else you get by successively adding
ancestors It is convenient to think that a recursive
definition defines objects in terms of "previously defined" objects of the class to define.
4COMP3100e
Recursion
Definitions such as these are often found in mathematics. For example, the formal definition of natural numbers is: 0 is a natural number, and each natural number has a successor, which is also a natural number.
To visualize recursion, it can be helpful to consider recursively-defined geometric figures, such as the Koch curve, the Sierpinski triangle, or the Cantor set.
Also, examples of recursion abound in natural language, often appearing as, or transforming into jokes. These jokes can help one develop an intuition for recursion.– For example, responding to the question, "What
do you mean what do I mean?" with "What do you mean 'What do you mean what do I mean?'?", can clearly go on forever, although it is unclear how many iterations can be meaningful...
Although artist- and poet-types often make jokes of this kind, studying recursion in mathematics and programming languages can help to understand the meaning and philosophy of language in this sense, and a careful observation of language in this sense can help to understand recursion.
5COMP3100e
Koch Curve
6COMP3100e
Koch Curve
The Koch curve is a mathematical curve, and one of the earliest fractal curves to have been described. It appeared in a 1904 paper entitled "Sur une courbe continue sans tangente, obtenue par une construction géométrique élémentaire" by the Swedish mathematician Helge von Koch. The better known Koch snowflake (or Koch star) is the same as the curve, except it starts with an equilateral triangle instead of a line segment. Eric Haines has developed the sphereflake fractal, a three-dimensional version of the snowflake.
One can imagine that it was created by starting with a line segment, then recursively altering each line segment as follows:
– divide the line segment into three segments of equal length. – draw an equilateral triangle that has the middle segment from
step one as its base. – remove the line segment that is the base of the triangle from step
2. After doing this once the result should be a shape
similar to the Star of David. The Koch curve is in the limit approached as the
above steps are followed over and over again. The Koch curve has infinite length because each time
the steps above are performed on each line segment of the figure its length increases by one third. The length at step n will therefore be (4/3)n and the fractal dimension is log4/log3 =~1.26 (bigger than the dimension of a line {1} but smaller than Peano's Space-filling curve {2}).
The Koch curve is continuous, but not differentiable anywhere.
The area of the Koch snowflake is 8/5 that of the initial triangle, so an infinite perimeter encloses a finite area.
7COMP3100e
Sierpinski Triangle
The Sierpinski triangle, also called the Sierpinski gasket, is a fractal, named after Wacław Sierpiński.
Sierpiński demonstrated that this fractal is a universal curve, in that any possible one-dimensional graph, projected onto the two-dimensional plane, is homeomorphic to a subset of the Sierpinski gasket.
For curves that cannot be drawn on a 2D surface without self-intersections, the corresponding universal curve is the Menger sponge.
8COMP3100e
Recursion in Language
Linguist Noam Chomsky produced evidence that unlimited extension of a language such as English is possible only by the recursive device of embedding sentences in sentences.
– Thus, a talky little girl may say, "Dorothy, who met the wicked Witch of the West in Munchkin Land where her wicked Witch sister was killed, liquidated her with a pail of water."
– Clearly, two simple sentences — "Dorothy met the Wicked Witch of the West in Munchkin Land" and "Her sister was killed in Munchkin Land" — can be embedded in a third sentence, "Dorothy liquidated her with a pail of water," to obtain a very talky sentence.
Niels K. Jerne, the 1984 Nobel Prize laureate in Medicine and Physiology, used Chomsky's transformational-generative grammar model to explain the human immune system, equating "components of a generative grammar ... with various features of protein structures." The title of Jerne's Stockholm Nobel lecture was The Generative Grammar of the Immune System.
Here is another, perhaps simpler way to understand recursive processes:
– Are we done yet? If so, return the results. Without such a termination condition a recursion would go on forever.
– If not, simplify the problem, solve those simpler problem(s), and assemble the results into a solution for the original problem. Then return that solution.
A more humorous illustration goes: – "In order to understand recursion, one must first understand
recursion." Or perhaps more accurate is the following due to Andrew Plotkin: "If you already know what recursion is, just remember the answer. Otherwise, find someone who is standing closer to Douglas Hofstadter than you are; then ask him or her what recursion is."
Examples of mathematical objects often defined recursively are functions, sets, and especially fractals.
9COMP3100e
Recursive Humor
Recursion – See "Recursion". – This is a parody on references in dictionaries,
which in some careless cases may lead to circular definitions; in fact the above is the shortest possible one.
– Every joke has an element of wisdom, and also an element of misunderstanding.
– This one is also the second-shortest possible example of an erroneous recursive definition of an object, the error being the absence of the termination condition (or lack of the initial state, if to look at it from an opposite point of view).
Newcomers to recursion are often bewildered by its apparent circularity, until they learn to appreciate that a termination condition is key.
Other examples are recursive acronyms, such as GNU, PHP or TTP (Dilbert; "The TTP Project").
– "GNU" is a recursive acronym for GNU's Not Unix.– Today, the official meaning is the recursive acronym
"PHP: Hypertext Preprocessor". – TTP stands for “The TTP Project”– The labels on Miller beer say "Miller MGD Genuine
Draft". » However, MGD stands for Miller Genuine Draft. » So the labels are saying "Miller Miller Genuine Draft
Genuine Draft". "The way to understand recursion is to
understand recursion"
10COMP3100e
Recursion in Programming
Recursion in computer programming defines a function in terms of itself. – One example application of recursion is in
parsers for programming languages. » The great advantage of recursion is that an
infinite set of possible sentences, designs or other data can be defined, parsed or produced by a finite computer program.
One basic form of recursive computer program is to define one or a few base cases, and then define rules to break down other cases into the base case. This is analytic, and is the most common design for parsers for computer languages.
Another, similar form is generative recursion. This is synthetic. – In this scheme, the computer uses rules to
assemble cases, and starts by selecting a base case.
– This scheme is often used when a computer must design something automatically, such as code, a machine part or some other data.
11COMP3100e
Recursion in Programming
The Quicksort and Mergesort algorithms are also commonly done using recursion, which allows them to run in an average of O(n log n) time.
Many operations involving tree data structures also use recursion, as it is often quite difficult to iteratively traverse a tree of unknown length.
In addition, some numerical methods for finding approximate solutions to mathematical equations use recursion. In Newton's method, for example, an approximate root of a function is provided as initial input to the method. The calculated result (output) is then used as input to the method, with the process repeated until a sufficiently accurate value is obtained.
12COMP3100e
Displaying values from 1 to 10
The Program Structure Loop is generally used in programming to print the values of one to 10
Example:Sub oldcount(ByVal max As _ Integer)
Dim num As Integer For num = 1 To max LstNumbers.Items.Add(num) NextEnd Sub
13COMP3100e
Inclusively Recursive
Sub newcount(ByVal num As _ Integer)
If num > 1 Then
newcount(num - 1)
End If
LstNumbers.Items.Add(num)
End Sub
14COMP3100e
The Newtonian Square Root
#include <stdio.h>#include <math.h>
enum boolean {no, yes};
void main(void){ float oldval, newval; int num; enum boolean finished = no;
printf("\nEnter value for square root: "); scanf("%d",&num); oldval= (1.0+num)/2.; while (!finished) { newval=(oldval+num/oldval)/2.;
if (newval >= oldval) finished= yes; oldval = newval;
} printf("Square root of %d is
%f",num,newval);
15COMP3100e
Newton Square Root in VB.Net
Private Function NewtonSqrt(ByVal num As Integer) As Double
Dim oldval, newval As Double Dim finished As Boolean
newval = 0 If num > 0 Then finished = False oldval = (1.0 + num) / 2 Do newval = (oldval + num / oldval) / 2 If (newval >= oldval) Then finished = True End If oldval = newval Loop While Not finished End If Return (newval)
End Function
16COMP3100e
Newtonian Recursive Square Root
Private Function betterGuess(ByVal num _ As Double, ByVal oldval As Double) As Double Return ((oldval + num / oldval) / 2)End Function
Private Function closeEnough(ByVal newval _ As Double, ByVal oldval As Double) As Boolean Return (Math.Abs(newval - oldval) < 0.000001)End Function
Private Function RecursiveSqrt(ByVal num _ As Double, ByVal oldval As Double) As Double Dim answer As Double
If closeEnough(num / oldval, oldval) Then answer = oldval Else answer = RecursiveSqrt(num,_ betterGuess(num, oldval)) End If Return (answer)End Function
17COMP3100e
Calculating Pi
Private Function Pi(ByVal num As Integer) As Double
If (num = 1) Then Return (1)Else If (num Mod 2 = 1) Then Return (Pi(num - 1) + 1 / (2 * num - 1))
Else Return (Pi(num - 1) - 1 / (2 * num - 1))
End IfEnd IfEnd Function
18COMP3100e
Calculating Pi Again
Private Function PiAgain(ByVal n As Integer) As Double
If (n = 1) Then Return (0.833333) Else If (n Mod 2 = 1) Then Return (PiAgain(n - 1) + (Power(0.5, 2 * n - 1) +
Power(0.33333, 2 * n - 1)) / (2 * n - 1)) Else Return (PiAgain(n - 1) - (Power(0.5, 2 * n - 1) +
Power(0.33333, 2 * n - 1)) / (2 * n - 1)) End If End IfEnd Function
Private Function Power(ByVal b As Double, ByVal e As Integer) As Double
If (e >= 0) Then If (e = 1) Then Return (b) Else Return (b * Power(b, e - 1)) End If Else If (e = -1) Then Return (1 / b) Else Return (1 / b * Power(b, e + 1)) End If End IfEnd Function
19COMP3100e
Mutually Recursive
Option Explicit
Private Sub CMDDisplay_Click()
LBLAlphabet = ""
A (VSBChar.Value)
End Sub
Private Sub VSBChar_Change()
lblChar = Chr$(VSBChar.Value)
End Sub
Public Sub A(c As Integer)
If (Chr$(c) > "A") Then
B (c)
End If
LBLAlphabet = LBLAlphabet + Chr$(c)
End Sub
Public Sub B(c As Integer)
A (c - 1)
End Sub
20COMP3100e
Fibinonacci
Private Sub vsbnum_Scroll(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Handles vsbnum.Scroll
lblnum.Text = CStr(100 - vsbnum.Value)
If vsbnum.Value <> 100 Then
lblfib.Text = CStr(fib(100 - vsbnum.Value))
Else
lblfib.Text = 0
End If
End Sub
Public Function fib(ByVal num As Integer) As Integer
If ((num = 1) Or (num = 2)) Then
fib = 1
Else
fib = fib(num - 1) + fib(num - 2)
End If
End Function
21COMP3100e
Tower of Hanoi
move_tower(k : INTEGER; start_peg, finish_peg, other_peg:INTEGER) is
-- move tower of k disks from start_peg to finish_peg via other_peg
localdoif k = 1 thenmove_disk_0(start_peg)elsemove_tower(k-1, start_peg, spare_peg,
finish_peg)move_other_disk(k, start_peg, finish_peg)move_tower(k-1, spare_peg, finish_peg,
start_peg)endend -- move_disks
22COMP3100e
Code for Tower of Hanoi
Public Sub movedisk(ByVal n As Integer, _ ByVal A As Integer, _ ByVal C As Integer, _ ByVal B As Integer) 'n,A,B,C; /* number to move, source pole, ‘ destination pole and spare pole respectively Dim Buffer As String
If (n = 1) Then Buffer = "Move from " + CStr(A) + " to " +
CStr(C) lstmove.Items.Add(Buffer) Else movedisk(n - 1, A, B, C) movedisk(1, A, C, B) movedisk(n - 1, B, C, A) End IfEnd Sub
Private Sub vsbDisks_Scroll(ByVal sender As _ System.Object, ByVal e As _ System.Windows.Forms.ScrollEventArgs) Handles _ vsbDisks.Scroll
LblDisks.Text = CStr(100 - vsbDisks.Value) lstmove.Items.Clear() movedisk(100 - vsbDisks.Value, 1, 3, 2)End Sub
23COMP3100e
Tower of Hanoi
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
LblDisks.Text = CStr(100 - vsbDisks.Value) movedisk(100 - vsbDisks.Value, 1, 3, 2)End Sub
24COMP3100e
QuickSort
Public Sub quicksort(ByVal first As Integer, _ ByVal last As Integer) Dim pivotpt As Integer Dim left As Integer Dim right As Integer
If Not (first >= last) Then pivotpt = first left = pivotpt + 1 right = last Do Do While (left <= right) AndAlso _ (table(left) <= table(pivotpt)) left = left + 1 Loop Do While (table(right) > table(pivotpt)) right = right - 1 Loop If (right > left) Then Call swap(left, right) End If Loop While (left < right) Call swap(pivotpt, right) Call quicksort(first, right - 1) Call quicksort(right + 1, last) End If End Sub