FCC学习笔记-(五) Basic Algorithm Scripting

来源:互联网 发布:制作新闻的软件 编辑:程序博客网 时间:2024/06/05 04:46

(五) Basic Algorithm Scripting

1. Reverse a String

  • 反转字符串

    先把字符串转换为数组,反转后,再转换为字符串

//用到前面的函数function reverseString(str) {  str=str.split("");  str.reverse();  str=str.join("");  return str;}reverseString("hello");  //return "olleh"//简洁代码function reverseString(str) {    return str.split("").reverse().join("");}

2. Factorialize a Number

  • 阶乘
//while循环function factorialize(num) {  var total = 1;  while (num>0) {    total *= num;    num -= 1;  }  return total;}// 递归方法√function factorialize(num) { if (num == 0) {    return 1;  }else {    return factorialize(num-1)*num;  }}

3. Check for Palindromes

  • 判定回文字符串

RegExp 正则表达式

//首尾对比function palindrome(str) {  var str2 = str.toLowerCase().replace(/\W+|\_/g,"");  len = Math.floor(str2.length/2);  for (var i = 0;i < len; i ++) {    if (str2[i] != str2[str2.length-i-1]) {      return false;    }  }  return true;}//通过反转字符串比较function palindrome(str) {    return str.toLowerCase().replace(/[\W_]/g,"") == str.toLowerCase().replace(/[\W_]/gi,"").split("").reverse().join("");}//首尾对比简洁代码function palindrome(str) {  str = str.toLowerCase().replace(/[\W_]/g,"");  for (var i = 0;i < str.length/2; i ++) {    if (str[i] != str[str.length-i-1]) {      return false;    }  }  return true;  }//指针方法function palindrome(str) {  var front = 0;  var back = str.length - 1;  while (back > front) {    while ( str[front].match(/[\W_]/g) ) {      front++;      continue;    }    while( str[back].match(/[\W_]/g) ) {      back--;      continue;    }    while (str[front].toLowerCase() != str[back].toLowerCase() ) {      return false;    }    front++;    back--;  }  return true;}

4. Find the Longest Word in a String

  • 找到字符串中最长的单词
    Array.prototype.splice()
    Array.prototype.slice()
  • 注意 不可以使用 str.splice(1,1).join(” “);
