The FCC JavaScript primary algorithm solution

Source: Internet
Author: User
Tags first string truncated

JavaScript basic algorithm problem on FCC

A while ago to do the basic algorithm, feel after the harvest is quite large, now will be summed up their own practice, for everyone to refer to the discussion. Basically as short as possible, but some algorithms can continue to simplify, such as the seventh question if the use of regular expressions to match, then a line of code can complete the requirements. You are welcome to propose different solutions. At the end of the FCC link, interested students can do.

1. Flipping a string
function reversestring (str) {  var arr=str.split ("");  STR=arr.reverse (). Join ("");   return str;} ReverseString ("Hello");
2. Calculate the factorial of an integer
function factorialize (num) {    return (num<1)? num = 1:num*factorialize (num-1);}
3. Determine if the given string is a palindrome

If the given string is a palindrome, returns true , conversely, returns false . If a string ignores punctuation, capitalization, and whitespace, it is exactly the same as reading and reading back, then the string is palindrome(palindrome).

functionpalindrome (str) {varp=/\s+| [,. _ ():/\-]/gi;varPstr=str.replace (P, ""); varArr=pstr.split (""); varRestr=Arr.reverse (); varNewstr= "";  for(vari=0; i<arr.length; i++) {Newstr+=Arr[i]; }  if(newstr.tolowercase () = =pstr.tolowercase ()) {          return true; }    return false; }palindrome ("Fye");
4. Find the longest word in the provided sentence and calculate its length.
functionFindlongestword (str) {varWordarr=str.split (""); varWordlengtharr=[]; varNum=0;  for(vari=0; i<wordarr.length; i++) {Wordlengtharr.push (wordarr[i].length); }   for(i=0; i<wordlengtharr.length; i++){      if(num<Wordlengtharr[i]) {num=Wordlengtharr[i]; }  }  returnnum;} Findlongestword ("The quick brown fox jumped over the lazy dog");
5. Capitalize the first letter of each word of the given string, and the remainder lowercase.
function Tofirstupper (Word) {    return word.substring (0,1). toUpperCase () +word.substring (1). toLowerCase ();} function titlecase (str) {  var wordarr=str.split ("");    for (var i=0; i<wordarr.length; i++) {      wordarr[i]=tofirstupper (wordarr[i]);  }  STR=wordarr.join ("");   return str;} Titlecase ("I ' m a Little tea pot");
6. The large array contains 4 decimal groups, each of which finds the maximum value in each decimal group, and then concatenates them together to form a new array.

such as: [[[4], 5, 1, 3], [+, 1001, 857, 1]]   should return to   [27,5,39,1]. 001]

