Home Web Front-end JS Tutorial More examples of recursion in JavaScript

More examples of recursion in JavaScript

Nov 28, 2016 am 11:36 AM
JavaScript

More examples

The second recursive example is to find the greatest common divisor of two natural numbers (have you ever gone back to your nostalgic middle school days). The program below uses the classic euclidean division method.


[javascript]
//greatest common divisor
//Assume a and b are both 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
//Assumption a and b are both 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 into mathematical recursive definition calculations, the recursive method is also applicable to the data involved Structures are problems defined in a recursive form, such as linked lists, graphs, trees, etc.

Now let’s look at a maze example. The maze can be abstracted into a mathematical diagram. Each fork in the road is a point, and the roads in between are edges. Two special points are defined as entrance and exit respectively.

The following are points and graphs defined in Javascript. Each point contains an id as a number and label, and adjacent points are saved in an array. The graph has a method for adding points, a more convenient method of directly adding point IDs, and a method for adding edges.

[javascript]
//define a vertex
function Vertex(id){
var stem={};
stem.id=id;
stem.adjacent=[];
return stem;
}
//define a graph
function Graph(){
var stem={}, vertices={};
//add vertices to the graph
function add(vertex){
if (vertex instanceof Array){
for (var i=0 , v=vertex; i }
vertices[vertex.id]=vertex;
}
//create vertices from ids and add them to the graph
function addIds(ids){
var id;
for (var i=0; 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 ){
                                                                                    who’ who’ who’ who’ who’ who’s’ who’s’,         v1.adjacent.push(v2); Stem.addIds=addIds;
stem. connect=connect;
return stem;
}

//define a vertex
function Vertex(id){
 var stem={};
 stem.id=id;
 stem.adjacent=[];
 return stem;
}
//define a graph
function Graph(){
 var stem={}, vertices={};
 //add vertices to the graph
 function add(vertex){
  if (vertex instanceof Array){
   for (var i=0, v=vertex; i    vertices[v[i].id]=v[i];
   }
  }
  vertices[vertex.id]=vertex;
 }
 //create vertices from ids and add them to the graph
 function addIds(ids){
  var id;
  for (var i=0; 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){
   v1.adjacent.push(v2);
   v2.adjacent.push(v1);
  }
 }
 stem.vertices=vertices;
 stem.add=add;
 stem.addIds=addIds;
 stem.connect=connect;
 return stem;
}我们走出迷宫的思路是从入口开始,遍历每个点所有相邻的点,直到找到出口。因为图可能会包含环,也就是在迷宫中会出现兜圈子的情况,所以程序中记录每个到过的点,如果再次遇上,则返回上一个点。如果遇到出口,则退出整个遍历,返回到入口,途中记录经过的每个点,并最终写出从入口到出口的路线。这不是一个最优的办法,得到的结果未必是最短的路线,但是只要入口和出口之间是连通的,就一定可以找到一条路线。

[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 connected = vertex.adjacent; 
        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('出不去!'); 
    } 

//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 connected = vertex.adjacent;
        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('出不去!');
    }
}我们可以试验一下这段代码走迷宫的能力。

[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); //你可以画出这个图  
    walkOut(g.vertices[1], g.vertices[5]);//1 > 2 > 3 > 5  
    walkOut(g.vertices[1], g.vertices[6]);//出不去!  
    walkOut(g.vertices[2], g.vertices[5]);//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); //你可以画出这个图
 walkOut(g.vertices[1], g.vertices[5]);//1 > 2 > 3 > 5
 walkOut(g.vertices[1], g.vertices[6]);//出不去!
 walkOut(g.vertices[2], g.vertices[5]);//2 > 1 > 3 > 5
}在现实生活中,我们当然也可以用这种笨办法走出任何一个可能走出的迷宫,只要你用笔和便签纸在每一个岔路口记下你选择的路线。

 


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

See all articles