FreeCodeCamp中級算法題答案

Diff Two Arrays

比較兩個數組,而後返回一個新數組,該數組的元素爲兩個給定數組中全部獨有的數組元素。換言之,返回兩個數組的差別。html

function diff(arr1, arr2) {
   var a1=arr1.filter(function(val){
        return arr2.indexOf(val)< 0;
   });
   var a2=arr2.filter(function(val){
       return arr1.indexOf(val)< 0;
   });
   return a1.concat(a2);
}

diff([1, 2, 3, 5], [1, 2, 3, 4, 5]);

Roman Numeral Converter

將給定的數字轉換成羅馬數字。
全部返回的 羅馬數字 都應該是大寫形式。
可參考Here數組

function convert(num) {
  var nums = [1000,900,500,400,100,90,50,40,10,9,5,4,1];
  var romans =["m","cm","d","cd","c","xc","l","xl","x","ix","v","iv","i"];
  var str = '';
  nums.forEach(function(item,index,array){
    while(num >= item){
      str += romans[index];
      num -= item;
    }
  });
  
 return str.toUpperCase();
}
convert(36);

Where art thou

寫一個 function,它遍歷一個對象數組(第一個參數)並返回一個包含相匹配的屬性-值對(第二個參數)的全部對象的數組。若是返回的數組中包含 source 對象的屬性-值對,那麼此對象的每個屬性-值對都必須存在於 collection 的對象中。ui

例如,若是第一個參數是 [{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }],第二個參數是 { last: "Capulet" },那麼你必須從數組(第一個參數)返回其中的第三個對象,由於它包含了做爲第二個參數傳遞的屬性-值對。翻譯

//法一
function where(collection, source) {
  var keys =  Object.keys(source);
  return collection.filter(function(obj){
      return keys.every(function(item){
          return obj.hasOwnProperty(item) && obj[item] === source[item];
      });
  });
}
//法二
function where(collection, source) {
  var keys =  Object.keys(source);
  return collection.filter(function(obj){
      return keys.every(function(item){
          return obj.hasOwnProperty(item) && obj[item] === source[item];
      });
  });
}

where([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

Search and Replace

使用給定的參數對句子執行一次查找和替換,而後返回新句子。第一個參數是將要對其執行查找和替換的句子。第二個參數是將被替換掉的單詞(替換前的單詞)。第三個參數用於替換第二個參數(替換後的單詞)。
注意:替換時保持原單詞的大小寫。例如,若是你想用單詞 "dog" 替換單詞 "Book" ,你應該替換成 "Dog"。code

//法一
function myReplace(str, before, after) {
    if(before[0] === before[0].toUpperCase()){
        after = after[0].toUpperCase() + after.slice(1);
    }
    str = str.replace(before,after);
    return str;
}


//法二
function myReplace(str, before, after) {
  var re = /^[A-Z]/;
  if(re.test(before.charAt(0))){
    after = after.charAt(0).toUpperCase() + after.slice(1);
  }
  str = str.replace(before,after);
  return str;
}
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");

Pig Latin

把指定的字符串翻譯成 pig latin
Pig Latin 把一個英文單詞的第一個輔音或輔音叢(consonant cluster)移到詞尾,而後加上後綴 "ay"。
若是單詞以元音開始,你只須要在詞尾添加 "way" 就能夠了。htm

function translate(str) {
    var myStr = '';
    var regex = /[aeiou]/gi;
    if(str[0].match(regex)){
        myStr = str + 'way';
    }else{
        var index = str.indexOf(str.match(regex)[0]);
        myStr = str.substr(index) + str.substring(0,index) + 'ay';
    }
  return myStr;
}

translate("consonant");//onsonantcay

DNA Pairing

DNA 鏈缺乏配對的鹼基。依據每個鹼基,爲其找到配對的鹼基,而後將結果做爲第二個數組返回。
Base pairs(鹼基對) 是一對 AT 和 CG,爲給定的字母匹配缺失的鹼基。
在每個數組中將給定的字母做爲第一個鹼基返回。
例如,對於輸入的 GCG,相應地返回 [["G", "C"], ["C","G"],["G", "C"]]
字母和與之配對的字母在一個數組內,而後全部數組再被組織起來封裝進一個數組。對象

function pair(str) {
  var arr = str.split('');
  var pair = '';
  return arr.map(function(item){
      switch(item){
          case 'C':
              pair = 'G';
            break;
          case 'G':
              pair = 'C';
            break;
        case 'A':
            pair = 'T';
            break;
        case 'T':
            pair = 'A';
             break;
      }
      return [item,pair];
  });
}

pair("GCG");

Missing letters

從傳遞進來的字母序列中找到缺失的字母並返回它。
若是全部字母都在序列中,返回 undefined。排序

法一:
    var arr = str.split('');
    for(var i = 0;i < arr.length;i++){
        var minus = arr[i+1].charCodeAt() - arr[i].charCodeAt();/後項減去前項/
        if( minus > 1){
            return String.fromCharCode(arr[i].charCodeAt()+1);
        }
    }
法二:
function fearNotLetter(str) {
    var compare = str.charCodeAt(0),missing;
    str.split('').map(function(item,index){
        if(str.charCodeAt(index) === compare){
            ++ compare;
        }else{
            missing = String.fromCharCode(compare);
        }
    });
    return missing;
}
fearNotLetter("abce");

Boo who

檢查一個值是不是基本布爾類型,並返回 true 或 false。
基本布爾類型即 true 和 false。ip

function boo(bool) {
 return typeof bool === 'boolean';
}

boo(true);

Sorted Union

寫一個 function,傳入兩個或兩個以上的數組,返回一個以給定的原始數組排序的不包含重複值的新數組。
例如:unite([1, 3, 2], [5, 2, 1, 4], [2, 1]) 應該返回 [1, 3, 2, 5, 4]。字符串

function unite(arr1, arr2, arr3) {
  var args = Array.from(arguments);
  var arr = args.reduce(function(prev,cur){
    return prev.concat(cur);
  });
  return arr.filter(function(item,index,arr){
    return arr.indexOf(item) === index;  
  });
}
unite([1, 3, 2], [5, 2, 1, 4], [2, 1]);

Convert HTML Entities

將字符串中的字符 &、<、>、" (雙引號), 以及 ' (單引號)轉換爲它們對應的 HTML 實體。

法一
function convert(str) {
  str = str.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")
           .replace(/"/g,"&quot;").replace(/'/g,"&apos;");
  return str;
}
convert("Dolce & Gabbana");
法二:
function convert(str) {
    var htmlEntities={
        '&':'&amp;',
        '<':'&lt;',
        '>':'&gt;',
        '\"':'&quot;',
        '\'':'&apos;',
    };
    return str.split('').map(function(entity){
        return htmlEntities[entity] || entity;
    }).join('');
}
convert("Dolce & Gabbana");
相關文章
相關標籤/搜索