您的当前位置:首页freeCodeCamp中级算法答案(个人做法)

freeCodeCamp中级算法答案(个人做法)

2024-12-14 来源:哗拓教育

1、通过Math.max()和Math.min()和Array.reduce()来实现数组中从小到大的累积和 ,例如sumAll([1,5]) 值为10

function sumAll(arr) {
   var arryA=[];
   var max=Math.max.apply(null,arr);
   var min=Math.min.apply(null,arr);
   var sum=0;
   var sumFun=function(max,min){
      for(var i=0;i<(max-min+1);i++){
         arryA.push(min+i);
      }
      console.log(arryA);
      var value=arryA.reduce(function(previousValue,currentValue){
         return previousValue+currentValue;
      });
      return value;
   };
   sum=sumFun(max,min);
   return sum;
}
console.log(sumAll([5, 10]));

关键点,通过Math.max.apply(null,array)来实现数组中的最大值判断

2、数组去重然后合并不同的数组
使用Array.indexOf() Array.slice() Array.filter() Array.concat()

function diffArray(arr1, arr2) {
   var newArr = [];
   var arrA=[];
   var arrB=[];
   var arrMiddle=[];
   if(arr1.length===0||arr2.length===0){//判断是否存在[]的情况
      console.log(arr2.concat(arr1))
   }else{
      arrA=arr1.filter(function(ele,index){
         var flag=true;
         var element=null;
         for(var i=0;i<arr2.length;i++){
            if(ele===arr2[i]){
               flag=false;
               element=ele;
            }
         }
         if(element!=null){
            arrMiddle.push(element);
         }
         return flag;
      });
      if(arrMiddle.length>0){//是否存在各不相同的情况
         var num;
         for(var k=0;k<arrMiddle.length;k++){
            num=arr2.indexOf(arrMiddle[k]);
            arr2.splice(num,1);
         }
         console.log(arr2);
         arrB=arr2;
      }else{
         arrB=arr2;
      }
      newArr=arrA.concat(arrB);
   }
   // Same, same; but different.
   return newArr;
}
console.log(diffArray([1, "calf", 3, "piglet"], [7, "filly"]))

3、分析一个数组包含的多个json格式对象,是否含有另一个json格式的对象的内容。
Where art thou

function whereAreYou(collection, source) {
   // What's in a name?
   var arr = [];
   // Only change code below this line
   var value=Object.keys(source);
   for(var i=0;i<collection.length;i++){
      if(Object.keys(collection[i]).length>=Object.keys(source).length){
         var flag=true;
         for(var key in source){
            if(collection[i].hasOwnProperty(key) ){
               if(collection[i][key]!=source[key]){
                  flag=false;
               }
            }else{
               flag=false;
            }
         }
         if(flag){
            arr.push(collection[i]);
         }
      }
   }
   // Only change code above this line
   return arr;
}
console.log(whereAreYou([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 }))

whereAreYou([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" })should return [{ first: "Tybalt", last: "Capulet" }].
whereAreYou([{ "a": 1 }, { "a": 1 }, { "a": 1, "b": 2 }], { "a": 1 }) should return [{ "a": 1 }, { "a": 1 }, { "a": 1, "b": 2 }].
whereAreYou([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 }) should return [{ "a": 1, "b": 2 }, { "a": 1, "b": 2, "c": 2 }].
whereAreYou([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "c": 2 }) should return [{ "a": 1, "b": 2, "c": 2 }].

4、搜索指定字符串,替换成指定字符串
Search and Replace

function myReplace(str, before, after) {
   var afterWord;
   if((before.charCodeAt(0)>=65)&&(before.charCodeAt(0)<=90)){
      console.log(1);
      afterWord=after.replace(after.charAt(0),after.charAt(0).toUpperCase());
   }else{
      afterWord=after;
   }
   return str.replace(before,afterWord);
}
console.log(myReplace("Let us go to the store", "store", "mall"))

注意首字母大写

5、拉丁猪算法,如果一个字符串包含元音字母aeiou,就把元音字母以前的字符串剪切到末尾,并且加上ay,如果首字母就是元音字母,就在末尾加上way
Pig Latin

function translatePigLatin(str) {
   var yuanArr=["a","e","i","o","u","A","E","I","O","U"];
   var index=0;
   var result="";
   var word1="";
   var word2="";
   for(var i=0;i<str.length;i++){
      if(yuanArr.indexOf(str[i])>-1){
         index=i;
         break;
      }
   }
   if(index>0){
      word1=str.substr(0,index);
      word2=str.substr(index,str.length-index);
      result=word2+word1+"ay";
   }else if(index===0){
      result=str+"way";
   }
   return result;
}
console.log(translatePigLatin("algorithm"))
console.log(translatePigLatin("california"))

6、DNA配对,根据A-T C-G这样配对
DNA Pairing

function pairElement(str) {
   var arryA=["A","T","C","G"];
   var arryB=["T","A","G","C"];
   var word=str.split("");

   var index=0;
   var arrAll=[];
   for(var i=0;i<word.length;i++){
      for(var j=0;j<arryA.length;j++){
         if(word[i]===arryA[j]){
            index=j;
         }
      }
      var arrOne=[];
      arrOne[0]=word[i];
      arrOne[1]=arryB[index];
      arrAll.push(arrOne);
   }
   return arrAll;
}
console.log(pairElement("GCG"))

pairElement("ATCGA") should return[["A","T"],["T","A"],["C","G"],["G","C"],["A","T"]]

pairElement("TTGAG") should return[["T","A"],["T","A"],["G","C"],["A","T"],["G","C"]].

7、识别一个字符串按照字母顺序少了哪一个字母

function fearNotLetter(str) {
   var arryA=[];
   var word=str;
   var index=0;
   var letter;
   var flag=0;
   for(var i=0;i<word.length;i++){
      arryA.push(word.charCodeAt(i));
   }
   flag=arryA[0];
   for(var j=0;j<arryA.length;j++){
      if(arryA[j]!=flag){
         index=arryA[j]-1;//取得不相同字母的上一位,-1取得失去的那一个
         break;//只要有一个不同,马上停止
      }
      flag++;
   }
   if(index!=0){
      letter=String.fromCharCode(index);
   }else{
      letter=undefined;
   }
   return letter;
}
console.log(fearNotLetter("abcdefghjklmno"));
fearNotLetter("abce") should return "d".
fearNotLetter("bcd") should return undefined.

8、判断参数是否是布尔类型
Boo who

function booWho(bool) {
   // What is the new fad diet for ghost developers? The Boolean.
   var word=bool;
   if(word===true && word===false){
      return true;
   }else{
      return false;
   }
}
console.log(booWho(null));

9、多个数组(包括二维数组)进行合并去重
Sorted Union

function uniteUnique(arr1, arr2, arr3) {
   var newArray=[];
   var allArray=Array.prototype.concat.apply([], arguments)
   for(var i=0;i<allArray.length;i++){
      if(newArray.indexOf(allArray[i])===-1){
         newArray.push(allArray[i]);
      }
   }
   return newArray;
}
console.log(uniteUnique([1, 3, 2], [1, [5]], [2, [4]]));

重点:由于有多个数组参数,需要用Array.prototype.concat.apply([],arugument)进行合并,用apply的原因是支持第二个参数为数组形式的

显示全文