function Largestoffour (arr) {  var newarr=[];   var index=0;    for (var i=0; i<arr.length; i++) {    for (var j=0; j<arr[i].length; J + +)      {if(arr[i][index]<arr[i][j]) {        index=j;      }    }    Newarr.push (Arr[i][index]);  }   return NEWARR;}
7. Check a string ( str) whether to specify the string ( targetEnd Returns true if it is, or false if it is not.

such as: confirmEnding("He has to give me a new name", "name") should return True

  confirmEnding("He has to give me a new name", "na")should return false.

function confirmending (str, target) {  var targetlength=target.length;   var strend=str.substr (str.length-targetlength);   if (strend==target) {    returntrue;  }   return false ;}
8. Repeat a specified string numTimes, if numis a negative number returns an empty string.

Such as repeat("abc", 3) : should "abcabcabc" repeat("abc", -2) 应该返回 "" return

function repeat (str, num) {  var originalstr=str;   if (num<=0) {    return "";  }   Else {    for (var i=1; i<num; i++) {      str+ =originalstr;    }     return  str;  }}
9. If the length of the string is greater than the specified parameter num A few long, then the redundant parts are used ... to express.

Note: The three-point number that is inserted at the end of a string is also counted as the length of the string. However, if the specified parameter is num less than or equal to 3, the added three point number is not counted in the length of the string.

such as: truncate("A-tisket a-tasket A green and yellow basket", 11) should return "A-tisket ..."

  truncate("Absolutely Longer", 2)Should return "Ab ...".

 function   truncate (str, num) { //  Clear out that junk in your trunk  if  (Num<=3 =str.slice (0,num) +" ... ";   return   str;  else  if  (Num>=str.length" { return   str;  else  {str  =str.slice (0,num-3) + "    ... ";   return   str; }}
10. Divide an array arr into a number of arrays by the specified array size size .

Description: For example: Chunk ([1,2,3,4],2) =[[1,2],[3,4]]; Chunk ([1,2,3,4,5],2) =[[1,2],[3,4],[5]];

such as: chunk([0, 1, 2, 3, 4, 5], 3) should return[[0, 1, 2], [3, 4, 5]]

  chunk([0, 1, 2, 3, 4, 5, 6], 3)should return[[0, 1, 2], [3, 4, 5], [6]]

function Chunk (arr, size) {  var newarrlength=math.ceil (arr.length/size);  var innerarr=[];    for (var i=0; i<newarrlength; i++) {    Innerarr.push (Arr.splice (0, size));  }   return Innerarr;}
11. Returns an array that is truncated nElements that are remaining after the element is truncated, starting at index 0.

such as: slasher([1, 2, 3], 2) should return[3]

  slasher([1, 2, 3], 9) 应该返回 [].

  slasher([1, 2, "chicken", 3, "potatoes", "cheese", 4], 5)should return["cheese", 4]

function Slasher (arr, howmany) {  Arr.splice (0, howmany);   return arr;}
12. The function returns True if the first string element of the array contains all the characters of the second string element.

Description: ["hello", "Hello"] True should be returned because all characters of the second string can be found in the first string, if case is ignored.

   ["hello", "hey"]should return false because the string "hello" does not contain the character "Y".

   ["Alien", "line"]Should return true because all characters in "line" can be found in "Alien".

function mutation (arr) {  var  exist;  arr[0]=arr[0].tolowercase ();  arr[1]=arr[1].tolowercase ();    for (var i=0; i<arr[1].length; i++) {    exist=arr[0].indexof (arr[1].charat (i));     if (Exist==-1) {      returnfalse;    }  }   return true ;}
13. Delete all false values in the array (false, NULL, 0, NaN, Undefined, "")

such as: bouncer([7, "ate", "", false, 9]) should return[7, "ate", 9]

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

function Bouncer (arr) {  return  arr.filter (Boolean);}
14. Implement a Destroy (destroyer) function, the first parameter is the array to be destroyed, the remaining parameters are the values to be destroyed

such as: destroyer([1, 2, 3, 1, 2, 3], 2, 3) should return[1, 1]

  destroyer([2, 3, 2, 3], 2, 3)should return[]

  destroyer(["tree", "hamburger", 53], "tree", 53)should return["hamburger"]

functionDestroyer (arr) {varDestroyelementarr=[];  for(varI=1; i<arguments.length; i++) {Destroyelementarr.push (arguments[i]); }  varFiltered=arguments[0].filter (function(num) {if(Destroyelementarr.indexof (num) <0){        return true; }      return false;  }); returnfiltered;}
15. Sort the array first, then find the specified value in the position of the array, and finally return the index of the position corresponding

Description: where([1,2,3,4], 1.5) should be returned 1 . Because 1.5 it is inserted into the array [1,2,3,4] [1,1.5,2,3,4] , and 1.5 the corresponding index value is1

such as: where([10, 20, 30, 40, 50], 35) should return3

  where([2, 20, 10], 19)should return2

function WHERE (arr, num) {  arr.sort (a/b) {return a-b;})  ;   for (var i=0; i<arr.length; i++) {    if(num<=arr[i]) {        return  i;    }  }   return i;}
16. Write a ROT13 function, implement input encryption string, output decryption string.

Note: The principle of ROT13 password is that the letter will shift 13 positions. By ' A '? ' N ', ' B '? ' O ', and so on. If the first letter is a, push it backwards by 13 bits to n, the second letter B, push it backwards 13 bits to o, and so on. When the letter n is encountered, it pushes forward 13 bits to a, and so on. Specific explanations of ROT13 can be consulted Http://www.baike.com/wiki/ROT13&prd=so_1_doc. In addition, all letters are uppercase, do not convert any non-alphabetic characters (for example: spaces, punctuation marks), encounter these special characters, skip them.

such as: rot13("SERR PBQR PNZC") should be decoded to"FREE CODE CAMP"

  rot13("SERR YBIR?")should be decoded to"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."

function rot13 (str) {  str=str.replace (/[a-z]/g,function  (word) {    if(word>=) N ") {      b=string.fromcharcode (word.charcodeat (0) -13);    }     Else {      b=string.fromcharcode (word.charcodeat (0) +13);    }     return b;  });   return str;}

FCC Chinese web: https://freecodecamp.cn

Welcome all to exchange the study together

The FCC JavaScript primary algorithm solution

Related Article

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.