Home Web Front-end JS Tutorial Summary of common JS algorithm examples

Summary of common JS algorithm examples

May 22, 2018 pm 03:03 PM
javascript Example Summary

This time I will bring you a summary of examples of commonly used algorithms in JS. What are the precautions when using commonly used algorithms in JS. The following is a practical case, let’s take a look.

Accumulation and accumulation

Accumulation: Add a series of data to a variable. The final cumulative result is obtained

For example: Calculate the cumulative sum of the numbers from 1 to 100

The ball falls from a height and returns to half of the original value each time. Find the tenth time the ball lands. The distance traveled by the ball in time

<script>
 var h=100;
 var s=0;
 for(var i=0;i<10;i++){
  h=h/2;
  s+=h;
 }
 s=s*2+100;
</script>
Copy after login

Accumulation:Multiply a series of data into a variable to get the cumulative result.

The common one is the factorial of n

var n=100;
var result= 1;
for(var i=1;i<=n;i++){
 result *=i;
}
Copy after login

General form:

Accumulation: V =e;

Accumulation: v*=e;

V represents accumulation and accumulation, e represents accumulation/accumulation term

Key points of the algorithm:

(1) Initialization

Initialize v and e

Accumulation: v = 0;

Accumulation: v = 1;

e initialization, if the accumulation/product item is complex, it may be decomposed into several sub-items and initialized separately , such as the problem of calculating pi, the cumulative term is decomposed into three parts: symbol, numerator and denominator.

(2) Loop control conditions

One is a fixed number of times, such as the problem of calculating the bounce distance, the problem of calculating the sum of the first 20 items of the sequence,

number of times It is not fixed, but must meet a certain condition: the problem of calculating pi requires that the absolute value of the last term be less than 10-6.

(3) Determine the change of the accumulation/product term

For example, the sum of the first 20 terms of the sequence is to use the sum of the current numerator and denominator as the next denominator, and the current denominator as the numerator .

Another example is the problem of finding pi, which is to invert the sign, add 2 to the denominator, and then find the next term.

Iteration

The iteration method is also the rolling method

Rule: it can be used continuously The old value gets the new value until we get the result we want.

How to solve the problem of iteration

1. Find the iteration variable (old value)

2. Determine the relationship between iteration

3. Knowing what the desired result is (conditions for ending the loop)

(1) is to know the final result

(2) The number of loops

<script>
 /*
 * 1.接受用户输入的俩个数
 * 2.一个函数的到最大公约数
 * 3.打印这个最大公约数*/
 var num1 = Number(prompt("请输入一个数"));
 var num2 = Number(prompt("请输入一个数"));
 var result = GCD(num1,num2);
 alert(result);
 /*
 * 函数的功能:得到最大公约数
 * 函数名:GCD
 * 函数的参数:俩个整数
 * 返回值:最大公约数*/
 /*
 * 如果num1<num2则交换,确保num1是交大的
 * 计算余数
 * 当num1(除数),对num2(被除数)的余数不为0,重复一下步骤
 * num2=>num1,
 * 余数=>num2
 * 重新计算余数
 * 最终的到最大公约数,也就是num2的值*/
 function GCD(num1,num2){
  /*return0;*/
  if(num1<num2){
   var t = num1;
   num1=num2;
   num2 = t;
  }
  var remainder = num1%num2;
  while(remainder!= 0){
   num1=num2;
   num2= remainder;
   remainder=num1%num2;
  }
  returnnum2;
 }
</script>
Copy after login

Recursion

Find the mathematical rule: calculate the value of the next item through the formula until the result we want

For example: a rabbit gives birth: through the first two The item gets the next item