function findLongestWord(str) {   //基本方法  s = str.split(" ");  maxlen = 0;  for (var i = 0; i < s.length; i++) {    if (maxlen < s[i].length) {      maxlen = s[i].length;    }  }  return maxlen;  //reduce方法  return str.split(" ").reduce(function(x,y){    return Math.max(x,y.length);  },0);  //递归方法  str = str.split(" ");  if (str.length == 1) {    return str[0].length;  }  if (str[0].length >= str[1].length) {    str.splice(1,1); // splice 移除了str部分内容    return findLongestWord(str.join(" "));  }  if (str[0].length <= str[1].length) {    return findLongestWord(str.slice(1,str.length).join(" ")); // slice 只是复制str的部分内容  }}

5. Title Case a Sentence

  • 字符串中单词首字母大写

String.prototype.substr():与数组的Array.prototype.slice()类似

function titleCase(str) {  //基本算法  str = str.toLowerCase().split(" ");  for (var i = 0; i < str.length; i++) {    str[i] = str[i].split("");    str[i][0] = str[i][0].toUpperCase();    str[i] = str[i].join("");  }  return str.join(" ");  //用replace  str = str.toLowerCase().split(" ");  for (var i = 0; i < str.length; i++) {    str[i] = str[i].replace(/\w/,str[i][0].toUpperCase());  }  return str.join(" ");  //改进基本方法  String.prototype.replaceAt = function(index, character) {    return this.substr(0,index) + character + this.substr(index + character.length);  }; //放到函数titleCase外  str = str.toLowerCase().split(" ");  var updatedTitle = [];  for (var st in str) {    updatedTitle[st] = str[st].replaceAt(0,str[st].charAt(0).toUpperCase());  }  return updatedTitle.join(" ");  //Map方法  str = str.toLowerCase().split(" ");  var updatedTitle = str.map(function(val) {    return val.replace(val.charAt(0),val.charAt(0).toUpperCase());  });  return updatedTitle.join(" ");  //正则表达式  return str.toLowerCase().replace(/(^|\s)\S/g,(L) => L.toUpperCase()); }titleCase("sHoRt AnD sToUt");

6. Return Largest Numbers in Arrays

  • 返回系列数组值最大的数
    Function.prototype.apply()
    Function.prototype.bind()
  • freecodecamp discussion
function largestOfFour(arr) {  // reduce方法  var maxArr =[];  for (var i = 0; i < arr.length; i++) {    maxArr[i] = arr[i].reduce(function (x,y) {      return Math.max(x,y);    });}  return maxArr;// map+reduce方法  return arr.map(function(val) {    return val.reduce(function(x,y) {      return Math.max(x,y);});  }); // advanced solution   return arr.map(Function.apply.bind(Math.max,null));}largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

7. Confirm the Ending

  • 验证结尾字符是否相同
    String.prototype.substr()
    String.prototype.substring()
function confirmEnding(str, target) {  //substr 方法  return str.substr(-target.length) == target;  //substring 方法  return str.substring(str.length - target.length) == target; }confirmEnding("Bastian", "n");

8. Repeat a string

  • 重复一个字符串
    String.prototype.repeat()
    Conditional (ternary) Operator
function repeatStringNumTimes(str, num) {  //递归方法  if (num == 1) {    return str;  }else if (num < 0) {    return "";  }  return str + repeatStringNumTimes(str,num-1);  // Conditional (ternary) Operator  return num >0 ? str.repeat(num) : "";}repeatStringNumTimes("abc", 3);

9. Truncate a string

  • 缩短字符串
function truncateString(str, num) {  // 基本方法  if (num <3 ) {    return str.slice(0,num) + "...";  }  if (str.length > num) {    return str.slice(0,num-3) + "...";  }else {    return str;  }  //Conditional (ternary) Operator   if (str.length <= num) {     return str;   }else {     return str.slice(0, (num < 3 ? num : num-3)) + "...";   }}truncateString("A-", 1);

10. Chunky Monkey

Array.prototype.splice()
Array.prototype.slice()

function chunkArrayInGroups(arr, size) {  //slice 方法  var arrg = [];  for (var i = 0; i < arr.length; i += size)  {     arrg.push(arr.slice(i,i+size));    }  return arrg;  // splice 方法  var arrg = [];  while (arr.length) {    arrg.push(arr.splice(0,size));  }  return arrg;}chunkArrayInGroups(["a", "b", "c", "d"], 2);

11. Slasher Flick

  • 保存指定数组
function slasher(arr, howMany) {  //splice方法  arr.splice(0,howMany); //直接return是错误的  return arr;  //slice 方法  return arr.slice(howMany);}slasher([1, 2, 3], 2);

12. Mutations

  • 判断数组中第一个字符串是否包含第二个字符所有字母
    String.prototype.indexOf()
    Array.prototype.every()
function mutation(arr) {//基本方法    var arrg = arr[1].toLowerCase().split("");  for (var st in arrg) {    if (arr[0].toLowerCase().indexOf(arrg[st]) === -1) {      return false;    }  }  return true;  //指针方法   var front = 0;  while (front < arr[1].length) {    if(arr[0].toLowerCase().indexOf(arr[1][front].toLowerCase()) !== -1) {      front ++;    }else {      return false;    }  }  return true;  //every方法 √  return arr[1].toLowerCase().split("").every(function (val) {    return arr[0].toLowerCase().indexOf(val) !== -1;  }); }mutation(["hello", "hey"]);

13. Falsy Bouncer

  • 滤除Falsy values
    Falsy values in JavaScript are false, null, 0, “”, undefined, and NaN.
    Boolean
    Array.prototype.filter()
function bouncer(arr) {  // filter 方法  return arr.filter(function (val) {    return Boolean(val);  }); // 简洁方法  return arr.filter(Boolean);}bouncer([7, "ate", "", false, 9]);

14. Seek and Destroy

  • 把第一个参数数组中与后续参数元素相同的元素滤除
    Arguments object
    Array.prototype.filter()
    Array.prototype.every()
function destroyer(arr) {  // filter + every 方法  var args = Array.prototype.slice.call(arguments).slice(1);  return arguments[0].filter(function (val) {     return args.every(function (cal) {       return cal !== val;     });  });  //Arrow Function 方法 var args = Array.prototype.slice.call(arguments).slice(1); return arguments[0].filter((val) => args.every((cal) => cal !== val) );}  //includes 方法  var args = Array.prototype.slice.call(arguments).slice(1);  return arr.filter(function(val) {    return !args.includes(val);  });}destroyer([1, 2, 3, 1, 2, 3], 2, 3);

15. Where do I belong

  • 把第二个参数放入第一个数组参数中排序

Array.prototype.sort()
Array.prototype.findIndex()
Array.prototype.concat()

function getIndexToIns(arr, num) {  // 基本方法  arr.sort(function (a,b) {    return a - b;  }); //sort 默认用于Unicode code points比较,即字符串  var index = 0;  for (var i = 0; i < arr.length; i++) {    if(num > arr[i]) {      index ++;      }  }  return index;  //改进基本方法  arr.sort(function (a,b) {    return a - b;  });   for (var i = 0; i < arr.length; i++) {    if(arr[i] >= num) {      return i;    }  }  return arr.length;  //filter方法 (不用sort亦可)  return arr.filter(function (val) {    return num > val;   }).length;  //findindex 方法  var index = arr.sort((a, b) => a > b).findIndex((L) => L >= num);  return index === -1 ? arr.length : index;  //indexOF + push 方法  arr.push(num);  return arr.sort((a, b) => a > b).indexOf(num);  //concat 方法√ (concat也可用于string)  return arr.concat(num).sort((a, b) => a >b).indexOf(num);}getIndexToIns([2, 5, 10], 15);

16. Caesars Cipher

RegExp.prototype.test()
String.fromCharCode()
String.prototype.charCodeAt()
Function.prototype.apply()

function rot13(str) {   //基本方法  return str.split("").map(function (val) {    if (65 <= val.charCodeAt() && val.charCodeAt()  <=77) {      return String.fromCharCode(val.charCodeAt() + 13);    }    if (78 <= val.charCodeAt() && val.charCodeAt() <=90) {      return String.fromCharCode(val.charCodeAt() - 13);    }    return val;  }).join("");  //Regex 方法  var updatedarr = [];  var regex = /[A-Z]/;  str = str.split("");  for (var st in str) {    if (regex.test(str[st])) {        updatedarr.push((str[st].charCodeAt() - 65 + 13) % 26 + 65);        }else {          updatedarr.push(str[st].charCodeAt());        }  }  str = String.fromCharCode.apply(String,updatedarr);  return str;  //Regex + replace 方法  return str.replace(/[A-Z]/g,L => String.fromCharCode(L.charCodeAt(0) % 26 + 65));}rot13("SERR PBQR PNZC");