Share a basic script algorithm example
之前偶然看到了w3c上的编程挑战题,就像拿来试试手,先做的是初级脚本算法,总体不难,如果有更好的方法,希望能一起交流!
1、翻转字符串
先把字符串转化成数组,再借助数组的reverse方法翻转数组顺序,最后把数组转化成字符串。
function reverseString(str) {var str2 = '';for(var i=str.length-1;i>=0;i--){ str2 += str[i]; }return str2; }function reverseString(str){var strArray = str.split(''); strArray.reverse(); str = strArray.join('');return str }
2、计算一个整数的阶乘
如果用字母n来代表一个整数,阶乘代表着所有小于或等于n的整数的乘积。
function factorialize(num) {var sum = 1;for(var i=num;i>0;i--){ sum *= i; } console.log(sum);return sum; }function factorialize(num) {if(num ==1){return 1; }else{return arguments.callee(num-1)*num; } }
3、回文算法
如果给定的字符串是回文,返回true
,反之,返回false
。
如果一个字符串忽略标点符号、大小写和空格,正着读和反着读一模一样,那么这个字符串就是(回文)。
注意你需要去掉字符串多余的标点符号和空格,然后把字符串转化成小写来验证此字符串是否为回文。
function palindrome(str) {var arr = []; str = str.toLowerCase(); for(var i=0;i<str.length;i++){// 在小写字母的Unicode的范围内或者在数字的Unicode范围内if((str.charCodeAt(i)<=122 && str.charCodeAt(i)>=97) || (str.charCodeAt(i)<=57 && str.charCodeAt(i)>=48)){ arr.push(str[i]); } }//只需要判断数组一半的次数就全部比较完了,不必再浪费时间了for(var i=0;i<Math.ceil(arr.length/2);i++) {if(arr[i] !== arr[arr.length-i-1]){return false; } }return true; }// 需要手动添加特殊字符function palindrome(str){var str1,str2; str = str.toLowerCase(); str = str.replace(/[\ |\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\_|\+|\=|\||\\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\>|\/|\?]/g,""); str1 = str.split(''); str1.reverse(); str2 = str1.join('');if(str === str2){return true}else{return false; } }
4、寻找最长的单词算法
找到提供的句子中最长的单词,并计算它的长度。
函数的返回值应该是一个数字。
// 利用charCodeAt()方法判断是不是一个单词,并记录单词长度,最后获得最长的单词长度function findLongestWord(str) {var num = 0, max = 0;for (var i = 0; i < str.length; i++) {if (str.charCodeAt(i) !== 32) { num++; } else {// 注意:如果最后一个字母不是空格,不会比较最后一个单词的长度max = num > max ? num : max; num = 0; } }// 比较最后一个单词的长度max = num > max ? num : max;return max; }// 利用split()方法将字符串分成每个单词组成的数组,取得其中最长的长度function findLongestWord(str){ var max = 0; var arr = str.split(' '); for(var i=0;i<arr.length;i++){ max = arr[i].length>max?arr[i].length:max; } return max; }
5、设置首字母大写算法
确保字符串的每个单词首字母都大写,其余部分小写。
像'the'和'of'这样的连接符同理。
//将字符串用split()方法转为数组,并用数组中的每个项的首字母的大写和这个项剩余的字符拼接,最后转为字符串function titleCase(str) {var arr,upChar; str = str.toLowerCase(); arr = str.split(' '); for(var i=0;i<arr.length;i++){ upChar = arr[i][0].toUpperCase() ; arr[i] = upChar + arr[i].slice(1); } arr = arr.join(' ');return arr; }function titleCase(str){var upChar, toUper = false;for(var i=0;i<str.length;i++){if((str.charCodeAt(i) == 32)){ toUper = true; }else if(toUper){ upChar= str[i].toUpperCase(); console.log(upChar) console.log(str[i]); str[i] = upChar; toUper = false; } }return str; }
6、寻找数组中的最大值算法
右边大数组中包含了4个小数组,分别找到每个小数组中的最大值,然后把它们串联起来,形成一个新数组。
function largestOfFour(arr) {var max = 0, result = [];for(var i=0;i<arr.length;i++){for(var j=0;j<arr[i].length;j++){var n = arr[i][j]; max = n>max?n:max; } result.push(max); max = 0; }return result; }
7、确认末尾字符算法
检查一个字符串(str
)是否以指定的字符串(target
)结尾。
如果是,返回true;如果不是,返回false。
// 从后开始比较function confirmEnding(str, target) {for (var i = 0; i < target.length; i++) {if (str[str.length - 1 - i] != target[target.length - 1 - i]) {return false; } }return true; }
8、重复操作算法
重要的事情说3遍!
重复一个指定的字符串 num
次,如果num
是一个负数则返回一个空字符串。
function repeat(str, num) {var result = '';if(num<0){return ''; }else{for(var i=0;i<num;i++){ result += str; } }return result; }
9、字符串截取算法
用瑞兹来截断对面的退路!
截断一个字符串!
如果字符串的长度比指定的参数num
长,则把多余的部分用...
来表示。
切记,插入到字符串尾部的三个点号也会计入字符串的长度。
但是,如果指定的参数num
小于或等于3,则添加的三个点号不会计入字符串的长度。
function truncate(str, num) {var result = '';var strArr = str.split('');if(num<=3){ result = str.slice(0,num) +'...'; }else if(str.length>num){ result = str.slice(0,num-3) + '...'; }else{ result = str; }return result; }
10、数组分割算法
猴子吃香蕉可是掰成好几段来吃哦!
把一个数组arr
按照指定的数组大小size
分割成若干个数组块。
function chunk(arr, size) {var result = [];var a = [];for(var i=0;i<arr.length;i++){ a.push(arr[i]);if( ((i+1)%size == 0) || (i == arr.length-1)){ result.push(a); a = []; } }return result; }
11、数组截断算法
打不死的小强!
返回一个数组被截断n
个元素后还剩余的元素,截断从索引0开始。
function slasher(arr, howMany) { var result = []; for(var i=howMany;i<arr.length;i++){ result.push(arr[i]); } return result; }
12、数组查询算法
蛤蟆可以吃队友,也可以吃对手。
如果数组第一个字符串元素包含了第二个字符串元素的所有字符,函数返回true。
举例,["hello", "Hello"]
应该返回true,因为在忽略大小写的情况下,第二个字符串的所有字符都可以在第一个字符串找到。
["hello", "hey"]
应该返回false,因为字符串"hello"并不包含字符"y"。
["Alien", "line"]
应该返回true,因为"line"中所有字符都可以在"Alien"找到。
function mutation(arr) {var arr1 = arr[0].toLowerCase(); console.log(arr1)var arr2 = arr[1].toLowerCase();for(var i=0;i<arr[1].length;i++){ if(arr1.indexOf(arr2[i]) == -1){return false; } }return true; }
13、删除数组中特定值
真假美猴王!
删除数组中的所有假值。
在JavaScript中,假值有false
、null
、0
、""
、undefined
和 NaN
。
function bouncer(arr) {// Don't show a false ID to this bouncer.for(var i=0;i<arr.length;i++){if(!arr[i] == true){ arr.splice(i,1); i--; } }return arr; }
14、去除数组中任意多个值
金克斯的迫击炮!
实现一个摧毁(destroyer)函数,第一个参数是待摧毁的数组,其余的参数是待摧毁的值。
function destroyer(arr) {// Remove all the valuesvar arr = arguments[0]; console.log(arr[1]);var data = Array.prototype.slice.call(arguments,1);for(var j=0;j<data.length;j++){for(var i=0;i<arr.length;i++){if(arr[i] == data[j]){ arr.splice(i,1); i--; } } }return arr; }
15、数组排序并插入值
我身在何处?
先给数组排序,然后找到指定的值在数组的位置,最后返回位置对应的索引。
举例:where([1,2,3,4], 1.5)
应该返回 1
。因为1.5
插入到数组[1,2,3,4]
后变成[1,1.5,2,3,4]
,而1.5
对应的索引值就是1
。
同理,where([20,3,5], 19)
应该返回 2
。因为数组会先排序为 [3,5,20]
,19
插入到数组[3,5,20]
后变成[3,5,19,20]
,而19
对应的索引值就是2
。
function where(arr, num) { arr.sort(function(a,b){return a - b; });for(var i=0;i<arr.length;i++){if(num > arr[i] && num < arr[i+1]){return i+1; }else if(num == arr[i]){return i; }else if(num >arr[arr.length-1]){return arr.length; } } }
16、位移密码算法
让上帝的归上帝,凯撒的归凯撒。
下面我们来介绍风靡全球的凯撒密码Caesar cipher
,又叫移位密码。
移位密码也就是密码中的字母会按照指定的数量来做移位。
一个常见的案例就是ROT13密码,字母会移位13个位置。由'A' ↔ 'N', 'B' ↔'O',以此类推。
写一个ROT13函数,实现输入加密字符串,输出解密字符串。
所有的字母都是大写,不要转化任何非字母形式的字符(例如:空格,标点符号),遇到这些特殊字符,跳过它们。
function rot13(str) { // LBH QVQ VG!var result = [];for(var i=0;i<str.length;i++){if(str.charCodeAt(i) >= 65 && str.charCodeAt(i) <= 90){var code = str.charCodeAt(i) + 13;if(code>90){ code = str.charCodeAt(i) + 13 - 26; } result.push(String.fromCharCode(code)); }else{ result.push(str[i]); } }return result.join(""); }
The above is the detailed content of Share a basic script algorithm example. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Common challenges faced by machine learning algorithms in C++ include memory management, multi-threading, performance optimization, and maintainability. Solutions include using smart pointers, modern threading libraries, SIMD instructions and third-party libraries, as well as following coding style guidelines and using automation tools. Practical cases show how to use the Eigen library to implement linear regression algorithms, effectively manage memory and use high-performance matrix operations.

01 Outlook Summary Currently, it is difficult to achieve an appropriate balance between detection efficiency and detection results. We have developed an enhanced YOLOv5 algorithm for target detection in high-resolution optical remote sensing images, using multi-layer feature pyramids, multi-detection head strategies and hybrid attention modules to improve the effect of the target detection network in optical remote sensing images. According to the SIMD data set, the mAP of the new algorithm is 2.2% better than YOLOv5 and 8.48% better than YOLOX, achieving a better balance between detection results and speed. 02 Background & Motivation With the rapid development of remote sensing technology, high-resolution optical remote sensing images have been used to describe many objects on the earth’s surface, including aircraft, cars, buildings, etc. Object detection in the interpretation of remote sensing images

1. Background of the Construction of 58 Portraits Platform First of all, I would like to share with you the background of the construction of the 58 Portrait Platform. 1. The traditional thinking of the traditional profiling platform is no longer enough. Building a user profiling platform relies on data warehouse modeling capabilities to integrate data from multiple business lines to build accurate user portraits; it also requires data mining to understand user behavior, interests and needs, and provide algorithms. side capabilities; finally, it also needs to have data platform capabilities to efficiently store, query and share user profile data and provide profile services. The main difference between a self-built business profiling platform and a middle-office profiling platform is that the self-built profiling platform serves a single business line and can be customized on demand; the mid-office platform serves multiple business lines, has complex modeling, and provides more general capabilities. 2.58 User portraits of the background of Zhongtai portrait construction

Counting sounds simple, but in practice it is very difficult. Imagine you are transported to a pristine rainforest to conduct a wildlife census. Whenever you see an animal, take a photo. Digital cameras only record the total number of animals tracked, but you are interested in the number of unique animals, but there is no statistics. So what's the best way to access this unique animal population? At this point, you must be saying, start counting now and finally compare each new species from the photo to the list. However, this common counting method is sometimes not suitable for information amounts up to billions of entries. Computer scientists from the Indian Statistical Institute, UNL, and the National University of Singapore have proposed a new algorithm - CVM. It can approximate the calculation of different items in a long list.

C++ programming puzzles cover algorithm and data structure concepts such as Fibonacci sequence, factorial, Hamming distance, maximum and minimum values of arrays, etc. By solving these puzzles, you can consolidate C++ knowledge and improve algorithm understanding and programming skills.

1. The main tasks of the overall framework can be divided into three categories. The first is the discovery of causal structures, that is, identifying causal relationships between variables from the data. The second is the estimation of causal effects, that is, inferring from the data the degree of influence of one variable on another variable. It should be noted that this impact does not refer to relative nature, but to how the value or distribution of another variable changes when one variable is intervened. The last step is to correct for bias, because in many tasks, various factors may cause the distribution of development samples and application samples to be different. In this case, causal inference may help us correct for bias. These functions are suitable for a variety of scenarios, the most typical of which is decision-making scenarios. Through causal inference, we can understand how different users react to our decision-making behavior. Secondly, in industry

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

The use of data structures and algorithms is crucial in cloud computing for managing and processing massive amounts of data. Common data structures include arrays, lists, hash tables, trees, and graphs. Commonly used algorithms include sorting algorithms, search algorithms and graph algorithms. Leveraging the power of Java, developers can use Java collections, thread-safe data structures, and Apache Commons Collections to implement these data structures and algorithms.
