Home > Web Front-end > JS Tutorial > JS common algorithm implementation code

JS common algorithm implementation code

高洛峰
Release: 2016-12-07 09:57:32
Original
791 people have browsed it

The main purpose of this article is to help everyone become familiar with the implementation of several commonly used algorithms using JS. The specific content is as follows

(1) Array deduplication

Principle: Define an object obj, and then use the array elements as the attribute names of obj. Determine duplication based on whether the attribute name is repeated

var unique = function(arr){
  let obj = {};
  let newArr = [];
  arr.forEach(function(x){
    if(!obj[x]){ //如果对象中没有该元素对应的属性
      obj[x] = true;
      newArr.push(x);
    }
  });
  return newArr;
}
Copy after login

​​​


(2) Use the quick sort algorithm to sort the array

This includes two effects, one is to use the characteristics of quick sort to achieve deduplication and quick sort , the other is quick sorting without deduplication.

Principle: Obtain the target array, select an element as the flag, traverse the remaining elements, put them on the right if they are larger than the flag, and put them on the left if they are smaller than the flag.

Special note: There are elements equal to the flag bit. If you store equal elements, deduplication will be achieved. If you store them, they will not be deduplicated.

var quickSort = function(arr){
   
  if(arr.length <= 1){
    return arr;
  }
   
  //定义一个左数组,定义一个右数组
  let leftArr = [];
  let rightArr = [];
  //选定一个参照值
  let tag = arr[0];
   
  /*
   * 使用如下方式判断,会把重复元素去掉,就实现了快排的同时去重
   */
  for(let i = 0; i < arr.length; i++){
    if(arr[i] < tag){ //将比tag小的元素放在左数组中
      leftArr.push(arr[i]);
    }
    if(arr[i] > tag){ //将比tag大的元素放在右数组中
      rightArr.push(arr[i]);
    }
  }
   
  /*
   * 使用如下方式就是使用快排进行排序,不去重
   */
  for(let i = 1; i < arr.length; i++){
    if(arr[i] < tag){ //将比tag小的元素放在左数组中
      leftArr.push(arr[i]);
    }else{ //将比tag大的元素放在右数组中
      rightArr.push(arr[i]);
    }
  }
   
  //递归调用
  return [].concat(quickSort(leftArr),[tag],quickSort(rightArr));
}
Copy after login


(3) Count the characters that appear most frequently in the string

Principle: This is similar to array deduplication. It also uses an object obj to use the array element as the attribute name of the object. If the object does not exist, Attribute name, the value is assigned to 1, if it exists, the value is increased by 1.

var maxShowTimes = function(str){
  // 创建一个用于判重的对象
  let obj = {};
  // 判断字符串是否为空或只有一个元素
  if(str.length <= 1){
    return str.length === 0?&#39;字符串不能为空&#39;:str;
  }
  // 利用String的charAt()方法获取各个字符
  for(let i = 0; i <= str.length; i++){
    if(!obj[str.charAt(i)]){ //如果不存在
      obj[str.charAt(i)] = 1;
    }else{ //如果存在
      obj[str.charAt(i)] += 1;
    }
  }
   
  // 在obj对象中寻找值最大的那个属性
  let maxChar = &#39;&#39;;
  let maxTimes = 0;
  for(var k in obj){
    if(obj[k] > maxTimes){
      maxChar = k;
      maxTimes = obj[k];
    }
  }
  return maxChar;
}
Copy after login


(4) To achieve the exchange value of two variables without using the third variable

Principle: It is a variable substitution, the idea is very clever, and can only be used for the exchange of numbers.

var swap = function(a,b){
  if(a === b){
    return [a,b];
  }
  b = b - a; // 此处的 b - a中的b和a的值是最初的值
  a = a + b; // a = a + b -a; 实现了将b的值赋给a
  b = a - b; // b = a - (b - a) = 2a - b 相当于 2b = 2a;实现了将a的值赋给b
  return [a,b];
}
Copy after login


(5) Find the maximum difference of an array

Principle: traverse the array once, find the maximum and minimum values, and return the difference

var getMaxProfit = function(arr){
  // 定义两个变量,分别存贮最大值和最小值
  let maxNum = arr[0];
  let minNum = arr[0];
  for(let i = 0; i < arr.length; i++){
    if(arr[i] > maxNum){
      maxNum = arr[i];
    }
    if(arr[i] < minNum){
      minNum = arr[i];
    }
  }
  return maxNum - minNum;
}
Copy after login


(6) Get any length Principle of random string

: You can manually specify the character library and random character length n, and use the Math.floor() and Math.random() methods to obtain random characters.

var getRandomString = function(n){
  // 定义随机字符串的字符库
  let str = &#39;qwertyuiopasdfghjklzxcvbnm1234567890&#39;;
  // 定义一个临时变量tmp存储生成的随机字符串
  let tmp = &#39;&#39;;
  //获取str的长度
  let len = str.length;
  // 生成一个长度为n的随机字符串
  for(let i = 0; i < n; i++){
    tmp += str.charAt(Math.floor(Math.random() * len));
  }
  return tmp;
}
Copy after login



Related labels:
js
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template