Home  >  Article  >  Web Front-end  >  Some practical little algorithms about js

Some practical little algorithms about js

零到壹度
零到壹度Original
2018-04-13 17:58:441148browse

The content of this article is to share with you some practical small algorithms about js, which have certain reference value. Friends in need can refer to

to determine whether the text is a reply Text

Definition: If a text is turned over and it is completely equal to the original text, then it can be called a "palindrome".

Method 1 (built-in methods for strings and arrays)

// PS:方法简单,但效率不高,会产生一个新的变量

方法二(循环)

/*
* 判断文字是否为回文
* @param {string|number} val 需要判断的文字
* @return {boolean} bool 是否为回文
*/
function isPalindrome2(val){
val = val + ''; // 非字符串转化为字符串
// 这里为什么 i <= j 呢?如果中间只有一个字符,是不需要比较的,它肯定等于它本身!!!
for(let i = 0, j = val.length - 1; i < j; i++, j--){
if(val.charAt(i) !== val.charAt(j)){
return false;
}
}
return true;
}
isPalindrome2(121) // true
isPalindrome2('yuzuy') // true

PS:网上还有其他解法,大多为以上两种的变形。

反转字符串

方法一(字符串、数组内置方法))

借用反转字符串的方法

/*
* 反转字符串
* @param {string} val 需要反转的字符串
* @return {string} str 反转后的字符串
*/
function reverseVal1(val){
if (typeof val !== 'string') return;
return val.split('').reverse().join('');
}

方法二(循环)

循环系列

/*
* 反转字符串
* @param {string} val 需要反转的字符串
* @return {string} str 反转后的字符串
*/
function reverseVal2(val){
if (typeof val !== 'string') return;
let str = '',
i = 0,
len = val.length;
while(i < len){
str += val.charAt(len - 1 - i);
i++;
}
return str;
}
/*
* 反转字符串
* @param {string} val 需要反转的字符串
* @return {string} str 反转后的字符串
*/
function reverseVal3(val){
if (typeof val !== 'string') return;
let str = '',
len = val.length;
for(let i = len - 1; i >= 0; i--){
str += val.charAt(i)
}
return str;
}

测试:reverseVal(‘abc’) // ‘cba’

阶乘

方法一(递归)

/*
* 阶乘
* @param {number} n 需要求的阶乘
* @return {number} 阶乘值
*/
function factorialize1(n){
if(typeof n !== 'number') throw new Error('参数必须为整整')
if(n === 1) return 1;
// 建议不要使用 arguments.callee,目前已经废弃了。
return n * factorialize1(n - 1);
}

PS:上面代码是一个阶乘函数,计算n的阶乘,最多需要保存n个调用记录,复杂度 O(n) 。
递归非常耗费内存,因为需要同时保存成千上百个调用帧,很容易发生“栈溢出”错误(stack overflow)。

方法二(ES6尾调用优化)

(递归优化版)

/*
* 阶乘
* @param {number} n 需要求的阶乘
* @return {number} 阶乘值
*/
function factorialize2(n, total = 1){
if(typeof n !== 'number' || typeof total !== 'number') throw new Error('参数必须为整整')
if(n === 1) return total;
return factorialize2(n - 1, n * total)
// f(3) => f(2, 3 * 2) => f(1, 6) => 6
}

PS:ES6尾调用优化但对于尾递归来说,由于只存在一个调用帧,所以永远不会发生“栈溢出”错误。
尾调用(Tail Call)是函数式编程的一个重要概念,本身非常简单,一句话就能说清楚,就是指某个函数的最后一步是调用另一个函数。

方法三(循环)

/*
* 阶乘
* @param {number} n 需要求的阶乘
* @return {number} 阶乘值
*/
function factorialize3(n){
if(typeof n !== 'number') throw new Error('参数必须为整整')
if(n === 1) return 1;
let total = 1;
while(n>1){
total = n * total;
n--;
}
return total;
}

测试:factorialize1(3) // 6

随机生成长度为n字符串

方法一

/*
* 生成指定长度的随机字符串
* @param {number} n 生成字符串个数
* @return {string} str 反转后的字符串
*/
function randomString1(n){
let str = 'abcdefghijklmnopqrstuvwxyz0123456789';
let tem = '',
i = 0;
// Math.random 函数产生值的范围[0,1)
while(i

PS:Math.round(Math.random() (str.length - 1))
Math.ceil(Math.random() 
(str.length - 1))
Math.floor(Math.random() * str.length)
这三种方式等价,都能生成[0, str.length-1]随机数

方法二(进制转化)

/*
* 生成指定长度的随机字符串
* @param {number} n 生成字符串个数
* @return {string} 反转后的字符串
*/
function randomString2(n){
return Math.random().toString(36).substr(2).slice(0, n)
}

PS:该方法原理为随机产生的数转换为指定进制字符串
toString(n),n为[2,36],n<=10时只产生0-9也就是10进制数字
该方法有个缺点,产生字符串的长度有一定的限制。

方法三(随机码点)

/*
* 生成指定长度的随机字符串
* @param {number} n 生成字符串个数
* @return {string} str 反转后的字符串
*/
function randomString3(n){
let str = '';
function randomChar(){
let l = Math.floor(Math.random() * 62);
if(l < 10) return l; // 数字部分 0-9
if(l < 36) return String.fromCharCode(l + 55); // 大写字母
return String.fromCharCode(l + 61); // 小写字母
}
while(str.length < n) str += randomChar();
return str;
}

PS:可以参考对于的ASCII码表。
测试:randomString1(3) // ‘1sd’

















##
/*
* 判断文字是否为回文
* @param {string|number} val 需要判断的文字
* @return {boolean} bool 是否为回文
*/
function isPalindrome1(val){
// 允许输入字符串和数字和布尔值
if (typeof val !== 'string') val = val.toString();
let newVal = val.split('').reverse().join('');
return val === newVal;
}
isPalindrome1(121) // true
isPalindrome1('yuzuy') // true


The above is the detailed content of Some practical little algorithms about js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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