<script>
 /*
 * 一般而言,兔子在出生俩个月后,就有繁殖能力
 * 一对兔子每个月能生出一对小兔子来
 * 如果所有的兔子都不死,那么一年以后总共有多少对兔子*/
 /*
 * 月份 0 1 2 3 4 5 6
 * 幼崽 1 1 1 2 3 5 8
 * 成年 0 0 1 1 2 3 5
 * 总共 1 1 2 3 5 8 13
 * */
 /*
 * 接收用户输入的月份
 * 计算兔子的对数
 * (1)如果经过的月份<2那么兔子的对数为1
 * (2)否则用初始的兔子的对数 加上 第一个月的对数为
 * 第二个月兔子的个数(an = an-1 +an-2)
 * 反复使用这个公式,计算出下个月兔子的个数一直到用户输入的月份为止
 * 打印的兔子的对数
 * */
 /* var month = Number(prompt("输入月份"));
  var sum ;
  var an =1;
  var an_1=1;
  var an_2;
  if(month < 2){
  sum=1;
  }else{
  sum=2;
  for(var i=1; i<month; i++){
  sum= an +an_1;
  an_1 =an;
  an = sum;
  }
  }
  alert(sum);*/
 /*
 * 思路2*/
 var month = Number(prompt("输入月份"));
 var rabbit = [1,1];
 for(var m=2;m<=month;m++){
  rabbit[m]=rabbit[m-1]+rabbit[m-2];
 }
 alert(rabbit[month]);
</script>
Copy after login

Recursion is divided into forward push and reverse push.

Exhaustion

When you encounter a problem and can’t find a better solution (can’t find a mathematical formula or rule) , use the "stupidest" method, take advantage of the fast computing speed of computers, list all possibilities

and record the results we want

<script>
 /*
 * 公鸡一值钱5,鸡母一值钱三,鸡仔三值钱一
 * 百钱买百鸡,问公鸡,鸡母、鸡仔各几何?
 * x y z
 * x + y + z = 100
 * x*5 + y * 3 + z/3 = 100*/
 for(var cock=0;cock<=20;cock++){
  for(var hen=0;hen<=33;hen++){
   var chihen=100-cock-hen;
   if(100== cock*5+ hen*3+ chihen/3){
    document.write("公鸡一共:"+cock+"鸡母一共:"+hen+"小鸡一共:"+chihen+"<br>")
   }
  }
 }
</script>
Copy after login

Exhaustive method Its characteristics are: the algorithm is simple and the corresponding program is also simple, but the amount of calculation is often large. However, the advantage of computers is their fast computing speed, so this algorithm can maximize its strengths and avoid weaknesses, and can often achieve good results.

Case: There is a three-digit number, the ones digit is larger than the hundreds digit, and the hundreds digit is larger than the tens digit, and the sum of the digits is equal to the product of the multiplication of the digits, find these three Number of digits

Recursion

The so-called recursion is to call yourself again inside the function.

For example, to find the factorial problem, the fact function is called inside the fact function

<script>
 /*计算n的阶乘*/
 function fact(n){
  if(1== n){
   return 1
  }
   return n*fact(n-1);
 }
 alert(fact(5));
</script>
Copy after login

The recursive algorithm is very complicated to understand according to the conventional thinking, and the function calls are nested layer by layer. Call, and then return layer by layer, you might as well change your mind to understand recursion.

Recursion is actually solving a problem of size n by reducing it to a problem of n-1. That is to find the relationship between n and n-1.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

VeeValidate form verification use case code analysis in vue project

##Vue uses vee-validate Detailed explanation of verification form steps

The above is the detailed content of Summary of common JS algorithm examples. For more information, please follow other related articles on the PHP Chinese website!

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

The relationship between the number of Oracle instances and database performance The relationship between the number of Oracle instances and database performance Mar 08, 2024 am 09:27 AM

The relationship between the number of Oracle instances and database performance Oracle database is one of the well-known relational database management systems in the industry and is widely used in enterprise-level data storage and management. In Oracle database, instance is a very important concept. Instance refers to the running environment of Oracle database in memory. Each instance has an independent memory structure and background process, which is used to process user requests and manage database operations. The number of instances has an important impact on the performance and stability of Oracle database.

See all articles