Algorithm design booklet

advertisement
Algorithm Design in Java
What is an algorithm?
The series of steps that you develop to solve a problem is known as a solution algorithm. There
are many different algorithms for almost any problem.
An algorithm is a collection of instructions which, when performed in a specific sequence, produce
the correct result. The study of algorithms is at the heart of computer science.
Defining Your Problem
When writing code for computer programs it is important to have a systematic approach to design.
An algorithm is a procedure for solving a problem in terms of:

the actions to be performed and

the order in which these actions are to be executed
Take as an example of an algorithm making a cup of coffee:
1 boil the water in the kettle
2 put a spoon of coffee in the cup and
3 pour water into the cup
if done in a different order
1 put a spoon of coffee in the cup
2 pour water into the cup and
3 boil the water in the kettle
the coffee would be foul and cold, so order or program control is important.
Algorithm Description Methods
There are three main ways to express an algorithm, before the solution is put into code.
Psuedocode – essentially English with some predefined rules of structure and some keywords
that make it appear like program code
Flowcharts – A diagrammatic method showing operations in boxes connected by lines and arrows
that graphically show the flow of control
Programming Control Structures
There are five basic programming control structures that can be used in any algorithm.
In all cases there is only one entry point to the structure and one exit point.
Since each structure can be thought of as a process, more complex algorithms can be constructed
by replacing any single process by one or other of the structures.
Five general structures: Sequence, Selection, Binary Selection, Multiway Selection, Repetition
(Pre-Test & Post-Test)
These five general structures break down into 7 control structures and each program uses
combinations of these to implement the algorithm. The control structures are:
Sequence
working through statements in order
Selection
if
if/ else
switch
Rosny College 2009
single selection structure – either instruction is performed or
double selection structure – selects between 2 different
actions or groups of actions
multiple selection structure – many different options
skipped
Page 1 of 7
Computer Science
Repetition
Algorithm Design
for
while
do/while
repeat code for a given number of times
repeat code as long as a given condition is true
we do not recommend using this version
Control Structure: Sequence
In a computer program or an algorithm, sequence involves simple steps which are executed one
after the other. The steps are executed in the same order in which they are written.
Example problem:
Write a set of instructions that describe how to make a pot of tea.
Pseudocode
BEGIN
Fill a kettle with water
Boil the water in the kettle
Put the tea leaves in the pot
Pour boiling water in the pot
END
Flowchart
Begin
Fill a kettle with water
Boil the water in the kettle
Put the leaves in the pot
Pour boiling water in the
pot
End
Exercise: Algorithm in Pseudocode and Flowchart for making toast.
Rosny College 2009
Page 2 of 7
Computer Science
Algorithm Design
Selection
Selection is used in a computer program or algorithm to determine which particular step or set of
steps is to be executed. A selection statement can be used to choose a specific path dependent
on a condition. There are two types of selection: binary (twa-way branching) selection and multiway (many way branching) selection.
Binary Selection
Binary selection allows the choice between two possible paths. If the condition is met then one
path is taken, otherwise the second possible path is taken.
Psuedocode:
1.
2.
IF condition THEN
IF condition THEN
Process 1
Process 1
ENDIF
ELSE
Process 2
ENDIF
Flowcharts
1.
2.
False
True
conditi
on
conditi
on
Process 1
Process 2
Process 1
Example problem 1: Set of instructions to describe when to answer the phone (type 1)
Example problem 2: Set of instructions to follow when approaching a set of traffic control lights
(type 2 – assuming light is green or other)
Possible Code Structures using IF statements:
if(statement)
if(statement)
{
{
//this code if
//this code if
// statement was true
// statement was true
}
} else {
//this code if
//statement was false
}
Rosny College 2009
if(statement)
{
//this code if
// statement was true
} elseif (another statement)
{
//this code if most recent
// statement was true
} else {
//this code if statements
// were all false
}
Page 3 of 7
Computer Science
Algorithm Design
Multi-way Selection
Multi-way selection allows for any number of possible choices, or cases. The path taken is
determined by the selection of the choice which is true. Multi-way selection is often referred to as
a case structure, and is also known as a switch statement.
Psuedocode:
SWITCH expression evaluates to
case a: process a
case b: process b
…
…
default:
default process
ENDSWITCH
Flowchart
Example Problem: Set of instructions that describes how to
possible signals at a set of traffic control lights.
respond to all
expression
Choice a
Process a
Choice b
Process b
otherwise
Default
process
Possible Code Structures using SWITCH statements:
switch(variable)
{
case a: //do this code if this was the right case
break;
case b: //do this code if this was the right case
break;
case c: //do this code if this was the right case
break;
default: //do this code if the variable didn’t match any of the cases
break;
}
Rosny College 2009
Page 4 of 7
Computer Science
Algorithm Design
Repetition
Repetition allows for a portion of an algorithm or computer program to be done any number of
times dependent on some condition being met. An occurrence of repetition is usually known as a
loop.
An essential feature of repetition is that each loop has a termination condition to stop the
repetitions, or the obvious outcome is that the loop never completes execution (an infinite loop).
The termination condition can be checked/tested at the beginning or end of the loop and is known
as a pre-test or post-test respectively.
Repetition: Pre-Test
A pre-tested loop is so-named because the condition has to be met at the very beginning of the
loop or the body of the loop is not executed. This construct is often called a guarded loop. The
body of the loop is executed repeatedly while the termination condition is true.
Pseudocode
Flowchart
(While loop)
WHILE condition is true
Process(es)
ENDWHILE
(For loop)
FOR expression
Process(es)
ENDFOR
Cond
Process(es)
Example problem: Determine a safety procedure for travelling in a car
Possible Code Structures using WHILE loop:
Int I = 0;
Int y = 20;
While(i<=10 )
{
g.drawString(“”+I, 20, y);
y=y+20;
}
Possible Code Structures using FOR loop:
Int y = 20;
For(int i=1; i<=10; i++)
{
g.drawString(“” +i, 20, y);
y=y+20;
}
Rosny College 2009
Page 5 of 7
Computer Science
Algorithm Design
Repetition: Post-Test
A post-tested loop executes the body of the loop before testing the termination condition. This
construct is often referred to as an unguarded loop. The body of the loop is repeatedly executed
until the termination condition is true.
An important difference between a pre-test and post-test loop is that the statements of a post-test
loop are executed at least once even if the condition is originally true, whereas the body of the pretest loop may never be executed if the termination condition is originally true. A close look at the
representations of the two loop types makes this point apparent.
Pseudocode
Flowchart
DO
Prcoess(es)
WHILE condition is true
Process(es)
Cond
Example problem: Determine a procedure to beat egg whites until fluffy.
Possible Code Structures using Do loop:
Int I = 0;
Int y = 20;
Do
{
g.drawString(“”+I, 20, y);
y=y+20;
} while(i<=10 );
NOTE: It is important to remember that using algorithm description methods allow us to break
down a problem, so that we can evaluate its effectiveness.
Algorithms should not be written using actual code.
Similarly, code should not be written using psuedocode keywords (ie. ‘endwhile’ does not exist in
java)
Developing algorithms helps programmers “think through” a problem before converting it to Java.
The traditional, simple and effective method to do this is called Top-down design (or stepwise
refinement). Here an outline or general specification of the problem is made. This is broken
down to a number of smaller sub-goals needed to complete the task. These sub-goals form
modules - hence the concept of modular programming.
The discrete modules known as can then be written and tested separately.
Rosny College 2009
Page 6 of 7
Computer Science
Algorithm Design
A method is a piece of code that does a particular job in a class. Methods can be used many times
in the original class and can be imported into other classes.
However, top-down design, which is ordered, sequential and deals almost entirely with the
instructions needed to solve a problem, is not suited to event-driven programs such as Java.
In an event-driven program the order in which actions are taken is determined by responses from
the user when interacting with the program’s GUI (Graphical User Interface). So event-driven
programs should be solved considering what is the initial (start state) and what happens when a
particular condition occurs.
Consider a guessing game where the program chooses a random number between 1 and 10, and
the user has to guess what it is. The program should display an appropriate message (number out
of range, correct, too low, or too high) within the paint area. The program should also count and
display the number of guesses the user has had.
The desired algorithm:
INITIALLY:


choose a secret number
start the count of number of guesses at 0
WHEN the user enters a guess:





get a guess from the user
add 1 to the count of the number of guesses
display the number of guesses
if the guess is out of range,
 say “number must be between 1 and 10”
else
{
 if the guess is smaller, say "too low"
 if the guess is higher, say "too high"
}
if the guess equals secret number,
{
 say "well done"
 choose another secret number
 start the count of number of guesses at 0
}
We will need to use the action method to get the data input and call the repaint() method to
display results in the applet window. Remember repaint calls another method update to clear the
display and then call paint.
When paint is called we want to display a short message telling the user what to do next.
When the action method is called it performs the following steps:
 gets a guess from the user
 adds 1 to the count of the number of guesses
 and then calls repaint which will clear the display and call paint
Paint then needs to display the appropriate message to the user, and show the number of
guesses.
Rosny College 2009
Page 7 of 7
Download