# More examples of JavaScript Recursion

Source: Internet
Author: User

More examples

The second recursive example is to find the maximum common divisor of two natural numbers (whether it has returned to the memorable middle school era ). The following program uses the Classic Division of the moving phase.

[Javascript]
// Greatest common divisor
// Assume that a and B are positive integers.
Function gcd (a, B ){
If (a <B) return gcd (B, a); // ensure a> = B
Var c = a % B;
If (c = 0)
Return B;
Else
Return gcd (B, c );
}

// Greatest common divisor
// Assume that a and B are positive integers.
Function gcd (a, B ){
If (a <B) return gcd (B, a); // ensure a> = B
Var c = a % B;
If (c = 0)
Return B;
Else
Return gcd (B, c );
}
In addition to the above conditions or solutions that can be converted to the calculation of the recursive definition of mathematics, the recursive method is also applicable to the data structure involved in it, that is, the problems defined in the form of recursion, such as linked list, graph, and tree.

Now let's look at an example of a maze. The maze can be abstracted into a mathematical graph. Each intersection is a point, and the path between them is an edge. Two special points are defined as the entry and exit respectively.

The following are the points and diagrams defined in Javascript. Each vertex contains an id as the number and sign, and adjacent vertices are saved in an array. The figure shows a method for adding vertices, a more convenient method for directly adding vertex IDs, and a method for adding edges.

[Javascript]
// Define a vertex
Function Vertex (id ){
Var stem = {};
Stem. id = id;
Return stem;
}
// Define a graph
Function Graph (){
Var stem = {}, vertices = {};
// Add vertices to the graph
If (vertex instanceof Array ){
For (var I = 0, v = vertex; I <v. length; I ++ ){
Vertices [v [I]. id] = v [I];
}
}
Vertices [vertex. id] = vertex;
}
// Create vertices from ids and add them to the graph
Var id;
For (var I = 0; I <ids. length; I ++ ){
Id = ids [I];
Vertices [id] = Vertex (id );
}
}
// Create an edge between two vertices
Function connect (i1, i2 ){
Var v1 = vertices [i1], v2 = vertices [i2];
If (v1 & v2 ){
}
}
Stem. vertices = vertices;
Stem. connect = connect;
Return stem;
}

// Define a vertex
Function Vertex (id ){
Var stem = {};
Stem. id = id;
Return stem;
}
// Define a graph
Function Graph (){
Var stem = {}, vertices = {};
// Add vertices to the graph
If (vertex instanceof Array ){
For (var I = 0, v = vertex; I <v. length; I ++ ){
Vertices [v [I]. id] = v [I];
}
}
Vertices [vertex. id] = vertex;
}
// Create vertices from ids and add them to the graph
Var id;
For (var I = 0; I <ids. length; I ++ ){
Id = ids [I];
Vertices [id] = Vertex (id );
}
}
// Create an edge between two vertices
Function connect (i1, i2 ){
Var v1 = vertices [i1], v2 = vertices [i2];
If (v1 & v2 ){
}
}
Stem. vertices = vertices;
Stem. connect = connect;
Return stem;
} The idea of getting out of the maze is to traverse all adjacent points of each point from the entrance until the exit is found. Because the graph may contain loops, that is, the circle may appear in the Maze. Therefore, every point that has been reached in the program is recorded. If it is encountered again, the previous point is returned. If an exit exists, the system exits the whole traversal and returns to the entrance. Each vertex that passes through the process is recorded, and the route from the entrance to the exit is finally written. This is not an optimal solution. The result may not be the shortest route. However, as long as the entrance and exit are connected, a route can be found.

[Javascript]
// Try to walk out of the maze and print the result
Function walkOut (entry, exit ){
Var visited = [], path = [];

Function walk (vertex ){
If (vertex = exit) {// find the exit
Path. push (vertex );
Return true;
}
If (visited. indexOf (vertex)>-1) {// the vertex was visited
Return false;
}
Visited. push (vertex); // remember each vertex
Var length = connected. length;
If (length = 0) {// the vertex is isolated
Return false;
}
For (var I = 0; I <length; I ++ ){
If (walk (connected [I]) {// try each adjacent vertex
Path. push (vertex );
Return true;
}
}
}

Function printPath (){
Var footprint = '';
Var length = path. length;
For (var I = length-1; I>-1; I --){
Footprint + = path [I]. id;
Footprint + = I === 0? '': '> ';
}
Print (footprint );
}

If (walk (entry )){
PrintPath ();
}
Else {
Print ('No! ');
}
}

// Try to walk out of the maze and print the result
Function walkOut (entry, exit ){
Var visited = [], path = [];

Function walk (vertex ){
If (vertex = exit) {// find the exit
Path. push (vertex );
Return true;
}
If (visited. indexOf (vertex)>-1) {// the vertex was visited
Return false;
}
Visited. push (vertex); // remember each vertex
Var length = connected. length;
If (length = 0) {// the vertex is isolated
Return false;
}
For (var I = 0; I <length; I ++ ){
If (walk (connected [I]) {// try each adjacent vertex
Path. push (vertex );
Return true;
}
}
}

Function printPath (){
Var footprint = '';
Var length = path. length;
For (var I = length-1; I>-1; I --){
Footprint + = path [I]. id;
Footprint + = I === 0? '': '> ';
}
Print (footprint );
}

If (walk (entry )){
PrintPath ();
}
Else {
Print ('No! ');
}
} We can test this code's ability to walk through the maze.

[Javascript]
Function testMaze (){
Var g = Graph ();
G. addIds ([1, 2, 3, 4, 5, 6]);
G. connect (1, 2 );
G. connect (1, 3 );
G. connect (1, 4 );
G. connect (2, 3 );
G. connect (3, 5); // you can draw this picture.
WalkOut (g. vertices , g. vertices ); // 1> 2> 3> 5
WalkOut (g. vertices , g. vertices ); // unable to get out!
WalkOut (g. vertices , g. vertices ); // 2> 1> 3> 5
}

Function testMaze (){
Var g = Graph ();
G. addIds ([1, 2, 3, 4, 5, 6]);
G. connect (1, 2 );
G. connect (1, 3 );
G. connect (1, 4 );
G. connect (2, 3 );
G. connect (3, 5); // you can draw this picture.
WalkOut (g. vertices , g. vertices ); // 1> 2> 3> 5
WalkOut (g. vertices , g. vertices ); // unable to get out!
WalkOut (g. vertices , g. vertices ); // 2> 1> 3> 5
} In real life, we can also use this stupid way to walk out of any possible maze, as long as you write your pen and paper at every fork in the road to write down your choice.

Related Keywords:
Related Article

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.