Download Applet Java for Kruskal`s algorithm and Prim`s algorithm

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Red–black tree wikipedia , lookup

Quadtree wikipedia , lookup

Lattice model (finance) wikipedia , lookup

B-tree wikipedia , lookup

Interval tree wikipedia , lookup

Binary search tree wikipedia , lookup

Java ConcurrentMap wikipedia , lookup

Transcript
University "Politehnica" Timisoara
Automation and Computer Science Faculty
Computer Science and Software Engineering Department
Applet Java for Kruskal’s algorithm and Prim’s
algorithm
Rodrigues François
TIMISOARA
2008
Tutor: Asist. Drd. Ing. Ciprian-Bogdan CHIRILA
Table of contents
Introduction
............................................................................................................................................1
1. Analysis ....................................................................................................................................................6
1.1 Project Specification ............................................................................................6
1.2 About Html and Java ............................................................................................6
1.3 About Java Applet ...................................................................................................7
2. Design.........................................................................................................................................................9
2.1 Program structure ...................................................................................................9
2.2 The User Interface .................................................................................................11
3. Coding .....................................................................................................................................................17
3.1 The Dessin class ...................................................................................................17
3.2 The Kruskal class ..................................................................................................19
1.3 The Prim class ..........................................................................................................21
4. Examples ..............................................................................................................................................25
4.1 Kruskal’s algorithm ............................................................................................25
4.2 Prim’s algorithm.....................................................................................................27
Conclusion .................................................................................................................................................30
Bibliography ............................................................................................................................................31
Appendices ................................................................................................................................................32
Thanks
I would like to thank my family who help me to make
possible this trip to Romania.
Thank you to all the teacher of the Computer Science
department of the IUT A of Lille, to have transmitted us their
knowledge.
Thank you to the persons of the international relations
department of the IUT A of Lille, Camille Delrue, and
particularly Roxana Queste for her Romanian lessons.
Thank you to M. Patrick Lebègue, responsible ERASMUS at the
Computer Science department of the IUT A of Lille, for making
possible those European exchanges.
And thank you to M. Voda, the Romanian homolog of Patrick
Lebègue.
To finish I would like to thank Ciprian-Bogdan Chirila, the
teacher who has accompanied us in our work during those 3
months.
Abstract
For the “DUT Informatique” that I am preparing at the IUT
A of Lille, I am doing my work placement in Timisoara,
Romania, as part of an ERASMUS European exchange. I have been
welcomed in “Universitatea Politehnica Timisoara”, in the
computer science department. I have been supervised by
Ciprian-Bogdan Chirila.
With internet people have found a new way to learn at
home. The ELearning was born to be able to people to learn
wherever and whenever. It is the same for students and
university who use more and more this principle. That is why
I have been asked to make an application to help the students
to understand much better the way graph algorithms are
working. For that, we will use the Java programming language,
and applet for lots of reasons: it is a powerful tool, with
which it is easy to develop, and that allows making eyeattracting applications and animations with graphics2D.
We have decided to demonstrate two graph algorithms:
Kruskal, and Prim. The first step of the development was to
understand the two algorithms, and program them. Though, we
have created a simple user interface, using oval to represent
the numbers of vertices, line to represent the arc, and we
have made animations easy to understand, all that things being
directed by buttons, textfield and combo boxes. The third step
was to implement the two graph algorithms to include them with
the graphical view.
As a conclusion, we have spent three great months in
Romania, discovering a new culture, new people, and working on
an interesting subject. I have done my best to make a good
application that will be used by computer science students.
Introduction
With over 1.4 billion of people connected all around the
world on internet, the web became an unavoidable service to
many people. Internet became an important tool to sell
everything. Some domain as the New Technologies of Information
and Communication can be still found free on internet. This
domain can be called “elearning”.
The different actors of eLearning don’t have the same
definition but the most common definition says that the aim of
eLearning is to make use the learners the new technologies of
information and communication, such as CD-ROMs, Intranet,
Internet…
Arista Knowledge Systems thinks that eLearning is the use
of the whole power of the Network, to make possible to learn
anytime, anywhere. Contrary at Arista Knowledge Systems, Cisco
Systems thinks that eLearning is learning by Internet. Its
components include diffusion of contents in different formats,
learning administration, and an online community of learners,
developers and experts. ELearning allows to learn cheaper, to
multiply the access to trainings, and to make the learners
responsible of their training.
We can define four mains varieties of eLearning:
• The virtual classroom the virtual classroom model
of eLearning continues to be the most familiar
analogue
for
building
eLearning
programs.
The
intention of virtual classrooms is to extend the
structure
and
services
that
accompany
formal
education programs from the campus or learning center
to learners, wherever they are located. The virtual
classroom is for 2 learners who may be pursuing a
distance education degree made up entirely of online
lessons, and it may include campus-based courses,
where students join in from a variety of on- and offcampus location, in a real-time class session via the
Internet.
• Online learning this model of eLearning revolves
around its dependence on courseware, delivered over
the Internet to learners at a variety of locations
where the primary interaction between the learner and
the experiences of their learning occur via networked
computer technology.
• Rapid eLearning this is a direct response to
eLearning products that made it hard for nontechnical
subject matter experts and learners to contribute and
make use of multimedia learning content to the
knowledge base.
• Mobile learning Mobile learning builds on the
availability of ubiquitous networks and portable
digital devices, including laptop computers, PDAs,
game consoles, MP3 players, and mobile phones, and it
takes advantage of place-independent flexibility that
comes from working away from the desktop.
As reported by the elearning Guild (2008), 84.31% of the
Guild’s membership reports using at least one Adobe tool as
part of their regular elearning practice. Guild members report
that they use two to three Adobe products on any given
project, and that they keep four to six Adobe products on
hand. We can notice on the two next pictures that Adobe and
Microsoft are sharing this market, and that PDF documents are
the most published on the Internet.
2
From the teaching and learning perspective, the file type
is most significant in its ability to distribute specific
kinds of learning content in reliable, secure ways. From this
perspective, the Adobe “universal clients,” Adobe Reader® (on
89% of all computers connected to the Internet) and Flash
Player (on 98% of all computers connected to the Internet),
3
give learning organizations the assurance of knowing that
learning content produced using Adobe tools do not require any
additional client downloads for distributing digital content
assets. Some of the ways that this learning content is used
includes but is not limited to:
• Course resources, including syllabi, reading lists,
assignments, reading assignments
• Multimedia: applications, animations, pictures, videos,
blogs, wikis, podcasts
• Flexible content, including SCORM and AICC conforming
learning objects
• Web conferences
• Virtual workspaces
• Community: social media, social networks
Elearning supply some advantages for the learner and for
the developer.
For the learner:
• Customized training
• Easy access
• Gain of time
• Community of learners: chat, forum…
For the developer:
• Gain of time
• Dynamic content enrichment
There are also disadvantages, which are:
•
•
•
A bigger effort from the learners. It’s most
difficult to work alone, without constraints than
in a classroom.
Technical constraints: choice of the file format,
network bandwidth,…
Some trainings cannot be assimilated by eLearning
4
As can we see the eLearning market yield many dollars, it
is always growing up, and it will be more and more used in
schools, but also in companies, to train the employees.
5
1. Analysis
1.1. Project Specification
It was asked me to program an application to
help students for learn and understand the Kruskal’s
algorithm and the Prim’s algorithm. I must do a
demonstration of Kruskal’s algorithm and Prim’s
algorithm step by step with picture and explication
for these algorithms became easier. I have the
choice for the language to coding the application,
but the application must be integrate to a web page,
and this page will be lodge in Mr. Chirila’s
website. I choose java language to program this
application and I used Java applet to integrate my
program to a web page.
1.2. About Html and Java
HTML,
an
initialism
of
Hypertext
Markup
language, is the predominant markup language for web
pages. It provides a means to describe the structure
of text-based information in a document, and to
supplement that text with interactive forms, embedded
images, and other objects. HTML is written in the
form of tags, surrounded by angle brackets. HTML can
also describe the appearance and semantic of a
document, and can include embedded scripting language
code (such as JavaScript on Java applets) which can
affect the behavior of a Web browsers and other html
processors.
As for Java, It is a programming language
originally developed by Sun Microsystems and released
in 1995 as a core component of Sun Microsystems’ Java
platform. Java was created by James Gosling and
Patrick Naughton employed of Sun Microsystems in
1991, officially presented in 1995 to Sun World. The
language derives much of its syntax from C and C++
but has a simpler object model and fewer low-level
facilities. Java applications are typically compiled
to bytecode that can run on any Java virtual machine
regardless of computer architecture. Java was built
6
exclusively as an object oriented language. As a
result, almost everything is an object and all code
is written inside a class. To use Java in html, you
must program a Java applet that is placed in an HTML
document using the <applet> HTML element.
1.3. About Java Applet
A java applet is an applet delivered in the form
of Java bytecode. Java applets can run in a Web
browser using a Java Virtual Machine like Internet
Explorer or Mozilla Firefox, on a computer where the
Java Virtual Machine is installed. It can run in a
Sun’s AppletViewer too, which is a stand-alone tool
for testing applets. Java applets were introduced in
the first version of the Java language and there are
usually written in the Java programming language but
they can also be written in other languages that
compile to Java bytecode such as Jython which named
JPython in the past. Jython is a language which
combines the Java programming language and the Python
programming language.
Java applets are executed in a sandbox by most
web browsers, preventing them from accessing local
data, indeed it cannot write or read in the hard disk
of the computer. In computer security, a sandbox is a
security mechanism for safely running programs, java
applets are self-contained programs that run in a
virtual machine or scripting language interpreter
that does the sandboxing. In application streaming
schemes, the applet is downloaded onto a remote
client and may begin executing before it arrives in
its entirety. Java Applets are common in web
browsers, which use the mechanism to safely execute
untrusted code embedded in web pages.
Like
Java
is
an
independent
programming
language, Java applets can be executed by browsers
for many platforms, including the most famous
platforms: Windows, Linux, Mac OS or UNIX. Moreover
there are open source tools like applet2app which can
be used to convert an applet to a stand-alone Java
application or Windows/Linux executable. This has the
advantage of running a Java applet in offline mode
without the need for internet browser software. To
state the other advantages of Java applet we can say
that
7
•
•
•
•
•
•
It is simple to make it work on many
platforms.
The same applet can work on all installed
versions of Java at the same time, rather
than just the latest plug-in version only.
It is supported by most web browsers.
It will cache in most web browsers, so will
be quick to load when returning to a web page
but may get stuck in the cache and have
issues when new versions come out.
It can run a few slower than other compiled
languages such as C++ but many times faster
than JavaScript
It can move the work from the server to the
client, making a web solution more scalable
with the number of users.
On the other hand, the problem with Java applets
is that the whole application must be downloaded on
the client computer because nothing is performed on
the server. It causes problems for persons with a low
bandwidth but thank to ADSL only some people have
this
problem.
Java
applet
has
some
other
disadvantages like that
•
•
•
•
•
•
It requires the Java plug-in, which isn’t
available by default on all web browsers.
An implementation of the sun Java plug-in
does not exist yet for 64-bit processors.
It cannot start until the Java Machine is
running,
and
this
may
have
significant
startup time the first time it is used.
If untrusted, it has severely limited access
to the user’s system.
Applets may require a specific Java Runtime
Environment
Some
organizations
only
allow
software
installed by the administrators. As a result,
many users cannot view applets by default.
Of course, I could have used another programming
language to do this application like Flex but it’s
difficult
to
find
information
to
learn
this
programming language.
8
2. Design
2.1 Program structure
The application is separate in eight classes. We
have the MyApplet or MaFrame classes to start the
program.
These
two
classes
whose
extends
respectively the Applet class and the JFrame class,
just initialize the different classes (Dessin, North
and South), and placed components of these classes
on the good position.
Arc
and
Node
classes
are
just
classes
respectively using by Kruskal and Prim classes.
These two last classes are using for running
algorithm.
The three main classes for general design of the
application are Dessin, North and South classes.
The Dessin class extends JPanel class. This
class can display all the design of vertices and
arcs with graphics2D. This Graphics2D class extends
the Graphics class to provide more sophisticated
control over geometry, coordinate transformations,
color management, and text layout. This is the
fundamental
class
for
rendering
2-dimensional
shapes, text and images on the Java(tm) platform.
North and South classes must have an object
Dessin to run, because it is with these classes that
the user will be say to the application what he
wants that it does, and after the user say what he
wants, the display must be refresh. We can see on
these two next pictures of North and South classes,
methods and variables of them.
9
10
We will see with the user interface how these
two principals’ classes are running.
2.2 The User Interface
In
the
application,
we
have
chosen
to
demonstrate two algorithms: Kruskal algorithm and
Prim’s algorithm. We have composed the graphical
interface of three main parts.
The first part allows the user to choose which
algorithm it will be used by the application, and he
can define the number of node that he wants. We can
see the principle on this example.
11
For
the
choice
between
Kruskal
and
Prim
algorithm we will use the component JComboBox. We
must define the JComboBox and add to this component
the labels that we want to be displayed and
selectable. We define the background color for the
design and we add the component to the listener. To
finish we add the box to the panel.
private JComboBox box = new JComboBox();
box.addItem((“Kruskal”));
box.addItem((“Prim”));
box.setBackground(Color.WHITE);
box.addActionListener(this);
this.add(box);
If the user changes the choice of algorithm, we
update in the Dessin class the good choice.
If(e.getSource()==box){
d.setChoix( (String)box.getSelectedItem() );
}
We use after a JLabel to display “number of
Node”, then a Jtextfield to pick up the number of
nodes that the user wants and to finish a button for
send all of the information.
private JTextField saisie = new JTextField();
private JButton envoyer = new JButton(“send”);
private JLabel node = new JLabel(“Number of Node”);
We connect the button to the listener, we define
the design for the label, we fix the size of the
JTextField and we add all components to the panel.
envoyer.addActionListener(this);
node.setForeground(Color.WHITE);
this.add(node);
12
saisie.setColumns(4);
this.add(saisie);
this.add(envoyer);
When the user enters all information and when he
clicks on the send’s button, we pick up the text that
the user wants and we test if this text is a number
and if the user enters something. If these conditions
are alright we update in the Dessin class the number
of nodes after we have converted the string in
integer.
String s=saisie.getText();
If(s.matches(ExpressionReguliere) && s.length()>0){
d.setNbnoeud(Integer.parseInt(s));
}
The second main part is only the part where the
trees will be shape. After the user chooses the
number of node that he wants, nodes will be shape on
the second part. On first time, the application
shapes as much as oval that node define on the first
main part. And it writes the number of each node in
their center. If we take the same number of node that
the previously example, the graphical view will be
like that.
The last main part allows the user to define
arcs of the tree. He writes the first number of a
node then the second and to finish the weight of this
arc. When the user writes theses three information’s,
he can clicks on the send’s button and the arc will
13
be shape on the second main part with the node.
There are for this part, three JTextField, three
JLabel and two JButton. When the user enters all
information and he clicks on the send’s button, we
pick up each information and we stock them on
different string. We test if each string is a good
number and if the user does not put two same node or
number of node so high compared to the highest node.
Finally we test if the arc does not in the tree yet.
If he does not in, we put the arc after the last arc
that we put in the tree.
When the user enters all arcs that he wants, he
can clicks on the step’s button, the Kruskal
algorithm or the Prim algorithm will be run. The user
must click on the step’s button to see step by step
the advance of the program.
14
If the user continues to click, the display will
be fixed when the selected algorithm will finished.
The user can restart the application while
choosing a new number of nodes.
15
16
3. Coding
3.1 The Dessin class
The Dessin class is the principal class to
arcs and vertices of the tree. We can see on the
picture the composition of this class. We
explain now the method paint whose is the
important of this class.
draw
next
will
most
We call to the constructor of parent class to
initialize the graphics g, and we create a graphics2D
17
from g.
Then we recover the height and the width which
we will use to place different design.
int largeur = getSize().width;
int hauteur = getSize().height;
Now we will draw the initial arcs that the user
enters one by one. After the user clicks on the
send’s button, we must refresh the display, and draw
the last arc that the user enters. In a loop going of
0 to number of arcs, we will pick up the two vertices
of each arc, and we will calculate the angle that its
fact compared to the trigonometrical circle.
int sommet1=arbre[i].getSommet1();
int sommet2=arbre[i].getSommet2();
angle =(sommet1-1)*(2*Math.PI / nbNoeud);
angle1=(sommet2-1)*(2*Math.PI / nbNoeud);
Then we will calculate the coordinates to draw
the arc selected with the height and the width and
with cosine and sine.
int
int
int
int
x=(int)( (largeur/2)-( (largeur/4) *Math.cos(angle))+15 );
y =(int) ( hauteur/2- (hauteur/4) *Math.sin(angle)+15 );
x2=(int)( (largeur/2)-( (largeur/4) *Math.cos(angle1))+15);
y2=(int) ( hauteur/2- (hauteur/4) *Math.sin(angle1)+15 );
When we have the coordinates, we change
color and we draw the line and this weight.
the
g2.setColor(Color.gray);
g2.drawLine(x,y,x2,y2);
g.drawString(""+(arbre[i].getCout()) , (int) ((x+x2)/2 +30),
(int) ((y+y2)/2 +30) );
After we test if the final tree is create. If
the array is not empty and if the user clicks on the
step’s button, we draw as much arcs as the user has
clicked on the button. These arcs will be drawing in
red and they will be largest. Before drawing we save
the graphical context, we practice a zoom of two
pixels, we draw arcs and weight of arcs and we
18
restore the old graphical context.
Stroke s = g2.getStroke();
g2.setStroke(new BasicStroke(2));
/* all the code to draw arc and his weight */
g2.setStroke(s);
To finish we will draw each vertices. For each
vertex we will change the color in dark gray and we
will draw oval around the trigonometrical circle.
Then we change the color in white and we draw the
number of the vertex in the oval. At last we modify
the angle to be able to draw other vertex.
g2.fillOval( (int)( (largeur/2)-( (largeur/4) *Math.cos(angle))
), (int) ( hauteur/2- (hauteur/4) *Math.sin(angle) ), 30, 30) ;
g.setColor(Color.white);
g.drawString(""+(i+1)
,
*Math.cos(angle))
+10),
*Math.sin(angle)+20 ));
(int)(
(int)
(largeur/2)-(
(
hauteur/2-
(largeur/4)
(hauteur/4)
angle+=2*Math.PI / nbNoeud;
3.2 The Kruskal class
Kruskal algorithm is an algorithm in graph
theory that finds a minimum spanning tree for a
connected weighted graph. This means it finds a
subset of the edges that forms a tree that includes
every vertex where the total weight of all the edges
in the tree is minimized.
The algorithm consists in arranging by order of
weight all of edges of the graph, then to withdraw
one by one, test if the last arc does not form a
cycle, and add this arc to the final tree.
19
In the constructor, we just do a call to the
kruskal method with the missing parameters. Then we
initialize the papa array at -1 for all the array of
integer. This array will be used for test if there
are cycles or not. Now we do a sort of the tree to
have the lightest arc in the beginning of the array.
Then we do a loop going of 0 to number of arcs or 0
to number of nodes. We test if there is not a cycle,
and if it is true we enter the arc on the final tree.
When it finishes, we return if the temporary integer
nb is equals to number of node minus 1.
init(papa);
int ia = 0;
int nb = 0;
triGraph(g,nbarret);
while (ia < nbarret && nb < nbnoeud){
if (cyclep(papa, g[ia].getSommet1(), g[ia].getSommet2())){
arbre[nb] = g[ia];
nb++;
}
ia++;
}
return nb == nbnoeud - 1;
To test if there is a cycle on the tree, we use
an integer array initialize at -1 for all of value.
20
We call the cyclep method with this array and with
the two vertices of the arc. We look on the array if
the value stock on the array at the position of the
first number is higher than 0, if yes we stock the
number and start again with this new number for index
array. When the value stock on the array at the
position of the first number is not higher than 0, we
do the same things with the second number. When the
second loop is finish we test if the two new numbers
are equals, if not we stock the second new number on
the array at index of the first new number. We return
the Boolean corresponding at first new number equals
to second new number. If this Boolean is false, there
do not have a cycle on the tree.
public boolean cyclep(int[] t, int a, int b)
int i = a;
int j = b;
while (t[i] > 0){
i = t[i];
}
while (t[j] > 0){
j = t[j];
}
if (i != j){
t[i] = j;
}
return i != j;
}
{
3.3 The Prim class
Like Kruskal algorithm, Prim algorithm is an
algorithm in graph theory that finds a minimum
spanning tree for a connected weighted graph. This
means it finds a subset of the edges that forms a
tree that includes every vertex where the total
weight of all the edges in the tree is minimized.
The first step consists in choosing a vertex
randomly. We have now an ensemble containing 1 vertex
and 0 edges. Then, we build the minimal tree
recursively in the following way:
At stage n, we have already built a tree
containing n vertex and n-1 edges, we draw up the
list of all the edges binding a vertex of the
21
ensemble to a vertex which is not on the ensemble.
Then we choose an edge of minimal weight, which add
it in the tree. The tree contains now n+1 vertices
and n edges. The algorithm finishes when all vertices
of the graph are contained in the ensemble.
In the constructor, we just initialize the array
of node with as node as the user enters and we just
do a call to the prim method with the missing
parameters.
public void initNod(int nbnoeud){
node = new Node[nbnoeud];
for (int i=0;i<nbnoeud;i++){
node[i]=new Node(i+1);
}
}
Then we initialize the papa array at -1 for all
the array of integer and the tab array at false for
all the array of boolean. The papa array will be used
for test if there are cycles or not and the tab array
will be used for test if there are some nodes whose
do not on the final tree.
22
public boolean chercheEnsemble(int k){
boolean tmp=true;
for(int i=0;i<k;i++){
if(!tab[i]){
tmp=false;
}
}
return tmp;
}
Now we do a sort of the tree to have the
lightest arc in the beginning of the array. Then we
initialize the random number with millisecond of the
computer date and we take a random node. We put this
number on the ensemble.
triGraph(g,nbarret);
r.setSeed(date.getTimeInMillis());
Node tmp = node[r.nextInt(nbnoeud)];
tab[tmp.GetSommet() -1]=true;
Now we do a loop as long as all the nodes are
not on the ensemble. We do a second loop going of 1
to number of nodes. We save in a temporary arcs
array, all the arcs which link a node of the ensemble
with a node which does not make party of this, and we
update a variable with the number of arcs that we
have found.
int i=1;
int cpt=0;
while(i<=nbnoeud){
for(int j=0;j<nbarret;j++){
if(i==g[j].getSommet1() || i==g[j].getSommet2()){
if( (tab[ ( g[j].getSommet1() -1 ) ] && !tab[ (
g[j].getSommet2()
-1
)
])||(!tab[
(
g[j].getSommet1() -1 ) ] && tab[ ( g[j].getSommet2()
-1 ) ]) ){
temporaire[cpt]=g[j];
cpt++;
}
}
}
i++;
}
23
After the second loop, but already in the first
loop, we test if we have found arcs. If yes, we do a
sort of the temporary arcs array and we do a loop
going of 0 to number of arcs that we have found. We
test if there is not a cycle, if it true we enter the
arc on the final tree and we put the node in the
ensemble. When it finishes, we return if the
temporary integer nb is equals to number of node
minus 1.
if(cpt!=0){
triGraph(temporaire,cpt);
while(ia<cpt && !find){
if(cycle(papa,temporaire[ia].getSommet1(),
temporaire[ia].getSommet2())){
arbre[nb] = temporaire[ia];
nb++;
tab[temporaire[ia].getSommet1() -1]=true;
tab[temporaire[ia].getSommet2() -1]=true;
find=true;
}
ia++;
}
}
24
4. Examples
4.1 Kruskal’s algorithm
This is our original graph.
[1-2] is the shortest arcs, with length 10.
25
[2-5] is now the shortest arc that does not form a
cycle, with length 12.
The next arc, [2-3] with length 15, is
shortest arc that does not form a cycle.
now
the
26
The next shortest arcs are [1-5], with length 20,
but it would form a cycle (1 2 5) if it were chosen.
The arc [4-5] is the next shortest arc that does not
form a cycle. The process is finished because we
have find number of nodes minus one arcs. Two last
arcs would form cycles (2 3 5) and (2 3 4 5). The
minimum spanning tree is found, is shown in red.
4.2 Prim’s algorithm
This is our original weighted graph.
27
Vertex 5 has been arbitrarily chosen as a starting
point. We put the vertex 5 on the ensemble. Vertices 1, 2,
3 and 4 are connected to 5 through a single edge. 1 is the
vertex nearest to 5 and will be chosen as the second
vertex of the ensemble along with the arc [1-5].
The next vertex chosen is the vertex nearest to
either 5 or 1. 2 is 10 away from 1 and 50 away from 5, 3
is 90, and 4 is 60. 2 is the smallest distance away, we
put the vertex 2 on the ensemble because the arc [1-2]
does not form a cycle.
28
In this case, we can choose between 3, and 4. 3 is 90
away from 5, and 100 away from 2, 4 is 60 away from 5.4 is
nearest, we put the vertex 4 on the ensemble because the
arc [4-5] does not form a cycle.
Vertex 3 is the only remaining vertex. It is 90 away
from 5, 100 away from 2, and 110 away from 4. 5 is nearer,
we put the vertex 3 on the ensemble because the arc [3-5]
does not form a cycle.
Now all the vertices have been selected and the
minimum spanning tree is shown in red.
29
Conclusion
As a conclusion, I will say that this work placement gave
me a lot experience above all my work and human experience.
I will talk about the work in first. This project was
interesting for many reasons. I had to ameliorate myself in
java programming language, and to work in a new environment
nearer to the work world with eclipse that’s an integrated
development environment. Java is a very important programming
language and we can do lot of things with this language. I do
not know all the power of this language but I will continue to
learn by myself with the help of the web especially that the
internet technologies are things that are now completely
anchored in our lives.
Then, it has been interesting for algorithmic. During the
last two years, I had never been the first to understand
algorithms and sometime I had needed some help. So with the
work I’ve been entrusted, I was wanted to understand and write
them by myself, so that I was forced to analyse very deeply
the way graph algorithms are working to do what it asked me.
It has also been interesting to increase my skills in
Graphical User Interface programming and web programming.
Moreover, I have a little satisfaction because my work will be
useful for computer science students, who have difficulties
with Kruskal’s and Prim’s algorithms.
This work placement has also been interesting for the
human experience. Indeed the ERASMUS program is really
something whose learn about yourself, and I encourage people
to live this unique experience. When you arrive with a friend
in a foreign country, you do not have this impression that you
are lonely and you can meet lots of people faster, who are
from different countries, different cultures, and you form
emotional tie that will be unique. To be called on to mix with
many foreign people, frequent Moroccan or Spanish people,
going party with Romanian people, these three international
months were very nice and very enriching. I think I have well
improved my English level, but I also know a few Romanian
words, and I am able to order existential things in this
language!
30
Bibliography
[1] http://www.adobe.com/education/pdf/elearning/Promise_of_eLearning_wp_final.pdf
[2] Joseph. B. Kruskal: On the Shortest Spanning Subtree of a Graph and the Traveling
Salesman Problem. In: Proceedings of the American Mathematical Society, Vol 7 pp. 48–50
[3] Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein.
Introduction to Algorithm. Section 23.2: The algorithms of Kruskal and Prim, pp.567–574.
[4] Michael T. Goodrich and Roberto Tamassia. Data Structures and Algorithms in Java.
Section 13.7.1: Kruskal's Algorithm, pp.632.
[5] R. C. Prim: Shortest connection networks and some generalisations. In: Bell System
Technical Journal, 36 (1957), pp. 1389–1401
[6] D. Cherition and R. E. Tarjan: Finding minimum spanning trees. In: SIAM Journal of
Computing, 5 (Dec. 1976), pp. 724–741
31
Appendices
32
public class Arc{
private int sommet1, sommet2, cout;
public Arc(int sommet1, int sommet2, int cout){
this.sommet1 = sommet1;
this.sommet2 = sommet2;
this.cout = cout;
}
public int getSommet1(){
return sommet1;
}
public int getSommet2(){
return sommet2;
}
public int getCout(){
return cout;
}
public void setCout(int cout){
this.cout=cout;
}
}
public class Node{
private int sommet;
public Node(int sommet){
this.sommet=sommet;
}
public int GetSommet(){
return sommet;
}
}
import javax.swing.*;
import java.applet.*;
import java.awt.BorderLayout;
public class MyApplet extends Applet{
/**
*
*/
private static final long serialVersionUID = 1L;
Dessin d=new Dessin();
North n = new North(d);
South s=new South(d);
JFrame MaFrame = new JFrame ("Algorithms");
public void init(){
setLayout(new BorderLayout());
this.add(n,BorderLayout.NORTH);
this.add(d, BorderLayout.CENTER);
this.add(s,BorderLayout.SOUTH);
}
public void start(){}
public void stop(){}
public void destroy(){}
}
import java.awt.* ;
import javax.swing.*;
public class MaFrame extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
Dessin d=new Dessin();
North n = new North(d);
South s=new South(d);
public MaFrame() {
super("Algorithm");
setLayout(new BorderLayout());
this.add(n,BorderLayout.NORTH);
this.add(d, BorderLayout.CENTER);
this.add(s,BorderLayout.SOUTH);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800, 600);
}
public static void main(String[] args) {
JFrame cadre = new MaFrame();
cadre.setVisible(true);
}
}
import
import
import
import
import
import
import
java.awt.Color;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
javax.swing.*;
javax.swing.JComboBox;
javax.swing.JPanel;
javax.swing.JTextField;
public class North extends JPanel implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
private JTextField saisie =new JTextField();
private JButton envoyer = new JButton("send");
private JLabel node = new JLabel(" number of Node");
private JComboBox box = new JComboBox();
Dessin d;
private String ExpressionReguliere = "([0-9]*)";
public North(Dessin d){
this.d=d;
setBackground(Color.black);
box.addItem(("Kruskal"));
box.addItem(("Prim"));
box.setBackground(Color.WHITE);
box.addActionListener(this);
envoyer.addActionListener(this);
this.add(box);
node.setForeground(Color.white);
this.add(node);
saisie.setColumns(4);
this.add(saisie);
this.add(envoyer);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()== box){
d.setChoix( (String)box.getSelectedItem() );
}else{
String s=saisie.getText();
if(s.matches(ExpressionReguliere ) && s.length()>0){
d.setNbnoeud(Integer.parseInt(s));
d.arbre = new Arc[2500];
d.nbArc=0;
d.setCpt(0);
d.fin=false;
d.recommence=true;
d.repaint();
}
}
}
}
import
import
import
import
java.awt.*;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
javax.swing.*;
public class South extends JPanel implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
private JTextField saisie1 =new JTextField("");
private JTextField saisie2 =new JTextField("");
private JTextField poidArc =new JTextField("");
private JButton envoyer = new JButton("send");
private JButton step = new JButton("step");
private JLabel noeud1 = new JLabel("1st node");
private JLabel noeud2 = new JLabel("2nd node");
private JLabel cout = new JLabel("cout");
private String ExpressionReguliere = "([1-9][0-9]*)";
Dessin d;
public int nbnoeud =50;
Arc[]arbre = new Arc[nbnoeud*nbnoeud];;
Kruskal k;
Prim p;
public South( Dessin d){
this.d=d;
initArbre(arbre);
setBackground(Color.black);
envoyer.addActionListener(this);
step.addActionListener(this);
noeud1.setForeground(Color.white);
this.add(noeud1);
saisie1.setColumns(4);
this.add(saisie1);
noeud2.setForeground(Color.white);
this.add(noeud2);
saisie2.setColumns(4);
this.add(saisie2);
cout.setForeground(Color.white);
this.add(cout);
poidArc.setColumns(4);
this.add(poidArc);
this.add(envoyer);
this.add(step);
}
public void initArbre(Arc[]arbre){
for(int i=0;i<arbre.length;i++){
arbre[i]=null;
}
}
public void actionPerformed(ActionEvent event){
if(d.recommence){
initArbre(arbre);
d.recommence=false;
}
if(event.getSource() == envoyer){
String c1=saisie1.getText();
String c2=saisie2.getText();
String c3=poidArc.getText();
if(c1.matches(ExpressionReguliere ) &&
c2.matches(ExpressionReguliere )
&& c3.matches(ExpressionReguliere ) ){
int s1 =Integer.parseInt(c1);
int s2 =Integer.parseInt(c2);
int poid=Integer.parseInt(c3);
if(s1<=d.getNbnoeud() && s2<=d.getNbnoeud() && s1!=s2){
Arc a = new Arc(s1,s2,poid);
boolean deja=false;
int emplacement =0;
int i=0;
while(arbre[i]!=null && i<arbre.length){
if( ( arbre[i].getSommet1()==a.getSommet1()
||arbre[i].getSommet1()==a.getSommet2() )
&&( arbre[i].getSommet2()==a.getSommet1()
||arbre[i].getSommet2()==a.getSommet2() ) ){
emplacement=i;
deja =true;
}
i++;
}
if(!deja){
arbre[d.getNbArc()]=a;
d.addArc(a,d.getNbArc());
}else{
arbre[emplacement].setCout(poid);
d.modifArc(emplacement,poid);
}
d.repaint();
}
}
}else if(event.getSource()==step){
if(arbre[0]!=null){
if(d.getCpt()==0){
if(d.getChoix().equals("Kruskal")){
k=new Kruskal(arbre , d.getNbnoeud(), d.getNbArc());
d.arbreFinal=k.arbre;
}else{
p=new Prim(arbre , d.getNbnoeud(), d.getNbArc());
d.arbreFinal=p.arbre;
}
d.fin=true;
}
if(d.arbreFinal[d.getCpt()]!=null){
d.setCpt(d.getCpt()+1);
}
d.repaint();
}
}
}
}
import java.awt.* ;
import javax.swing.*;
public class Dessin extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
private int nbNoeud=0;
private String choixKP="Kruskal";
Arc[] arbre;
public int nbArc=0;
Arc[] arbreFinal=new Arc[2500];
public boolean fin=false;
public boolean recommence=false;
private int cpt=0;
public Dessin() {
arbre = new Arc[2500];
setBackground(Color.white);
}
public void paint(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
int largeur = getSize().width;
int hauteur = getSize().height;
double angle = 0;
Stroke s = g2.getStroke();
for(int i=0;i<nbArc;i++){
int sommet1=arbre[i].getSommet1();
int sommet2=arbre[i].getSommet2();
angle =(sommet1-1)*(2*Math.PI / nbNoeud);
double angle1=(sommet2-1)*(2*Math.PI / nbNoeud);
g2.setColor(Color.gray);
int x=(int)( (largeur/2)-( (largeur/4)
*Math.cos(angle))+15 );
int y =(int) ( hauteur/2- (hauteur/4)
*Math.sin(angle)+15 );
int x2=(int)( (largeur/2)-( (largeur/4)
*Math.cos(angle1))+15 );
int y2=(int) ( hauteur/2- (hauteur/4)
*Math.sin(angle1)+15 );
g2.drawLine(x,y,x2,y2);
g.setColor(Color.gray);
g.drawString(""+(arbre[i].getCout()) , (int) ((x+x2)/2
+30), (int) ((y+y2)/2 +30) );
}
for(int i=0;i<getCpt();i++){
if(arbreFinal[i]!=null){
int sommet1=arbreFinal[i].getSommet1();
int sommet2=arbreFinal[i].getSommet2();
angle =(sommet1-1)*(2*Math.PI / nbNoeud);
double angle1=(sommet2-1)*(2*Math.PI / nbNoeud);
g2.setColor(Color.red);
g2.setStroke(new BasicStroke(2));
int x=(int)( (largeur/2)-( (largeur/4)
*Math.cos(angle))+15 );
int y =(int) ( hauteur/2- (hauteur/4)
*Math.sin(angle)+15 );
int x2=(int)( (largeur/2)-( (largeur/4)
*Math.cos(angle1))+15 );
int y2=(int) ( hauteur/2- (hauteur/4)
*Math.sin(angle1)+15 );
g2.drawLine(x,y,x2,y2);
g2.setStroke(s);
g.setColor(Color.red);
g.drawString(""+(arbreFinal[i].getCout()) , (int)
((x+x2)/2 +30), (int) ((y+y2)/2 +30) );
}
}
angle=0;
for(int i=0;i<nbNoeud;i++){
g2.setColor(Color.darkGray);
g2.fillOval( (int)( (largeur/2)-( (largeur/4)
*Math.cos(angle)) ), (int) ( hauteur/2- (hauteur/4)
*Math.sin(angle) ), 30, 30) ;
g.setColor(Color.white);
g.drawString(""+(i+1) , (int)( (largeur/2)-( (largeur/4)
*Math.cos(angle)) +10), (int) ( hauteur/2- (hauteur/4)
*Math.sin(angle)+20 ));
angle+=2*Math.PI / nbNoeud;
}
}
public int getCpt(){
return cpt;
}
public void setCpt(int i){
this.cpt=i;
}
public int getNbnoeud(){
return nbNoeud;
}
public void setNbnoeud(int i){
this.nbNoeud = i ;
}
public void setChoix(String s){
this.choixKP = s ;
}
public String getChoix(){
return choixKP;
}
public int getNbArc(){
return nbArc;
}
public void addArc(Arc a,int nbarc){
arbre[nbarc]=a;
nbArc++;
}
public void modifArc(int emplacement, int poid){
arbre[emplacement].setCout(poid);
}
}
import java.util.Calendar;
import java.util.Random;
public class Prim{
public
public
public
public
public
int nNoeuds = 50;
int nAretes = nNoeuds * nNoeuds;
Arc[] arbre = new Arc[nNoeuds];
int[] papa = new int[nNoeuds];
Arc[] temporaire = new Arc[nNoeuds];
public boolean[] tab=new boolean[nNoeuds];
public Node[] node;
Random r = new Random();
Calendar date=Calendar.getInstance();
public Prim(Arc[] depart, int nbnoeud ,int nbarret){
initNod(nbnoeud);
prim(depart,nbnoeud,nbarret,papa,arbre);
}
public void initNod(int nbnoeud){
node = new Node[nbnoeud];
for (int i=0;i<nbnoeud;i++){
node[i]=new Node(i+1);
}
}
public void init(int[] t){
for (int i = 0; i < t.length; i++){
t[i] = -1;
tab[i]=false;
}
}
public boolean chercheEnsemble(int k){
boolean tmp=true;
for(int i=0;i<k;i++){
if(!tab[i]){
tmp=false;
}
}
return tmp;
}
public void triGraph(Arc[] t, int nbarret){
int j;
int k;
Arc a;
for (int i = 0; i < nbarret; i++){
j = i;
for (k = j; k < nbarret; k++){
if (t[k].getCout() < t[j].getCout()){
j = k;
}
}
a = t[j];
t[j] = t[i];
t[i] = a;
}
return;
}
public boolean cycle(int []pere, int a, int b){
int i = a;
int j = b;
while (pere[i] > 0){
i = pere[i];
}
while (pere[j] > 0){
j = pere[j];
}
if (i != j){
pere[i] = j;
}
return i != j;
}
public boolean prim(Arc[] g, int nbnoeud, int nbarret, int[]
papa,Arc[] arbre)
{
init(papa);
int nb = 0;
triGraph(g,nbarret);
r.setSeed(date.getTimeInMillis());
Node tmp = node[r.nextInt(nbnoeud)];
tab[tmp.GetSommet() -1]=true;
while (!chercheEnsemble(nbnoeud)){
boolean find =false;
int ia = 0;
int i=1;
int cpt=0;
while(i<=nbnoeud){
for(int j=0;j<nbarret;j++){
if(i==g[j].getSommet1() || i==g[j].getSommet2()){
if( (tab[ ( g[j].getSommet1() -1 ) ] && !tab[ (
g[j].getSommet2() -1 ) ])||(!tab[ (
g[j].getSommet1() -1 ) ] && tab[ (
g[j].getSommet2() -1 ) ]) )
{
temporaire[cpt]=g[j];
cpt++;
}
}
}
i++;
}
if(cpt!=0){
triGraph(temporaire,cpt);
while(ia<cpt && !find){
if (cycle(papa, temporaire[ia].getSommet1(),
temporaire[ia].getSommet2()))
{
arbre[nb] = temporaire[ia];
nb++;
tab[temporaire[ia].getSommet1() -1]=true;
tab[temporaire[ia].getSommet2() -1]=true;
find=true;
}
ia++;
}
}
}
return nb == nbnoeud - 1;
}
}
public class Kruskal {
public
public
public
public
int nNoeuds = 50;
int nAretes = nNoeuds * nNoeuds;
Arc[] arbre = new Arc[nNoeuds];
int[] papa = new int[nNoeuds];
public Kruskal(Arc[] depart ,int nbnoeud,int nbarret){
kruskal(depart,nbnoeud,nbarret,papa,arbre);
}
public void init(int[] t){
for (int i = 0; i < t.length; i++){
t[i] = -1;
}
}
public void triGraph(Arc[] t, int nbarret){
int
int
Arc
for
j
j;
k;
a;
(int i = 0; i < nbarret; i++){
= i;
for (k = j; k < nbarret; k++){
if (t[k].getCout() < t[j].getCout()){
j = k;
}
}
a = t[j];
t[j] = t[i];
t[i] = a;
}
return;
}
public boolean cyclep(int[] t, int a, int b){
int i = a;
int j = b;
while (t[i] > 0)
i = t[i];
}
{
while (t[j] > 0)
{
j = t[j];
}
if (i != j){
t[i] = j;
}
return i != j;
}
public boolean kruskal(Arc[] g, int nbnoeud, int nbarret,
int[] papa,Arc[] arbre)
{
init(papa);
int ia = 0;
int nb = 0;
triGraph(g,nbarret);
while (ia < nbarret && nb < nbnoeud)
{
if (cyclep(papa, g[ia].getSommet1(), g[ia].getSommet2()))
{
arbre[nb] = g[ia];
nb++;
}
ia++;
}
return nb == nbnoeud - 1;
}
}