About some basic algorithm questions about characters and arrays in js, and about js array Algorithms

Source: Internet
Author: User
Tags alphanumeric characters

About some basic algorithm questions about characters and arrays in js, and about js array Algorithms

Recently, I have been playing the fcc review. It's just like upgrading an instance. It's quite attractive to me. Today, I took the time to ping the Basic Algorithm Scritping question. Based on some tips, it is relatively simple. I would like to learn from the methods used to handle some questions. For example, a project sometimes needs to process a character. If you cannot think of some related methods, it is quite troublesome. So, record it here. If you encounter some character or Array Processing in the future, you can refer to this article to get some tips instead of reading the document.

If you have a better and simpler code or a better idea, please leave a message (I have always thought that only by learning other people's good code can you make progress faster and have a more flexible thinking ). For beginners, try again without reading the code. (You do not need to consider the parameter type for the following questions. Strictly speaking, you should make a judgment on the parameter type. For example: typeOf (arg) = number)

1. Reverse a String

Flip string

First, convert the string into an array, then use the array reverse Method to flip the array order, and finally convert the array into a string.

Your result must be a string

function reverseString(str) { str = str.split('').reverse().join('');  return str;}reverseString("hello");

2. Check for Palindromes

If the given string is a return, true is returned. Otherwise, false is returned.

If a string ignores punctuation marks, uppercase and lowercase letters, and spaces, and is reading exactly the same as the opposite, the string is palindrome ).

Note that you need to remove unnecessary punctuation marks and spaces from the string, and then convert the string to lowercase to verify whether the string is a background.

The value of the function parameter can be "racecar", "RaceCar", or "race CAR ".

Function palindrome (str) {// Good luck! Str = str. replace (/[\ | \~ | \ '| \! | \@ | \# | \$ | \% | \^|\& | \ * | \ (| \) | \-| \ _ | \ + | \ = | \ [| \] | \ {| \} | \; | \: | \ "| \ '| \, |\< | \. |\>|\/ |\?] /G, ""); // remove punctuation marks, This Is My Baidu, js regular expressions are not very familiar with str = str. replace (/\ s +/g); str = str. toLowerCase (); var arr = str. split (''); arr = arr. reverse (); var str1 = arr. join (""); if (str = str1) {return true;} return false;} palindrome ("eye");/* palindrome ("eye ") A boolean value palindrome ("eye") should be returned. true should be returned. palindrome ("race car") should return true. palindrome ("not a palindrome") should return false. palindrome ("A man, a plan, a canal. panama ") returns true. palindrome ("never odd or even") should return true. palindrome ("nope") should return false. palindrome ("almostomla") should return false. palindrome ("My age is 0, 0 si policym. ") returns true. palindrome ("1 eye for of 1 eye. ") should return false. palindrome ("0_0 (:/-\ :) 0-0") should return true. */

3. Title Case a Sentence

Make sure that the first letter of each character string is in upper case, and the other parts are in lower case. (Eg: titleCase ("I'm a little tea pot") should return "I'm A Little Tea Pot ". titleCase ("sHoRt AnD sToUt") should return "Short And Stout ".)

/* This question is very simple, mainly to understand that split () is to split the string into an array join () is to convert the array into a string toLowerCase () toUpperCase () for case-insensitive conversion. Note, valid only for letters. Other characters (eg :/,! @) Invalid */function titleCase (str) {str = str. split (""); // split the string into an array by space (var I = 0; I <str. length; I ++) {str [I] = str [I]. toLowerCase (); str [I] = str [I]. substring (0, 1 ). toUpperCase () + str [I]. substring (1);} return str. join (""); // concatenate the array into a string using spaces} titleCase ("I'm a little tea pot ");

4. Confirm the Ending

Check whether a string (str) ends with a specified string (target.

If yes, true is returned. If not, false is returned. For example, confirmEnding ("Bastian", "n") should return true. confirmEnding ("Connor", "n") should return false. confirmEnding ("Walking on water and developing software from a specification are easy if both are frozen", "specification") should return false.

Function confirmEnding (str, target) {// "Never give up and good luck will find you." // -- Falcor return str. substr (str. length-target.length) = target? True: false;} confirmEnding ("Bastian", "n"); confirmEnding ("He has to give me a new name", "na "); /* confirmEnding ("Bastian", "n") should return true. confirmEnding ("Connor", "n") should return false. confirmEnding ("Walking on water and developing software from a specification are easy if both are frozen", "specification") should return false. confirmEnding ("He has to give me a new name", "name") should return true. confirmEnding ("He has to give me a new name", "me") should return true. confirmEnding ("He has to give me a new name", "na") should return false. confirmEnding ("If you want to save our world, you must hurry. we dont know how much longer we can withstand the nothing "," mountain ") should return false. */

5. Repeat a string repeat a string

The important thing is said three times!

Repeat a specified string num. If num is a negative number, an empty string is returned. For example:

Repeat ("*", 3) should return "***".
Repeat ("abc", 3) should return "abcabcabc ".
Repeat ("abc", 4) should return "abcabcabcabc ".
Repeat ("abc", 1) should return "abc ".
Repeat ("*", 8) should return "********".
Repeat ("abc",-2) should return "".

When you cannot complete the challenge, remember to make a big move 'read-Search-Ask '.

Here are some resources that help you:

• Global String Object

function repeat(str, num) { // repeat after me var newstr = str; if(num >1){  for(var i = 1; i< num ; i ++){   str +=newstr;  }  return str; }else if(num == 1){  return str; }else{  return ""; } }repeat("abc", 3);repeat("*", 3);

6. Chunky Monkey

Monkeys can eat bananas in a few paragraphs!

Splits an array arr into several blocks Based on the specified array size.

Example: chunk ([1, 2, 3, 4], 2) = [[1, 2], [3, 4];

Chunk ([1, 2, 3, 4, 5], 2) = [[1, 2], [3, 4], [5];

function chunk(arr, size) { // Break it up.var arr1 = [];  for (var i = 0; i < arr.length; i = i + size) {    var arr2 = arr;    arr1.push(arr2.slice(i, i + size));  }  return arr1;}chunk(["a", "b", "c", "d"], 2);

7. Falsy Bouncer

Fake Monkey King!

Delete all values in the array.

In JavaScript, the false values include false, null, 0, "", undefined, and NaN.

When you cannot complete the challenge, remember to make a big move 'read-Search-Ask '.

Here are some resources that help you:

• Boolean Objects
• Array. filter ()

For example:

Bouncer ([7, "ate", "", false, 9]) should return [7, "ate", 9].

Bouncer (["a", "B", "c"]) should return ["a", "B", "c"].

Bouncer ([false, null, 0, NaN, undefined, ""]) should return [].

Bouncer ([1, null, NaN, 2, undefined]) should return [1, 2].

/* Note that this is the understanding of the filter. This is my initial code. It is not very well written. If there are not many reference values, pay attention to NaN comparison. You are not yourself (NaN! = NaN) */function bouncer (arr) {// Don't show a false ID to this bouncer. var arr1 = []; var j = 0; arr. filter (function (val, index) {if (val = false | val = null | val = 0 | val = "" | val = undefined | val! ==Val) {arr1.push (index) ;}}); var len = arr1.length; for (var I = 0; I <len; I ++) {arr. splice (arr1 [I]-j, 1); j ++;} return arr;} bouncer ([7, "ate", "", false, 9]);

8. Seek and Destroy

Jicks's mortar!

Implement a destroyer function. The first parameter is the array to be destroyed, and the remaining parameters are the values to be destroyed.

For example:

Destroyer ([1, 2, 3, 1, 2, 3], 2, 3) should return [1, 1].
Destroyer ([1, 2, 3, 5, 1, 2, 3], 2, 3) should return [1, 5, 1].
Destroyer ([3, 5, 1, 2, 2], 2, 3, 5) should return [1].
Destroyer ([2, 3, 2, 3], 2, 3) should return [].
Destroyer (["tree", "hamburger", 53], "tree", 53) should return ["hamburger"].

Here are some resources that help you:

• Arguments object
• Array. filter ()

function destroyer(arr) { // Remove all the values var tempArguments = arguments; return arr.filter(function(entry) {  for(var i = 1; i< tempArguments.length; i++) {   if (entry == tempArguments[i]) {    return false;   }  }  return true; });}destroyer([1, 2, 3, 1, 2, 3], 2, 3);

9. Where do I belong

Where am I?

Sort the array first, locate the specified value in the array, and return the index corresponding to the position.

For example, where ([1, 2, 4], 1.5) should return 1. Because 1.5 is inserted into the array [1.5, 1.5] And then changed to [1,], and the index value of is 1.

Similarly, where ([20, 3, 5], 19) should return 2. Because the array is first sorted as [3, 5, 20], 19 inserted into the array [3, 5, 20] And then changed to [3, 5,], and 19 corresponding index value is 2.

Here are some resources that help you:

• Array. sort ()

Function where (arr, num) {// Find my place in this sorted array. // note the sort () sorting rule arr. sort (function (a, B) {return a-B;}); for (var I = 0; I <arr. length; I ++) {if (arr [I]> num | arr [I] = num) {return I ;}} return arr. length;} where ([5, 3, 20, 3], 5 );

10. Caesars Cipher

Let God go to God, and Caesar go to Caesar.

Next, we will introduce the world's popular Caesar password Caesar cipher, also known as shift password.

Shift the password, that is, the letters in the password will be shifted according to the specified number.

A common case is the ROT13 password, where letters are moved to 13 locations. By 'A'↔'N', 'B'↔'O', and so on.

Write a ROT13 function to encrypt the input string and decrypt the output string.

All letters are in uppercase. Do not convert any non-alphanumeric characters (such as spaces and punctuation marks). Skip these special characters.

For example:

Rot13 ("serr pbqr pnzc") should be decoded as "free code camp"

Rot13 ("serr cvmmn! ") It should be decoded as" free pizza! "

Rot13 ("serr ybir? ") Should be decoded as" free love? "

Rot13 ("gur dhvpx oebja qbt whzcrq bire gur ynml sbk.") should be decoded to "the quick brown dog jumped over the lazy fox ."

Here are some resources that help you:

• String. charCodeAt ()
• String. fromCharCode ()

Function rot13 (str) {// lbh qvq vg! Var arr = str. toUpperCase (). split (""); var str1 = []; for (var I = 0; I <arr. length; I ++) {var arr1 = arr [I]. split (""); for (var j = 0; j <arr1.length; j ++) {var num = arr1 [j]. charCodeAt (); if (num >=65 & num <= 90) {arr1 [j] = num + 13> 90? String. fromCharCode (64 + (num + 13-90): String. fromCharCode (num + 13); // 64 + (num + 13-90) Why 64?} str1.push (arr1.join (""));} return str1.join ("");} // Change the inputs below to testrot13 ("serr pbqr pnzc ");

The above discussion about the characters and arrays in js is the full content shared by the editor. I hope to give you a reference and support for the help house.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.